<?php
session_name('super_admin_session');
if (!is_dir(dirname(__DIR__) . '/session_data/super')) { mkdir(dirname(__DIR__) . '/session_data/super', 0700, true); } session_save_path(dirname(__DIR__) . '/session_data/super');
session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);
session_start();
error_reporting(0);
ini_set('display_errors', 1);

include('includes/dbconnection.php');
require_once 'includes/session_term_helper.php';
$stResult = resolveCurrentSessionTerm($con);
$currentSessionName = $stResult['session_name'];
$currentTermName    = $stResult['term_name'];
include('includes/flash.php');
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// required files
require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';
require 'phpqrcode/qrlib.php'; // Ensure you have the PHP QR Code library

// Check if admin is logged in
if (!isset($_SESSION['sid']) || strlen($_SESSION['sid']) == 0) {
    header('location:logout.php');
    exit;
}

try {
    // Fetch failed emails
    $sql = "SELECT ef.id, ef.student_id, ef.reason, ef.timestamp, s.studentName, s.studentno, s.email
            FROM email_failure ef
            JOIN students s ON ef.student_id = s.id 
            ORDER BY ef.timestamp DESC";
    $stmt = $dbh->prepare($sql);
    $stmt->execute();
    $failedEmails = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Handle resend email request
    if (isset($_GET['resend_id']) && is_numeric($_GET['resend_id'])) {
        $email_id = intval($_GET['resend_id']);
        resendEmail($email_id);
    }
} catch (PDOException $e) {
    die("Database error: " . $e->getMessage());
}

// Resend Email Function
function resendEmail($email_id) {
    global $dbh;

    try {
        $sql = "SELECT ef.student_id FROM email_failure ef WHERE ef.id = :email_id";
        $stmt = $dbh->prepare($sql);
        $stmt->bindParam(':email_id', $email_id, PDO::PARAM_INT);
        $stmt->execute();
        $failedEmail = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($failedEmail) {
            $student_id = $failedEmail['student_id'];

            $sql = "SELECT s.email, s.studentName, s.studentno FROM students s WHERE s.id = :student_id";
            $stmt = $dbh->prepare($sql);
            $stmt->bindParam(':student_id', $student_id, PDO::PARAM_INT);
            $stmt->execute();
            $studentDetails = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($studentDetails) {
                $email = $studentDetails['email'];
                $student_name = $studentDetails['studentName'];
                $studentno = $studentDetails['studentno'];

                if (sendEmailWithAttachment($email, $student_name, $studentno)) {
                    $delete_sql = "DELETE FROM email_failure WHERE id = :email_id";
                    $delete_stmt = $dbh->prepare($delete_sql);
                    $delete_stmt->bindParam(':email_id', $email_id, PDO::PARAM_INT);
                    $delete_stmt->execute();

                    flash_alert('Email resent successfully!', 'failed-email.php');
        header('Location: failed-email.php'); exit;
                } else {
                    flash_alert('Failed to resend email.');
                }
            } else {
                flash_alert('Student details not found.');
            }
        } else {
            flash_alert('Failed email record not found.');
        }
    } catch (PDOException $e) {
        flash_alert('Error: ' . $e->getMessage());
    }
}


