<?php
// scripts/backup.php
// Simple project backup script (includes migrations folder)
// Usage: php scripts/backup.php [output-zip-path]

$root = dirname(__DIR__);
$defaultDir = $root . DIRECTORY_SEPARATOR . 'backups';
if (!is_dir($defaultDir)) mkdir($defaultDir, 0777, true);

$ts = date('Ymd-His');
$defaultZip = $defaultDir . DIRECTORY_SEPARATOR . "backup-{$ts}.zip";
$out = $argv[1] ?? $defaultZip;

$zip = new ZipArchive();
if ($zip->open($out, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
    fwrite(STDERR, "Failed to create zip file: $out\n");
    exit(1);
}

$include = [
    'migrations',
    'public',
    'src',
    'composer.json',
    'composer.lock',
    '.env',
    'README.md'
];

$addPath = function($path, $rootPath) use ($zip, &$addPath) {
    $full = $rootPath . DIRECTORY_SEPARATOR . $path;
    if (is_dir($full)) {
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($full));
        foreach ($files as $file) {
            if ($file->isDir()) continue;
            $filePath = $file->getRealPath();
            $localPath = substr($filePath, strlen($rootPath) + 1);
            $zip->addFile($filePath, $localPath);
        }
    } elseif (is_file($full)) {
        $zip->addFile($full, $path);
    }
};

foreach ($include as $p) {
    $addPath($p, $root);
}

$zip->close();

echo "Backup written to: $out\n";
exit(0);
