<?php
/**
 * GET /api/download-app.php
 * Descarcă întreaga aplicație ca arhivă .zip (pentru mutare pe hosting).
 *
 * Construit în PHP pur (deflate prin zlib) fiindcă extensia `zip` poate lipsi.
 * Exclude: data/ (DB + chei), logs/, .git, fișiere .bak și config.local.php —
 * astfel pe hosting pornește „curat" și redirectează la install.php.
 */
require_once __DIR__ . '/../includes/config.php';

$root    = APP_ROOT;
$rootLen = strlen($root) + 1;

$excludeTop   = ['data', 'logs', '.git', '.idea', '.vscode', 'node_modules'];
$excludeNames = ['config.local.php', '.installed', '.htpasswd'];

// Colectează fișierele
$files = [];
$it = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS),
    RecursiveIteratorIterator::SELF_FIRST
);
foreach ($it as $path => $info) {
    if (!$info->isFile()) continue;
    $rel = str_replace('\\', '/', substr($path, $rootLen));
    if ($rel === '') continue;
    $top = explode('/', $rel)[0];
    if (in_array($top, $excludeTop, true)) continue;
    if (in_array(basename($rel), $excludeNames, true)) continue;
    if (preg_match('/\.bak(-[0-9\-]+)?$/', $rel)) continue;
    $files[$rel] = $path;
}

$entries = '';
$central = '';
$offset  = 0;
$count   = 0;

foreach ($files as $rel => $path) {
    $data = @file_get_contents($path);
    if ($data === false) continue;
    $crc = crc32($data);
    $unc = strlen($data);
    $comp = gzdeflate($data, 6);
    if ($comp === false || strlen($comp) >= $unc) { $method = 0; $comp = $data; }
    else { $method = 8; }
    $clen = strlen($comp);
    $nameLen = strlen($rel);

    // Local file header
    $lfh = pack('V', 0x04034b50) . pack('v', 20) . pack('v', 0) . pack('v', $method)
         . pack('v', 0) . pack('v', 0)                      // time, date
         . pack('V', $crc) . pack('V', $clen) . pack('V', $unc)
         . pack('v', $nameLen) . pack('v', 0) . $rel;
    $entries .= $lfh . $comp;

    // Central directory header
    $central .= pack('V', 0x02014b50) . pack('v', 20) . pack('v', 20) . pack('v', 0) . pack('v', $method)
         . pack('v', 0) . pack('v', 0)
         . pack('V', $crc) . pack('V', $clen) . pack('V', $unc)
         . pack('v', $nameLen) . pack('v', 0) . pack('v', 0) . pack('v', 0) . pack('v', 0)
         . pack('V', 0) . pack('V', $offset) . $rel;

    $offset += strlen($lfh) + $clen;
    $count++;
}

$eocd = pack('V', 0x06054b50) . pack('v', 0) . pack('v', 0)
      . pack('v', $count) . pack('v', $count)
      . pack('V', strlen($central)) . pack('V', $offset) . pack('v', 0);

$out = $entries . $central . $eocd;

$fname = 'gestionare-app-' . date('Ymd-His') . '.zip';
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . $fname . '"');
header('Content-Length: ' . strlen($out));
header('Cache-Control: no-store');
echo $out;