// Function to send email with PDF attachment using PHPMailer
function sendEmailWithAttachment($email, $student_name,$studentno) {

    global $dbh;

    // Fetch student details
    $sql = "SELECT studentno, stream,studentName, academic_session, section FROM students WHERE studentno = :studentno";
    $stmt = $dbh->prepare($sql);
    $stmt->bindParam(':studentno', $studentno);
    $stmt->execute();
    $student = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$student) {
        return false; // Student not found
    }
    else{
    $newAdmissionNo1 = $student['studentno'];
    $school_type = $student['stream'];


    $sql = "SELECT * FROM students WHERE studentno = ?";
    $stmt = $dbh->prepare($sql);
    $stmt->execute([$newAdmissionNo1]);
    $student = $stmt->fetch(PDO::FETCH_ASSOC);
    
    
    $formattedDate = date('d-m-Y', strtotime($student['postingDate']));
     
   // Generate QR code with student details
   $qrText = "This admission letter is valid and authorized by Adesina College, Ibadan to 
   Admission No: {$student['studentno']}
   Student Name: {$student['studentName']}
   Class: {$student['class']}
   Session Admitted: {$student['academic_session']}
   Thanks for verifying this admission letter.";
   $qrFilePath = 'temp_qr.png';
   QRcode::png($qrText, $qrFilePath, QR_ECLEVEL_L, 4); // Generate QR code

    // Generate the PDF content (same as before)
    $htmlContent = "
    <!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<title>Admission Letter</title>
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css'> <!-- Font Awesome -->
<style>
body {
font-family: Times New Roman, serif;
margin: 0;
padding: 0;
}
.container {
width: 80%;
margin: auto;
border: 2px dotted #000;
padding: 20px;
line-height: 1.6;
}
.header {
text-align: center;
padding: 0;
margin: 0;
}
.header img {
height: 100px;
margin: 0;
padding: 0;
}
.header h1 {
font-size: 35px;
font-weight: bold;
margin: 0;
padding: 0;
}
.header b {
font-size: 10px;
margin: 0;
padding: 0;
}
.title {
text-align: center;
font-size: 18px;
font-weight: bold;
margin: 20px 0;
}
.details {


width: 100%;

}
.child{
float: left;
width: 50%;

}
.left {
margin-left: 100%;

font-size: 14px;
font-weight: bold;
}
.right {
margin-left: 50%;

font-size: 14px;
font-weight: bold;
}
.content {
text-align: justify;
}
.signature {
margin-top: 50px;
text-align: center;
font-size: 14px;
}
.signature img {
height: 100px;
margin-top: 10px;
}
.signature p {
margin: 0;
text-align: center;
}
.congratulations {
text-align: center;
margin-top: 30px; /* Optional margin for spacing */
}
.congratulations p {
font-family: 'brushscriptmt';
font-size: 40px;
font-weight: bold;
margin: 0;
}
/* Prevent automatic page break */
@page {
margin: 10mm;
}
</style>
</head>
<body>

<div class='container'>
<!-- Header with School Logo and Details -->
<div class='header'>
<h1>ADESINA COLLEGE, IBADAN</h1>
<b><i> 2, Kolawole Ajadi Crescent, Alagbayun, Akobo, Ibadan<br>
www.adesinacollegeibadanonline.com<br>08055481880, 08023240174</i></b><br>
<img src='company/logo.jpeg' alt='logo' height ='120'><br>
<b style ='font-size:9;'>(Government Approved)</b>
</div>
<br><br>

<!-- Details Section -->
<div class='details'>
<div class='child'>
<div class='left'><strong>Admission No:</strong> {$student['studentno']}</div>
</div>
<div class='child'>
<div class='right'><strong>Date:</strong> {$formattedDate}</div>
</div>
</div>
<br>
<!-- Admission Letter Title -->
<div class='title'>
ADMISSION LETTER
</div>

<!-- Main Content of the Letter -->
<div class='content'>
<p>Dear {$student['studentName']},</p>
<p>
I am pleased to inform you that you have been offered a provisional admission into 
<strong>{$student['section']}</strong> for the year {$student['academic_session']} academic session.
</p>
<p>
Be informed that your full admission is subject to the full payment of the school fee, 
submission of one recent passport photograph and medical reports.
</p>

<p>
For official documentation, this admission letter is subject to verification by scanning the barcode below.
</p>
</div>

<!-- Congratulations Section -->
<div class='congratulations'>
<p>
Congratulations<br>
<img src='{$qrFilePath}' alt='QR Code' width ='105' height ='105'><!-- QR Code on top of the signature -->
</p>
</div>

<!-- Signature Section with QR Code -->
<div class='signature'>
<b>Signed,</b><br>
<b>School Management</b>
</div>
</div>

</body>
</html>
";

    
    

    // Generate the PDF using mPDF
    include("vendor/autoload.php");
    $mpdf = new \Mpdf\Mpdf(['format' => 'A4']);
    $mpdf->WriteHTML($htmlContent);
    // Set PDF metadata
    $mpdf->SetTitle("Admission Letter - {$student['studentName']}");
    $mpdf->SetAuthor("Adesina College");

    // Disable page breaks to keep content on one page
    $mpdf->SetWatermarkImage('company/logo1.jpeg', 0.1); // 0.1 for light opacity, 'F' for fit to page
    $mpdf->showWatermarkImage = true;
    $pdfContent = $mpdf->Output('', 'S'); // Get the PDF as a string for email attachment

    // Send the email using PHPMailer
     $mail = new PHPMailer(true);
        try {
          $mail->isSMTP();
          $mail->Host = 'mail.acionlineportal.com.ng';
          $mail->SMTPAuth = true;
          $mail->Username = 'noreply@acionlineportal.com.ng'; // SMTP username
          $mail->Password = 'acionlineportal';          // SMTP password
          $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
          $mail->Port = 465;
          $mail->Timeout = 10;
  
          $mail->setFrom('noreply@acionlineportal.com.ng', 'ADESINA COLLEGE');
        $mail->addAddress($email, $student_name);

        $mail->isHTML(true);
        $mail->Subject = 'ACI SCHOOL FEES PAYMENT APPROVAL NOTIFICATION';
        $mail->Body = "
        <html>
        <body>
            <div style='max-width: 600px; margin: auto; font-family: Arial, sans-serif; background-color: #f4f4f4; padding: 20px;'>
                 



            <h1 style='color: #ffffff; text-align: center;padding: 10px 0; background-color: #4CAF50;'>Payment Approved</h1>
                <p>Dear $student_name,</p>
                <p>We are pleased to inform you that your payment  has been successfully confirmed and
                Admission Number issued successfully. Congratulations !!!</p>
                <hr>
                 <p><strong>Admission Number:</strong> {$student['studentno']}</p>
                <p><strong>Password:</strong> 12345678</p>

                 <p>Please note that your Admission Number will  be required to login into your student portal</p>
                <hr>
                
                <p>Your admission letter is attached. Please log into your student portal to download your receipt.</p>
                <p>It is essential that you bring a printed copy of your receipt and admission letter for uniform collection and documentation.</p>
                <p>Thank you!</p>
                <hr>
                <p>If you have any questions or need further assistance, please feel free to reach out to us. Thank you!</p>
                <hr>
        <center>
            <p>Adesina College Ibadan &copy; " . date("Y") . ". All Rights Reserved.</p>
        </center>
        <hr>
            </div>
        </body>
        </html>"; 
        // Attach PDF 
        $boardinglist = ('ACI_BOARDING_LIST.pdf');
        $mail->addStringAttachment($pdfContent, 'Admission_Letter.pdf');
        if ($school_type =='Boarding' || $school_type=='boarding' || $school_type=='BOARDING'){
        $mail->addAttachment($boardinglist, 'ACI_BOARDING_LIST.pdf');
        }                       

        $mail->addStringAttachment($pdfContent, 'Admission_Letter.pdf');

        $mail->send();
        return true; // Email sent successfully
    } catch (Exception $e) {
        error_log("Mailer Error: {$mail->ErrorInfo}");
        return false; // Email sending failed
    }
}
}

