<?php
session_name('mini_admin_session');
session_start();
error_reporting(0);
include('includes/dbconnection.php');
include('includes/flash.php');

require_once 'includes/session_term_helper.php';
$stResult = resolveCurrentSessionTerm($con);
$currentSessionName = $stResult['session_name'];
$currentTermName = $stResult['term_name'];

// Include PHPMailer and QR code libraries
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
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

$message_id = $_GET['id'];
$messageData = $_SESSION['message_data'];
if (strlen($_SESSION['sid']) == 0) {
    header('location:logoutmini.php');
} else {

    if (isset($_POST['disapprove'])) {

        $regno = $_POST['fullname'];
        $adno = $_POST['fullname'];
        $term = $_POST['term'];
        $session = $_POST['session'];
        $class = $_POST['class'];
        $school_type = $_POST['school_type'];
        $payment_type = $_POST['payment_type'];
        $pay_id = $_POST['pay_id'];
        $amount = $_POST['amount'];
        $payment_for = $_POST['pay_for'];
        $studentname = $_POST['stdname'];
        $sql = "SELECT * FROM students WHERE studentno =?";
        $stmt = $dbh->prepare($sql);
        $stmt->execute([$adno]);
        if ($stmt->rowCount() > 0) {

            // check student and email
            $fecthemail = $stmt->fetch(PDO::FETCH_ASSOC);
            $email = $fecthemail['email'];
            $id = $fecthemail['id'];
        }
        try {
            // Update the message status to 'disapproved' (set status = 2, assuming 2 indicates disapproval)
            $stmtDisapprove = $dbh->prepare("UPDATE message SET status = 2 WHERE id = :message_id AND status = 0 LIMIT 1");
            $stmtDisapprove->bindParam(':message_id', $message_id);
            $stmtDisapprove->execute();

            // Notify user via email about disapproval
            $mail = new PHPMailer(true);
            try {
                // SMTP configuration
                $mail = new PHPMailer(true);
                $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, $studentname);

                $mail->isHTML(true);
                $mail->Subject = 'ACI School Fees Payment Disapproval 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: #f44336;'>Payment Disapproved</h1>
                    <p>Dear $studentname,</p>
                    <p>We regret to inform you that your payment of NGN $amount has been disapproved.</p>
                    <p>Kindly bring your transaction receipt to school for verification of your payment.</p>
                    <p>Thank you!</p>
                    <hr>
                    <center>
                        <p>Adesina College Ibadan &copy; " . date("Y") . ". All Rights Reserved.</p>
                    </center>
                </div>
            </body>
            </html>";

                $mail->send();
                flash_alert('Payment disapproved and Email sent successfully!', 'pay11.php');
                header('Location: pay11.php');
                exit;
            } catch (Exception $e) {
                flash_alert('Payment disapproved, but email could not be sent. Please try again.', 'pay11.php');
                header('Location: pay11.php');
                exit;
            }
        } catch (Exception $e) {
            flash_alert('Something went wrong. Payment disapproval failed. Please try again.');
        }
    }



    if (isset($_POST['submit'])) {
        $admissionNo = $_POST['admissionNo'];
        $regno = $_POST['fullname'];
        $adno = $_POST['fullname'];
        $term = $_POST['term'];
        $session = $_POST['session'];
        $class = $_POST['class'];
        $school_type = $_POST['school_type'];
        $payment_type = $_POST['payment_type'];
        $pay_id = $_POST['pay_id'];
        $amount = $_POST['amount'];
        $payment_for = $_POST['pay_for'];
        $studentname = $_POST['stdname'];

        // Fetch student email
        $sql = "SELECT * FROM students WHERE studentno = ?";
        $stmt = $dbh->prepare($sql);
        $stmt->execute([$adno]);

        if ($stmt->rowCount() > 0) {
            $studentData = $stmt->fetch(PDO::FETCH_ASSOC);
            $email = $studentData['email'];
            $id = $studentData['id'];



            // Format posting date
            $formattedDate = date('M j, Y', strtotime($studentData['postingDate']));
            // Generate QR code with student details
            $qrText = "This admission letter is valid and authorized by Adesina College, Ibadan to 
             Admission No: {$studentData['studentno']}
             Student Name: {$studentData['studentName']}
             Class: {$studentData['class']}
             Session Admitted: {$studentData['academic_session']}
             Thanks for verifying this admission letter.";
            $qrFilePath = 'temp_qr.png';
            QRcode::png($qrText, $qrFilePath, QR_ECLEVEL_L, 4); // Generate QR code

            // Define the HTML content for the PDF
            $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'>Admission No: $admissionNo</div>
 </div>
 <div class='child'>
 <div class='right'>Date: {$formattedDate}</div>
</div>
</div>
<br>
<!-- Admission Letter Title -->
<div class='title'>
 ADMISSION LETTER
</div>

<!-- Main Content of the Letter -->
<div class='content'>
 <p>Dear <strong>{$studentData['studentName']}</strong>,</p>
 <p>
     I am pleased to inform you that you have been offered a provisional admission into<br> 
     <strong>{$studentData['section']}</strong> for the year {$studentData['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', 'default_font_size' => 12, 'default_font' => 'Times New Roman']);
            $mpdf->WriteHTML($htmlContent);

            // Set PDF metadata
            $mpdf->SetTitle("Admission Letter - {$studentData['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


            // Clean up QR code image file
            unlink($qrFilePath);

            // Attempt to send email before inserting payment
            $mail = new PHPMailer(true);
            try {
                // SMTP configuration
                $mail = new PHPMailer(true);
                $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, $studentname);

                // Email content
                $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 $studentname,</p>
                                <p>We are pleased to inform you that your payment of NGN $amount has been successfully confirmed and
                                Admission Number issued successfully. Congratulations !!!</p>
                                <hr>
                                 <p><strong>Admission Number:</strong> $admissionNo</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>
                                <h3>Payment Details</h3>
                                <hr>
                                <p><strong>Amount Paid:</strong> NGN $amount</p>
                                <p><strong>Class:</strong> $class</p>
                                <p><strong>Term:</strong> $term</p>
                                <p><strong>Session:</strong> $session</p>
                                <p><strong>Purpose of Payment:</strong> $payment_for</p>
                                <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->send();
                // Insert payment record
                $query = $dbh->prepare("INSERT INTO payment (studentno, studentName, Term, session, class, school_type, payment_type, pay_id, amount, pay_for, student_id) 
                                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $query->execute([$adno, $studentname, $term, $session, $class, $school_type, $payment_type, $pay_id, $amount, $payment_for, $id]);

                // Update message status
                // Update message status using the passed id
                if (!empty($message_id)) {
                    $stmtUpdate = $dbh->prepare("UPDATE message SET status = 1 WHERE id = :message_id AND status = 0 LIMIT 1");
                    $stmtUpdate->bindParam(':message_id', $message_id);
                    $stmtUpdate->execute();
                }


                // Update studentno with the new admission number in students table
                $updateQuery = "UPDATE students SET studentno = ? WHERE studentno = ?";
                $updateStmt = $dbh->prepare($updateQuery);
                $updateStmt->execute([$admissionNo, $adno]);

                unset($_SESSION['id']);
                unset($_SESSION['message_data']);

                flash_alert('Payment approved, Admission Number updated, and email sent successfully!', 'pay11.php');
                header('Location: pay11.php');
                exit;
            } catch (Exception $e) {
                flash_alert('Email could not be sent. Payment was not approved. Please try again.', 'pay11.php');
                header('Location: pay11.php');
                exit;
            }
        } else {
            flash_alert('Student not found. Please try again.');
        }
    }
}
?>

