<?php
// Initialize a new ZipArchive object
$zip = new ZipArchive();
$zipFileName = 'all_id_cards.zip';

// Create a new zip file
if ($zip->open($zipFileName, ZipArchive::CREATE) === TRUE) {
    // Connect to MySQL
    include_once './dbconn.php';

    // Query to retrieve data
    $sql = "SELECT * FROM `web_app_enrollee_data`";
    $result = mysqli_query($conn, $sql);

    // Loop through each record and generate ID card
    while ($row = mysqli_fetch_assoc($result)) {
        // Generate ID card for each record
        $id = $row['id'];
        $name = $row['first_name'] . " " . $row['surname'];
        $idNumber = $row['hmo_id'];
        $client = $row['company_name'];
        $plan = $row['type_of_plan'];
        $gender = $row['gender'];
        $imageUrl = $row['Passport_link'];

        // Call the printIDCard function
        printIDCard($id, $name, $idNumber, $client, $plan, $gender, $imageUrl, $zip);
    }

    // Close MySQL connection
    mysqli_close($conn);

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

    // Set headers to force download the zip file
    header('Content-Type: application/zip');
    header('Content-disposition: attachment; filename=' . $zipFileName);
    header('Content-Length: ' . filesize($zipFileName));
    readfile($zipFileName);

    // Delete the zip file after download
    unlink($zipFileName);
} else {
    echo 'Failed to create zip file';
}

// Function to generate ID card and add it to the zip archive
function printIDCard($id, $name, $idNumber, $client, $plan, $gender, $imageUrl, $zip) {
    // Prepare POST data
    $postData = array(
        'name' => $name,
        'id_number' => $idNumber,
        'client' => $client,
        'plan' => $plan,
        'validity' => $gender,
        'image_url' => $imageUrl
    );

    // Set up stream context options
    $options = array(
        'http' => array(
            'method'  => 'POST',
            'header'  => 'Content-type: application/x-www-form-urlencoded',
            'content' => http_build_query($postData)
        )
    );

    // Create a stream context
    $context = stream_context_create($options);

    // Send POST request
    $response = file_get_contents('idcard.php', false, $context);

    // Decode the JSON response
    $responseArray = json_decode($response, true);

    // Check if response contains file URL
    if (isset($responseArray['file_url'])) {
        // Add the file to the zip archive
        $zip->addFromString("ID_Cards/{$id}_ID_Card.png", file_get_contents($responseArray['file_url']));
    } else {
        // Handle error
        echo "Failed to generate ID card for ID: $idNumber";
    }
}

?>
