<?php

require_once '../config.php';

// Get the logged-in user ID from the session
session_start();

// Check if the user is logged in as a system admin
if (!isset($_SESSION['userType']) || $_SESSION['userType'] !== 'member') {
    header('Location: ../indexX.php');
    exit;
}
// Establish the database connection
$connection = mysqli_connect($db_host, $db_user, $db_password, $db_name);
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

$loggedInUserId = $_SESSION['id']; // Assuming you have stored the user ID in a session variable

// Get the selected batch ID from the query parameters
$selectedBatchId = $_GET['bid']; // Assuming you pass the selected batch ID as a query parameter

// Directory where the generated certificates are stored
$certificatesDirectory = 'certificates/'.$loggedInUserId.'/'.$selectedBatchId;
//member/certificates/69/20240418155209
//echo $certificatesDirectory;

// Path to the zip file
$zipName = 'certificates_' .$loggedInUserId.'_'. $selectedBatchId . '.zip';

// Create a new zip archive
$zip = new ZipArchive();

if ($zip->open($zipName, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
    die('Error creating zip file');
}

// Get the list of certificate files in the directory
$certificateFiles = scandir($certificatesDirectory);

foreach ($certificateFiles as $file) {
    // Exclude directories and non-PDF files
    if (!is_dir($file) && pathinfo($file, PATHINFO_EXTENSION) === 'pdf') {
        // Add the file to the zip archive
        $zip->addFile($certificatesDirectory . '/' . $file, $file);
    }
}

// Close the zip archive
$zip->close();

// Download the zip file
if (file_exists($zipName)) {
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="' . $zipName . '"');
    header('Content-Length: ' . filesize($zipName));
    readfile($zipName);

    // Delete the zip file after download
    unlink($zipName);
} else {
    echo 'Error creating zip file';
}
