<?php

require_once __DIR__ . '/core/auth.php';
requireEcosystemAuth();

$sourceDir = __DIR__;
$zipFile = sys_get_temp_dir() . '/cbt_ecosystem_portal_' . time() . '.zip';

$zip = new ZipArchive();
if ($zip->open($zipFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) {
    die("Gagal membuat arsip ZIP portal.");
}

$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($sourceDir, RecursiveDirectoryIterator::SKIP_DOTS),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $file) {
    if (!$file->isDir()) {
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($sourceDir) + 1);
        $normPath = str_replace('\\', '/', $relativePath);

        if (strpos($normPath, '.git') === 0 || strpos($normPath, 'data/ecosystem.db-journal') !== false) {
            continue;
        }

        $zip->addFile($filePath, $normPath);
    }
}

$zip->close();

if (file_exists($zipFile)) {
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="cbt_ecosystem_portal.zip"');
    header('Content-Length: ' . filesize($zipFile));
    header('Pragma: no-cache');
    header('Expires: 0');
    readfile($zipFile);
    unlink($zipFile);
    exit;
} else {
    die("Berkas ZIP tidak ditemukan.");
}
