<?php
session_start();
require_once 'phpqrcode/qrlib.php';
require_once 'pdo_config.php';

$created_files = [];
$zips = [];

if (isset($_POST['generate_bulk'])) {
    $lrns = $_POST['lrn'];
    $firsts = $_POST['first'];
    $middles = $_POST['middle'];
    $lasts = $_POST['last'];
    $grades = $_POST['grade'];
    $sexes = $_POST['sex'];
    $birthdays = $_POST['birthday'];
    $numbers = $_POST['number'];

    $outputDir = "qr_codes/";
    if (!file_exists($outputDir)) mkdir($outputDir, 0777, true);

    for ($i = 0; $i < count($lrns); $i++) {
        $name = $firsts[$i] . " " . $middles[$i] . " " . $lasts[$i];
        $grade_display = ($grades[$i] === 'Nursery' || $grades[$i] === 'Kindergarten') ? $grades[$i] : "Grade " . $grades[$i];
        $qr_data = "http://159.223.47.179/student_checkin/checkin_auto.php?lrn=" . urlencode($lrns[$i]) .
            "&name=" . str_replace(' ', '+', $name) .
            "&grade=" . urlencode($grade_display) .
            "&number=" . urlencode($numbers[$i]);

        $gradeDir = $outputDir . $grade_display;
        if (!file_exists($gradeDir)) mkdir($gradeDir, 0777, true);

        $temp_file = "$gradeDir/temp_" . $lrns[$i] . ".png";
        $final_file = "$gradeDir/qr_" . $lrns[$i] . ".png";
        QRcode::png($qr_data, $temp_file, QR_ECLEVEL_H, 6);
        $QR = imagecreatefrompng($temp_file);
        $logo = imagecreatefrompng("school_logo.png");

        $qr_width = imagesx($QR);
        $logo_width = imagesx($logo);
        $scale = $logo_width / ($qr_width / 4);
        $logo_qr_height = imagesy($logo) / $scale;
        $from_width = ($qr_width - $qr_width / 4) / 2;

        imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $qr_width / 4, $logo_qr_height, $logo_width, imagesy($logo));
        imagepng($QR, $final_file);
        unlink($temp_file);

        $created_files[] = ['path' => $final_file, 'name' => $name, 'grade' => $grade_display];

        $stmt = $pdo->prepare("INSERT INTO students (lrn, name, grade, sex, birthday, contact)
            VALUES (?, ?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE name=VALUES(name), grade=VALUES(grade), sex=VALUES(sex), birthday=VALUES(birthday), contact=VALUES(contact)");
        $stmt->execute([$lrns[$i], $name, $grades[$i], $sexes[$i], $birthdays[$i], $numbers[$i]]);
    }

    // Group by grade & create ZIPs
    $grouped = [];
    foreach ($created_files as $file) {
        $grouped[$file['grade']][] = $file['path'];
    }

    foreach ($grouped as $grade => $files) {
        $zipname = "$outputDir/{$grade}_QRCodes.zip";
        $zip = new ZipArchive();
        if ($zip->open($zipname, ZipArchive::CREATE) === TRUE) {
            foreach ($files as $f) {
                $basename = basename($f);
                if ($zip->locateName($basename) === false) {
                    $zip->addFile($f, $basename);
                }
            }
            $zip->close();
            $zips[$grade] = [
                'path' => $zipname,
                'count' => count(glob(dirname($f) . "/*.png"))
            ];
        }
    }

    $_SESSION['created_files'] = $created_files;
    $_SESSION['zips'] = $zips;
    header("Location: generate.php?generated=1");
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SDAESI QRCode Generator</title>
    <style>
        body { background: #121212; color: white; font-family: Arial; padding: 20px; text-align: center; }
        .school-logo { width: 80px; }
        .school-name { font-weight: bold; margin: 10px 0 30px; }
        table { width: 100%; border-collapse: collapse; margin-bottom: 15px; }
        table td { padding: 8px; }
        input, select { width: 100%; padding: 6px; }
        .qr-box { display: inline-block; margin: 15px; background: #1e1e1e; padding: 15px; border-radius: 10px; }
img.qr-preview { width: 180px; height: 180px; }
        .download-link { color: #00f0ff; text-decoration: none; }
        .dashboard-link { margin-top: 20px; display: inline-block; color: #aaa; }
        .dashboard-link:hover { color: #fff; }
    </style>
</head>
<body>

<div class="container">
    <img src="school_logo.png" alt="School Logo" class="school-logo">
    <div class="school-name">SIOCON DISTRICT ADVENTIST ELEMENTARY SCHOOL INC</div>

    <h3>📘 Bulk QR Code Generator</h3>
    <form method="POST">
        <table border="0" id="studentTable">
            <tr>
                <td><input type="text" name="lrn[]" placeholder="LRN" required></td>
                <td><input type="text" name="first[]" placeholder="First" required></td>
                <td><input type="text" name="middle[]" placeholder="Middle" required></td>
                <td><input type="text" name="last[]" placeholder="Last" required></td>
                <td>
                    <select name="grade[]" required>
                        <option value="" hidden>Grade</option>
                        <option value="Nursery">Nursery</option>
                        <option value="Kindergarten">Kindergarten</option>
                        <option value="1">Grade 1</option>
                        <option value="2">Grade 2</option>
                        <option value="3">Grade 3</option>
                        <option value="4">Grade 4</option>
                        <option value="5">Grade 5</option>
                        <option value="6">Grade 6</option>
                    </select>
                </td>
                <td>
                    <select name="sex[]" required>
                        <option value="" hidden>Sex</option>
                        <option>Male</option>
                        <option>Female</option>
                    </select>
                </td>
                <td><input type="date" name="birthday[]" required></td>
                <td><input type="text" name="number[]" placeholder="Contact" required></td>
            </tr>
        </table>
        <button type="button" onclick="addRow()">➕ Add Student</button><br><br>
        <button type="submit" name="generate_bulk">🚀 Generate QR Codes</button>
    </form>

    <?php if (isset($_GET['generated']) && isset($_SESSION['created_files'])): ?>
        <h3>✅ Generated QR Code</h3>
        <?php $preview = $_SESSION['created_files'][0]; ?>
        <div class="qr-box">
            <p><?php echo htmlspecialchars($preview['name']); ?></p>
            <img src="<?php echo $preview['path']; ?>" class="qr-preview"><br>
            <a class="download-link" href="<?php echo $preview['path']; ?>" download>⬇ Download QR</a>
        </div>

        <h4>📦 Download ZIP File(s)</h4>
        <?php foreach ($_SESSION['zips'] as $grade => $zip): ?>
            <p>
                <a class="download-link" href="<?php echo $zip['path']; ?>" download>
                    <?php echo "$grade QRCodes.zip ({$zip['count']} file" . ($zip['count'] > 1 ? "s" : "") . ")"; ?>
                </a>
            </p>
        <?php endforeach; ?>
        <?php session_unset(); ?>
    <?php endif; ?>

    <a href="dashboard.php" class="dashboard-link">← Back to Dashboard</a>
</div>

<script>
function addRow() {
    const table = document.getElementById('studentTable');
    const row = table.rows[0].cloneNode(true);
    row.querySelectorAll('input, select').forEach(input => input.value = '');
    table.appendChild(row);
}
</script>

</body>
</html>