<!DOCTYPE html>
<html>
<?php @include("includes/head.php"); ?>

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

        <!-- Main Sidebar Container -->
        <?php @include("includes/sidebar2.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-wallet"></i>
                                    </div>
                                    <div>
                                        <h1 class="premium-title text-primary">
                                            Payment Management
                                            <span class="premium-subtitle text-secondary">Approval Request</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="dashboard1.php"
                                                class="text-primary">Home</a></li>
                                        <li class="breadcrumb-item">
                                            <rove href="approve1.php" class="text-primary">Approve Payment</a>
                                        </li>
                                        <li class="breadcrumb-item active" aria-current="page">Request Approval</li>
                                    </ol>
                                </nav>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

            <!-- Main content -->
            <section class="content">
                <div class="container-fluid">
                    <div class="row ">
                        <div class="col-md-12">
                            <!-- general form elements -->
                            <div class="card card-primary">
                                <div class="card-header">
                                    <h3 class="card-title">Pay Tuition Fees For Student without Admission No.</h3>
                                </div>
                                <!-- /.card-header -->
                                <!-- form start -->
                                <form role="form" method="post" enctype="multipart/form-data">
                                    <div class="card-body">
                                        <span style="color: brown">
                                            <h5>Student's Details</h5>
                                        </span>
                                        <hr>
                                        <div class="row">

                                            <div class="form-group col-md-4">
                                                <label for="sex">Admission No. | FullName</label>
                                                <select class="form-control" id="fullname" name="fullname"
                                                    onchange="passValue()" required>
                                                    <option value=""></option>
                                                    <?php
                                                    $result = mysqli_query($con, "SELECT studentno,studentName FROM students");
                                                    //fecth result
                                                    while ($row = mysqli_fetch_array($result)) {
                                                        echo "<option value =" . $row['studentno'] . ">" . $row['studentno'] . "|" . $row['studentName'] . "</option>";
                                                    }
                                                    ?>
                                                </select>
                                            </div>
                                            <div class="form-group col-md-4">
                                                <label for="age">Student's Fullname</label>
                                                <input type="text" class="form-control" id="stdname" name="stdname"
                                                    value="<?php echo $messageData['fullname']; ?>" required readonly>
                                            </div>
                                            <div class="form-group col-md-4">
                                                <label for="age">Term</label>
                                                <input type="text" class="form-control" id="term" name="term"
                                                    value="<?php echo $messageData['term']; ?>" required>


                                            </div>
                                            <div class="form-group col-md-4">
                                                <label for="sex">Session</label>
                                                <input type="text" class="form-control" id="session" name="session"
                                                    value="<?php echo $messageData['session']; ?>" required>


                                            </div>
                                            <div class="form-group col-md-4">
                                                <label for="age">Class</label>
                                                <input type="text" class="form-control" id="class" name="class"
                                                    value="<?php echo $messageData['class']; ?>" required>

                                            </div>

                                            <div class="form-group col-md-4">
                                                <label for="age">School Type</label>
                                                <input type="text" class="form-control" id="school_type"
                                                    name="school_type" value="<?php echo $messageData['school_type']; ?>"
                                                    required>

                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="form-group col-md-4">
                                                <label for="age">Payment Type</label>
                                                <select type="select" class="form-control" id="payment_type"
                                                    name="payment_type">
                                                    <option></option>
                                                    <option value="Full Payment">Full Payment</option>
                                                    <option value="Part Payment">Part Payment</option>
                                                </select>
                                            </div>
                                            <div class="form-group col-md-4">
                                                <label for="age">Payment ID</label>
                                                <input type="text" class="form-control" name="pay_id" id="pay_id" value="<?php
                                                function generate_pay_ID($length = 15)
                                                {
                                                    $char = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSQTUVWXYZ';
                                                    $charlength = strlen($char);
                                                    $randomString = '';
                                                    for ($i = 0; $i < $length; $i++) {
                                                        # code...
                                                        $randomString .= $char[rand(0, $charlength - 1)];
                                                    }
                                                    return $randomString;
                                                }
                                                $tid = generate_pay_ID();
                                                echo isset($pay_id) ? $pay_id : $tid ?>" required readonly>
                                            </div>

                                            <div class="form-group col-md-4">
                                                <label for="age">Payment For</label>
                                                <input type="text" class="form-control" id="pay_for" name="pay_for"
                                                    value="<?php echo $messageData['purpose']; ?>" required>
                                            </div>

                                        </div>
                                        <div class="row">
                                            <div class="form-group col-md-4">
                                                <label for="age">Amount to Pay</label>
                                                <input type="number" class="form-control" id="amount" name="amount"
                                                    placeholder="Amount" value="<?php echo $messageData['amount']; ?>"
                                                    required>
                                            </div>

                                            <div class="form-group col-md-4">
                                                <label for="admissionNo">New Admission No.</label>
                                                <input type="text" class="form-control" id="admissionNo"
                                                    name="admissionNo" oninput="this.value = this.value.toUpperCase()"
                                                    required>
                                            </div>
                                        </div>


                                        <!-- /.card-body -->
                                        <div class="card-footer">
                                            <center>
                                                <button type="submit" name="submit" id="submit"
                                                    class="btn btn-primary">Approve</button>
                                                <button type="submit" name="disapprove" id="disapprove"
                                                    class="btn btn-danger">Disapprove</button>
                                            </center>
                                        </div>
                                </form>
                            </div>
                            <!-- /.card -->
                        </div>
                        <!-- /.col -->
                    </div>
                    <!-- /.row -->
                </div>
                <!-- /.container-fluid -->
            </section>
            <!-- /.content -->
        </div>
        <!-- /.content-wrapper -->
        <?php @include("includes/footer.php"); ?>

    </div>


    <!-- ./wrapper -->
    <?php @include("includes/foot.php"); ?>
    <script src="dist/js/jquery-3.7.1.min.js"></script>
    <script src="dist/js/select2.min.js"></script>

    <script>
        // In your Javascript (external .js resource or <script> tag)
        $(document).ready(function () {
            $('#fullname').select2();
        });

        function passValue() {
            var value = document.getElementById("fullname").value;
            if (value) {
                // Make an AJAX request to the PHP script
                var xhr = new XMLHttpRequest();
                xhr.open("GET", "fetch_value.php?option=" + encodeURIComponent(value), true);
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        // Parse the JSON response
                        var response = JSON.parse(xhr.responseText);
                        // Fill the fields with the returned values
                        document.getElementById("stdname").value = response.studentName || ''; // Assuming you also want to fill this field
                        document.getElementById("class").value = response.class || '';
                        document.getElementById("school_type").value = response.stream || '';
                    }
                };
                xhr.send();
            } else {
                document.getElementById("stdname").value = '';
                document.getElementById("class").value = '';
                document.getElementById("school_type").value = '';
                alert('Please select an option.');
            }
        }
    </script>
</body>

</html>