<?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;
use Dotenv\Dotenv;
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


// Load Composer dependencies
require_once 'vendor/autoload.php';
// Load environment variables
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

$school_name = $_ENV['SCHOOL_NAME'];
$school_address = $_ENV['SCHOOL_ADDRESS'];
$prefix = $_ENV['Admission_prefix'];
$school_website = $_ENV['BASE_URL'];
$logo = $_ENV['WEBSITE_LOGO'];

if (strlen($_SESSION['sid']) == 0) {
    header('location:logout.php');
} else {

    if (isset($_POST['submit'])) {
        $admissionNo = $_POST['fullname'];
        $stdname = $_POST['stdname'];
        $email = $_POST['email'];


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

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

            // Format posting dat

            $formattedDate = date('M j, Y', strtotime($studentData['postingDate']));
            // Generate QR code with student details
            $qrText = "This admission letter is valid and authorized by $school_name, 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>
<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;
        }
        .content p {
            font-size: 15px;
        }
        .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>" . strtoupper($school_name) . "</h1>
 <b><i>$school_address</i></b><br>
 <img src=$logo 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: {$studentData['studentno']}</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>
     We are pleased to inform you that you have been offered a provisional admission into <strong>{$studentData['class']} {$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 fees, 
     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($school_name);

            // Disable page breaks to keep content on one page
            $mpdf->SetWatermarkImage($logo, 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 {
                $mail->isSMTP();
                $mail->Host = $_ENV['SMTP_HOST'];
                $mail->SMTPAuth = true;
                $mail->Username = $_ENV['SMTP_NO_REPLY'];
                $mail->Password = $_ENV['SMTP_NO_REPLY_PASSWORD'];
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
                $mail->Port = $_ENV['SMTP_PORT'];
                $mail->Timeout = 10;

                $mail->setFrom($_ENV['SMTP_NO_REPLY'], $_ENV['SCHOOL_NAME']);
                $mail->addAddress($email, $stdname);
                $mail->isHTML(true);
                $mail->Subject = $school_name . ' - ADMISSION LETTER';
                $mail->Body = "
                        <html>
                        <body>
                            <div style='max-width: 600px; margin: auto; font-family: Arial, sans-serif; background-color: #f4f4f4; padding: 20px;'>
                                 
                
            
                                <p>Dear <strong>{$studentData['studentName']}</strong>,</p>
                                <p>Congratulations!!!</p>
                                <p>We are pleased to inform you that your payment has been confirmed and
                                Admission Number issued successfully. </p>
                                <hr>
                                 <p><strong>Admission Number:</strong> $admissionNo</p>
                                <p><strong>Password:</strong> 12345678</p>
                                <p>Click <a href='$school_website'>here</a> to log in.</p>


                                 <p>Please note that your Admission Number will  be required to log into your student portal</p>
                                <hr>
                                <h5>Admission Details</h5>
                                <hr>
                                <p><strong> Class: {$studentData['section']}</p>
                                <p><strong>Session Admitted: {$studentData['academic_session']}</p>
                                <p>Your admission letter has been attached below in this mail.<br>
                                 Please log into your student portal to download your receipt.</p>
                                <p style ='color:red;'>It is essential that you bring a printed copy of the school receipt and admission letter for your enrollment 
                                process, documentation and uniform collection upon resumption.</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>$school_name &copy; " . date("Y") . ". All Rights Reserved.</p>
                        </center>
                        <hr>
                            </div>
                        </body>
                        </html>";
                // Attach PDF 
                $mail->addStringAttachment($pdfContent, 'Admission_Letter.pdf');
                $mail->send();

                flash_alert('Admission letter and email sent successfully!', 'sendadmissionletter.php');
                header('Location: sendadmissionletter.php');
                exit;
            } catch (Exception $e) {
                flash_alert('Email could not be sent. Please try again.');
            }
        } 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-folder-open"></i>
                                    </div>
                                    <div>
                                        <h1 class="premium-title text-primary">
                                            Document Management
                                            <span class="premium-subtitle text-secondary">Admission Letter</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 active" aria-current="page">Send Admission Letter
                                        </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">
                                    <h5 class="card-title font-weight-bold"><i class="fas fa-envelope"></i> Send
                                        Admission Letter</h5>
                                </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-6">
                                                <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 WHERE status =1");
                                                    //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-6">
                                                <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>
                                        <div class="row">
                                            <div class="form-group col-md-6">
                                                <label for="age">Email</label>
                                                <input type="email" class="form-control" id="email" name="email"
                                                    placeholder="Email Only" required>
                                            </div>
                                        </div>



                                        <!-- /.card-body -->
                                        <div class="card-footer">
                                            <center>
                                                <button type="submit" name="submit" id="submit" class="btn btn-primary">
                                                    <i class="fas fa-check-circle"></i> Send Admission Letter</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>