<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/_bootstrap.php';
require_once dirname(__DIR__, 2) . '/common/web_session_auth.php';

golder_require_method('GET');

$master = golder_master_pdo();
$customerId = 0;

try {
    $ctx = golder_require_current_web_customer_session($master);
    $customerId = (int)($ctx['customer_id'] ?? 0);
} catch (Throwable $_ignored) {
    $apiCtx = golder_api_auth('desktop_sync');
    $customerId = (int)($apiCtx['customer_id'] ?? 0);
}

if ($customerId <= 0) {
    golder_json_response(['status' => 'error', 'message' => 'Unauthorized'], 401);
}

$backupUuid = trim((string)($_GET['backup_uuid'] ?? ''));
if ($backupUuid === '') {
    golder_json_response(['status' => 'error', 'message' => 'backup_uuid is required'], 400);
}

$st = $master->prepare(
    'SELECT file_path
     FROM backup_files
     WHERE backup_uuid = :id
       AND customer_id = :cid
     LIMIT 1'
);
$st->execute([':id' => $backupUuid, ':cid' => $customerId]);
$row = $st->fetch();
if (!$row) {
    golder_json_response(['status' => 'error', 'message' => 'Backup not found'], 404);
}

$filePath = (string)($row['file_path'] ?? '');
if ($filePath === '' || !is_file($filePath)) {
    golder_json_response(['status' => 'error', 'message' => 'Backup file is missing'], 404);
}

$filename = basename($filePath);
header('Content-Type: application/octet-stream');
// GÜNCELLEME: İndirmeyi tarayıcıda kesin başlatması için .golder uzantısını sabitledik
header('Content-Disposition: attachment; filename="Golder_Yedek_' . date('Ymd_His') . '.golder"');
header('Content-Length: ' . (filesize($filePath) ?: 0));
header('X-Content-Type-Options: nosniff');
readfile($filePath);
exit;


