<?php
include('includes/dbconnection.php');
include('includes/flash.php');
require_once __DIR__ . '/vendor/autoload.php'; // mPDF autoload
// Auto-detect and fix only if needed
if (php_sapi_name() !== 'cli') { // Ignore if running from CLI (optional)
    if (
        interface_exists('PsrExt\Http\Message\RequestInterface', false) &&
        interface_exists('Psr\Http\Message\RequestInterface', false) &&
        !is_a('PsrExt\Http\Message\RequestInterface', 'Psr\Http\Message\RequestInterface', true)
    ) {
        class_alias('Psr\Http\Message\RequestInterface', 'PsrExt\Http\Message\RequestInterface');
    }
}

use Mpdf\Mpdf;
use Dotenv\Dotenv;

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

$school_name = $_ENV['SCHOOL_NAME'];
$logo = $_ENV['WEBSITE_LOGO'];
$logo1 = $_ENV['WEBSITE_LOGO'];
$address = $_ENV['id_address'];
$email = $_ENV['SCHOOL_EMAIL'];
$phone = $_ENV['SCHOOL_PHONE'];
$principalSignature = $_ENV['PRINCIPAL_SIGNATURE'];

$class = $_GET['class'];
$section = $_GET['section'];

// Students Query
$studentsQuery = mysqli_query($con, "SELECT * FROM students WHERE class = '$class' AND section = '$section' AND status =1");

// Create a unique download folder
$downloadFolder = 'id_cards/' . uniqid('id_card_', true);
mkdir($downloadFolder, 0777, true);

