<?php
/**
 * Build a deployment ZIP of the application — Linux/cPanel-safe (forward-slash
 * paths, built with the native ZipArchive). Excludes local backups, uploaded
 * PHI, transient temp, editor/session data, and the output zip itself.
 *
 *   php bin/build-deploy-zip.php
 *
 * Output: medmecs-deploy.zip in the project root. Extract it into your web root
 * on the server. config.php is env-aware (auto-detects live vs local), so it is
 * safe to include.
 */
$root = realpath(__DIR__ . '/..');
$out  = $root . DIRECTORY_SEPARATOR . 'medmecs-deploy.zip';
@unlink($out);

/* Directory prefixes (relative, forward-slash) to skip entirely. */
$excludeDirs = [
    'backups', '.claude', '.git', '.vscode', '.idea', 'node_modules',
    'storage/uploads/collection', 'storage/uploads/facility-mapping',
    'storage/uploads/billing-sheets', 'storage/uploads/tmp', 'storage/tmp',
];
$excludeExt = ['zip'];

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

$it = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS),
    RecursiveIteratorIterator::SELF_FIRST
);
$files = 0; $dirs = 0;
foreach ($it as $file) {
    $rel = str_replace('\\', '/', substr($file->getPathname(), strlen($root) + 1));
    if ($rel === '') continue;
    foreach ($excludeDirs as $ex) {
        if ($rel === $ex || strpos($rel, $ex . '/') === 0) continue 2;   // skip excluded tree
    }
    if ($file->isDir()) {
        $zip->addEmptyDir($rel); $dirs++;
    } else {
        if (in_array(strtolower($file->getExtension()), $excludeExt, true)) continue;
        $zip->addFile($file->getPathname(), $rel); $files++;
    }
}
$zip->close();
printf("Built %s\n  %.2f MB · %d files · %d dirs\n", $out, filesize($out) / 1048576, $files, $dirs);
