<?php
require_once '../includes/init.php';

$user = new User($pdo);
if (!$user->isLoggedIn() || !$user->isAdmin()) {
    die("Access Denied");
}

// Configuration
$exclude = [
    'config/database.php',
    '.git',
    '.gitignore',
    '.vscode',
    'assets/uploads',
    'update_package.zip',
    'db_backup_',
    'error_log',
    'node_modules'
];

$rootPath = realpath('../');
$zipName = 'update_package_' . date('Y-m-d_H-i-s') . '.zip';
$zipPath = $rootPath . '/' . $zipName;

$zip = new ZipArchive();
if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) {
    die("Cannot create zip file");
}

/**
 * Recursive directory iterator to add files
 */
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $name => $file) {
    // Skip directories (they will be added automatically)
    if (!$file->isDir()) {
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);
        $relativePath = str_replace('\\', '/', $relativePath); // Normalize slashes

        // Check exclusions
        $skip = false;
        foreach ($exclude as $exc) {
            if (strpos($relativePath, $exc) === 0 || strpos($filePath, $exc) !== false) {
                $skip = true;
                break;
            }
        }
        
        // Also skip the script itself if needed, or temporary files
        if (strpos($relativePath, 'admin/create_update_package.php') !== false) {
            // Include this script? Yes, why not.
        }

        if (!$skip) {
            $zip->addFile($filePath, $relativePath);
        }
    }
}

// Add a dummy update.sql if one doesn't exist, just to show structure?
// No, the user will create it if needed.

$zip->close();

if (file_exists($zipPath)) {
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="'.basename($zipPath).'"');
    header('Content-Length: ' . filesize($zipPath));
    readfile($zipPath);
    unlink($zipPath); // Delete after download
} else {
    echo "Error creating zip file.";
}
