<?php
include('includes/session.php');
error_reporting(0);
include('includes/dbconnection.php');

include('phpqrcode/qrlib.php'); // Include the QR code library

require_once('vendor/autoload.php'); // Include mPDF

use Mpdf\Mpdf;

use Dotenv\Dotenv;

// Load environment variables
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

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

// Get student ID from request and validate
$student_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$student_id) {
    die("Invalid student ID.");
}

// Verify the database connection
if (!$con) {
    die("Database connection error: " . mysqli_connect_error());
}

// Fetch all student details
$sql = "SELECT * FROM students WHERE id = ?";
$stmt = $con->prepare($sql);


if (!$stmt) {
    die("Database query error: " . $con->error);
}

$stmt->bind_param("i", $student_id);
$stmt->execute();
$result = $stmt->get_result();
$studentData = $result->fetch_assoc();
$stmt->close();

if (!$studentData) {
    die("Student not found.");
}

// 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 $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>
";

// Include the mPDF library and generate the PDF
require_once __DIR__ . '/vendor/autoload.php';
$mpdf = new \Mpdf\Mpdf(['format' => 'A4', 'default_font_size' => 12, 'default_font' => 'Times New Roman']);

// Set PDF metadata
$mpdf->SetTitle("Admission Letter - {$studentData['studentName']}");
$mpdf->SetAuthor($school_name);

// Disable page breaks to keep content on one page
$mpdf->AddPageByArray(['margin-top' => 5, 'margin-bottom' => 5, 'margin-left' => 5, 'margin-right' => 5]);
$mpdf->SetWatermarkImage($logo, 0.1); // 0.1 for light opacity, 'F' for fit to page
$mpdf->showWatermarkImage = true;

// Write HTML to PDF
$mpdf->WriteHTML($htmlContent);

// Output the PDF as a download
$mpdf->Output($prefix.'_Admission_Letter.pdf', 'D');  // 'D' forces the download

// Clean up QR code image file after generation
unlink($qrFilePath);
?>
