<?php
include("./include/config.php");

if (!isset($_SESSION['a_user'])) {
    header("Location: index.php");
    exit;
}

if (isset($_GET['selectedRows']) && !empty($_GET['selectedRows'])) {
    $selectedRows = json_decode($_GET['selectedRows'], true);
    
    $zip = new ZipArchive();
    $zip_name = 'selected_files.zip';
    
    if ($zip->open($zip_name, ZipArchive::CREATE) === TRUE) {
        foreach ($selectedRows as $application_no) {
            $sql = "SELECT * FROM data WHERE application_no = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param('s', $application_no);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($row = $result->fetch_assoc()) {
                $zip->addFile($row['photo_file'], basename($row['photo_file']));
                $zip->addFile($row['adhar_file'], basename($row['adhar_file']));
                $zip->addFile($row['adhar_file1'], basename($row['adhar_file1']));
                $zip->addFile($row['pan_file'], basename($row['pan_file']));
                $zip->addFile($row['cc_file'], basename($row['cc_file']));
                $zip->addFile($row['cc_file1'], basename($row['cc_file1']));
                $zip->addFile($row['cc_2_file'], basename($row['cc_2_file']));
                $zip->addFile($row['cc_2_file1'], basename($row['cc_2_file1']));
            }
            
            $stmt->close();
        }
        
        $zip->close();
        
        header("Content-type: application/zip");
        header("Content-Disposition: attachment; filename=$zip_name");
        header("Content-length: " . filesize($zip_name));
        header("Pragma: no-cache");
        header("Expires: 0");
        readfile("$zip_name");
        
        unlink($zip_name);
    } else {
        echo "Failed to create ZIP.";
    }
} else {
    echo "No rows selected.";
}
?>
