<?php
require_once "db_connection.php";

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'])) {
    $id = intval($_POST['id']);
    $query = "SELECT * FROM karshenasan WHERE id = $id";
    $result = $conn->query($query);

    if ($result && $row = $result->fetch_assoc()) {
        $zip = new ZipArchive();
        $zipFileName = "reports_{$id}_" . time() . ".zip";
        $zipFilePath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $zipFileName;

        if ($zip->open($zipFilePath, ZipArchive::CREATE) === TRUE) {
            for ($i = 1; $i <= 10; $i++) {
                $fileKey = "file$i";
                if (!empty($row[$fileKey])) {
                    $filePath = __DIR__ . "/k_uploads/" . $row[$fileKey];
                    if (file_exists($filePath)) {
                        $zip->addFile($filePath, "مرحله$i-" . basename($filePath));
                    }
                }
            }
            $zip->close();

            header('Content-Type: application/zip');
            header('Content-Disposition: attachment; filename="' . $zipFileName . '"');
            header('Content-Length: ' . filesize($zipFilePath));
            readfile($zipFilePath);
            unlink($zipFilePath); // پاک کردن فایل موقت بعد از ارسال
            exit;
        } else {
            die("خطا در ایجاد فایل زیپ.");
        }
    } else {
        die("ردیف موردنظر یافت نشد.");
    }
} else {
    die("درخواست نامعتبر.");
}