?>


<!DOCTYPE html>
<html>
<?php @include("includes/head.php"); ?>
<body class="hold-transition sidebar-mini layout-fixed">
  <div class="wrapper">
    <!-- Navbar -->
    <?php @include("includes/header.php"); ?>
    <!-- /.navbar -->

    <!-- Main Sidebar Container -->
    <?php @include("includes/sidebar.php"); ?>

    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
      <!-- Content Header (Page header) -->
        <section class="content-header premium-header">
    <div class="container-fluid">
        <div class="header-glass-card">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <div class="title-section">
                        <div class="icon-box bg-primary-gradient shadow-sm">
                            <i class="fas fa-envelope"></i>
                        </div>
                        <div>
                            <h1 class="premium-title text-primary">
                                Email Management
                                <span class="premium-subtitle text-secondary">Manage Failed Emails</span>
                            </h1>
                    <div class="mt-1">
                      <?php if ($currentSessionName): ?>
                        <span class="badge badge-primary mr-1">
                          <i class="fas fa-calendar-alt"></i>
                          <?= htmlspecialchars($currentSessionName) ?>
                        </span>
                      <?php endif; ?>
                      <?php if ($currentTermName): ?>
                        <span class="badge badge-success">
                          <i class="fas fa-bookmark"></i>
                          <?= htmlspecialchars($currentTermName) ?>
                        </span>
                      <?php else: ?>
                        <span class="badge badge-warning">
                          <i class="fas fa-exclamation-triangle"></i> No active term
                        </span>
                      <?php endif; ?>
                    </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb premium-breadcrumb">
                            <li class="breadcrumb-item"><a href="dashboard.php" class="text-primary">Home</a></li>
                            <li class="breadcrumb-item active" aria-current="page">Failed Emails</li>
                        </ol>
                    </nav>
                </div>
            </div>
        </div>
    </div>
</section>

      <!-- Main content -->
      <section class="content">
        <div class="container-fluid">
          <div class="row">
            <div class="col-12">
              <div class="card">
                <div class="card-header">
                  <h3 class="card-title">Failed Emails</h3>
                  <div class="card-tools">
                                    
                  </div>
                </div>
                <!-- /.card-header -->

                <!-- Payment Filter Form -->
<div class="card-body">
    <!-- Date filter form -->
   
</div>


<!-- Payment Table -->
<div class="card-body mt-2">
    <table id="example1" class="table table-bordered table-hover">
    <thead>
                <tr>
                    <th>#</th>
                    <th>Student Name</th>
                    <th>Email Address</th>
                    <th>Reason</th>
                    <th>Timestamp</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                
                <?php     $email1 = htmlspecialchars($email['email'] ?? ''); 
                $studentno = htmlspecialchars($student['studentno'] ?? ''); // Handle null/empty email

                if (count($failedEmails) > 0) {
                    $i = 1;
                    foreach ($failedEmails as $email) { ?>
                        <tr>
                            <td><?php echo $i++; ?></td>
                            <td><?php echo htmlspecialchars($email['studentName']); ?></td>
                            <td><?php echo $email1; ?></td>
                            <td><?php echo htmlspecialchars($email['reason']); ?></td>
                            <td><?php echo htmlspecialchars($email['timestamp']); ?></td>
                            <td>
                                <!-- Resend Button -->
                                <a href="failed-email.php?resend_id=<?php echo $email['id']; ?>" class="btn btn-primary btn-sm">Resend</a>
                            </td>
                        </tr>
                    <?php } 
                } else { ?>
                    <tr>
                        <td colspan="6" class="text-center">No failed emails found.</td>
                    </tr>
                <?php } ?>
            </tbody>
        </table>
</div>
                <!-- /.card-body -->
              </div>
              <!-- /.card -->
            </div>
          </div>
        </div>
      </section>
    </div>
    <?php @include("includes/footer.php"); ?>
  </div>

  <?php @include("includes/foot.php"); ?>

</body>
</html>


