<?php
// Stop any accidental output
ob_start();

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

    if (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] === 0) {

        // QR Library
        include('phpqrcode/qrlib.php');

        // CSV file temp path
        $csvFile = $_FILES['csv_file']['tmp_name'];

        // Temp folder for QR files
        $tempDir = 'qr_temp/';
        if (!file_exists($tempDir)) {
            mkdir($tempDir, 0777, true);
        }

        // Read CSV
        $file = fopen($csvFile, 'r');
        $stdIds = [];

        while (($data = fgetcsv($file)) !== false) {
            $stdId = trim($data[0]);

            if ($stdId != '') {
                $stdIds[] = $stdId;

                // Correct QR URL (NO www)
                $url = "https://id.hamdarduniversity.edu.bd/id.php/id/$stdId";

                // Filename for QR
                $filename = $tempDir . $stdId . '.png';

                // Generate QR
                QRcode::png($url, $filename, QR_ECLEVEL_L, 4);
            }
        }
        fclose($file);

        // Create ZIP
        $zipName = 'qr_codes.zip';
        $zip = new ZipArchive();

        if ($zip->open($zipName, ZipArchive::CREATE | ZipArchive::OVERWRITE)) {

            foreach ($stdIds as $id) {
                $zip->addFile($tempDir . $id . '.png', $id . '.png');
            }

            $zip->close();

            // Remove temp PNGs
            foreach ($stdIds as $id) {
                unlink($tempDir . $id . '.png');
            }
            rmdir($tempDir);

            // Send ZIP headers
            header('Content-Type: application/zip');
            header('Content-Disposition: attachment; filename="qr_codes.zip"');
            header('Content-Length: ' . filesize($zipName));

            // Clean buffer → VERY IMPORTANT
            ob_clean();
            flush();

            readfile($zipName);

            unlink($zipName);
            exit;
        } else {
            echo "Failed to create zip.";
        }
    } else {
        echo "Please upload a CSV file.";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Generate QR Codes</title>
</head>
<body>
<h2>Upload CSV to Generate QR Codes</h2>
<form method="post" enctype="multipart/form-data">
    <input type="file" name="csv_file" accept=".csv" required>
    <button type="submit" name="submit">Generate QR Codes</button>
</form>
</body>
</html>
