<?php
// Increase execution time and memory limit for larger files
set_time_limit(300);
ini_set('memory_limit', '512M');

// Directory to compress (the whole project root)
$rootPath = realpath(__DIR__ . '/../');
$zipFileName = 'phpodev-main.zip';

// Initialize archive object
$zip = new ZipArchive();
$tempFile = tempnam(sys_get_temp_dir(), 'zip_project_');

if ($zip->open($tempFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
    // Create recursive directory iterator
    /** @var SplFileInfo[] $files */
    $files = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($rootPath, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::LEAVES_ONLY
    );

    foreach ($files as $name => $file) {
        // Skip directories (they will be added automatically with files)
        if (!$file->isDir()) {
            // Get real and relative path for current file
            $filePath = $file->getRealPath();
            $relativePath = substr($filePath, strlen($rootPath) + 1);

            // Normalize directory separators for ZIP consistency
            $relativePath = str_replace('\\', '/', $relativePath);

            // Exclude unwanted directories and files
            // .git, .gemini, node_modules, .vscode, and any temporary ZIP files
            if (
                preg_match('/^(\.git|\.gemini|node_modules|\.vscode)/i', $relativePath) ||
                strpos($relativePath, 'phpodev-main.zip') !== false
            ) {
                continue;
            }

            // Add current file to archive
            $zip->addFile($filePath, $relativePath);
        }
    }

    // Zip archive will be created only after closing object
    $zip->close();

    // Check if the file was created and is not empty
    if (file_exists($tempFile) && filesize($tempFile) > 0) {
        // Stream the file
        header('Content-Description: File Transfer');
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename="' . $zipFileName . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($tempFile));
        
        // Clean output buffer to prevent corrupted zip files
        if (ob_get_level()) {
            ob_end_clean();
        }
        
        readfile($tempFile);
        unlink($tempFile);
        exit;
    } else {
        echo "Hata: Geçici ZIP dosyası oluşturulamadı veya boş.";
    }
} else {
    echo "Hata: ZipArchive oluşturulamadı.";
}
