<?php
    ini_set('memory_limit', '128M');
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    require_once('config.php');
    require_once('students.php');
    require '../aws/app/start.php'; // AWS S3 SDK initialization

    // Create an instance of the student class
    $studentObj = new Student($conn);
    $students = $studentObj->getAllStudents();

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['passport_name'])) {
        // Check if any passport was selected for download
        $selectedPassports = $_POST['passport_name'];

        if (!empty($selectedPassports)) {
            // Create a temporary file for the ZIP archive
            $zip = new ZipArchive();
            $zipFileName = tempnam(sys_get_temp_dir(), 'passports') . '.zip';

            if ($zip->open($zipFileName, ZipArchive::CREATE) !== TRUE) {
                exit("Cannot open <$zipFileName>\n");
            }

            // Add each selected passport to the ZIP file
            foreach ($selectedPassports as $passport) {
                $fileUrl = $s3->getObjectUrl($config['s3']['bucket'], $passport);
                
                // Get the content of the file from AWS
                $fileContent = file_get_contents($fileUrl);

                // Add the file to the ZIP archive
                $zip->addFromString(basename($passport), $fileContent);
            }

            // Close the ZIP file
            $zip->close();

            // Force the download of the ZIP file
            header('Content-Type: application/zip');
            header('Content-Disposition: attachment; filename="passports.zip"');
            header('Content-Length: ' . filesize($zipFileName));

            // Send the file to the browser and delete the temporary file
            readfile($zipFileName);
            unlink($zipFileName); // Remove the temp file after download
            exit;
        } else {
            echo "No passport selected for download.";
        }
    }
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Download Passport</title>
</head>
<body>
    <form method="POST">
        <table border="1">
            <tr>
                <td>Check</td>
                <td>S/N</td>
                <td>Exams Number</td>
            </tr>
            <?php 
                $serialNumber = 0;
                foreach($students as $student){ 
                    $serialNumber++; 
            ?>
            <tr>
                <td><input type='checkbox' name='passport_name[]' value='<?php echo $student['passport']; ?>'/></td>
                <td><?php echo $serialNumber; ?></td>
                <td><?php echo $student['examination_number']; ?></td>
            </tr>
            <?php } ?>
        </table>
        <button type="submit">Download Selected Passports</button>
    </form>
</body>
</html>