while ($student = mysqli_fetch_assoc($studentsQuery)) {
    $studentName = preg_replace('/[^A-Za-z0-9\-]/', '_', $student['studentName']); // sanitize file name
    $studentPhoto = "studentimages/" . htmlspecialchars($student['studentImage']);
    // mPDF config
    $mpdf = new Mpdf([
        'format' => 'A4', // make it A4 or custom as needed
        'margin_left' => 0,
        'margin_right' => 0,
        'margin_top' => 0,
        'margin_bottom' => 0,
    ]);

    // Build the HTML
    $html = '
    <style>
        @import url("https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap");
        body { font-family: "Poppins", sans-serif; font-size: 10px; }
        .wrapper { display: flex; width: 100%; }
        .front, .back { width: 50%; padding: 5px; box-sizing: border-box; }
        .card { background: #ffffff; border: 1px solid #ccc; border-radius: 8px; padding: 10px; height: 40%; position: relative; overflow: hidden; box-shadow: 0 0 5px rgba(0,0,0,0.2); }
        .card::before { content: "' . strtoupper($school_name) . '"; position: absolute; top: 30%; left: 50%; transform: translate(-50%, -50%) rotate(-30deg); font-size: 28px; color: #999999; opacity: 0.07; white-space: nowrap; z-index: 1; font-weight: bold; }
        .logo { text-align: center; }
        .logo img { width: 50px; }
        .photo { text-align: center; }
        .details { font-size: 9px; margin-top: 5px; text-align: center; }
        .details div { margin-bottom: 4px; }
        .role { font-size: 9px; color: #ff7e00; font-weight: bold; margin-bottom: 6px; }
        .id-number { background: #000; color: #fff; padding: 3px 8px; border-radius: 5px; font-size: 10px; display: inline-block; margin-top: 5px; }
        .qr { text-align: center; margin-top: 10px; }
        .qr img { width: 40px; }
        .back .terms { font-size: 8px; margin-top: 8px; }
        .back .terms ul { padding-left: 16px; margin-top: 5px; }
        .back .terms li { margin-bottom: 3px; }
        .signature { text-align: center; margin-top: 20px; }
        .signature img { width: 80px; }
        .signature-line { width: 80%; height: 1px; background: #000; margin: 10px auto; }
        .barcode { text-align: center; margin-top: 10px; }
        .contact-info { font-size: 7px; text-align: center; margin-top: 8px; line-height: 1.3; }
    </style>
    <div class="wrapper">
        <div class="front">
            <div class="card">
                <div class="logo">
                    <img src="' . $logo . '" alt="School Logo">
                    <h3>' . strtoupper(htmlspecialchars($school_name)) . '</h3>
                </div>
                <div class="photo">
                    <img src="' . $studentPhoto . '" alt="Student Photo" style="width:70px; height:70px; border-radius:50%; object-fit:cover;">
                </div>
                <div class="details">
                    <div style="font-size:11px;font-weight:600;">' . htmlspecialchars($student['studentName']) . '</div>
                    <div class="role">STUDENT</div>
                    <div><strong>Parent:</strong> ' . htmlspecialchars($student['parentName']) . '</div>
                    <div><strong>Class:</strong> ' . htmlspecialchars($student['class']) . ' (' . htmlspecialchars($student['section']) . ')</div>
                    <div><strong>Contact No:</strong> ' . htmlspecialchars($student['contactno']) . '</div>
                </div>
                <div style="text-align:center;">
                    <div class="id-number">' . htmlspecialchars($student['studentno']) . '</div>
                </div>
                <div class="qr" style="text-align:center;margin-top:10px;">
                    <img src="https://api.qrserver.com/v1/create-qr-code/?size=50x50&data=' . urlencode($student['studentno']) . '" alt="QR Code">
                </div>
            </div>
        </div>
        <div class="back">
            <div class="card">
                <div class="logo">
                    <img src="' . $logo1 . '" alt="School Logo">
                </div>
                <div class="terms">
                    <strong>Terms & Conditions:</strong>
                    <ul>
                        <li>ID card must be worn at all times.</li>
                        <li>Lost cards must be reported immediately.</li>
                        <li>This card is non-transferable.</li>
                    </ul>
                </div>
                <div class="signature">';
    if (file_exists($principalSignature)) {
        $html .= '<img src="' . $principalSignature . '" alt="Principal Signature">';
    } else {
        $html .= '<div class="signature-line"></div>';
    }
    $html .= '
                    <div style="font-size:7px;">Principal Signature</div>
                </div>
                <div class="barcode">
                    <img src="https://barcode.tec-it.com/barcode.ashx?data=' . urlencode($student['studentno']) . '&code=Code128&multiplebarcodes=false&translate-esc=false" alt="Barcode">
                </div>
                <div class="contact-info">
                    ' . htmlspecialchars($address) . '<br>
                    Email: ' . htmlspecialchars($email) . '<br>
                    Phone: ' . htmlspecialchars($phone) . '
                </div>
            </div>
        </div>
    </div>';

    // Save each PDF inside the unique download folder
    $filePath = $downloadFolder . '/id_card_' . $studentName . '.pdf';
    $mpdf->WriteHTML($html);
    $mpdf->Output($filePath, 'F');
}

// Now create the ZIP
$zipFile = 'id_cards/id_card_bundle_' . $class . '_' . $section . '.zip';
$zip = new ZipArchive();

if ($zip->open($zipFile, ZipArchive::CREATE) === TRUE) {
    $pdfFiles = glob($downloadFolder . '/*.pdf');
    if (count($pdfFiles) > 0) {
        foreach ($pdfFiles as $file) {
            $zip->addFile($file, basename($file));
        }
        $zip->close();

        // Cleanup: delete PDFs and folder
        array_map('unlink', $pdfFiles);
        rmdir($downloadFolder);

        // Clear output buffers
        while (ob_get_level()) {
            ob_end_clean();
        }

        // Headers and output
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename="' . basename($zipFile) . '"');
        header('Content-Length: ' . filesize($zipFile));
        flush();
        readfile($zipFile);

        // After download, delete the zip
        unlink($zipFile);
        exit;
    } else {
        flash_alert('No PDFs generated.', 'idcard.php');
        header('Location: idcard.php'); exit;
    }
} else {
    flash_alert('Failed to create ZIP archive.', 'idcard.php');
        header('Location: idcard.php'); exit;
}
