<?php
// Central quota endpoint for web + desktop clients.
declare(strict_types=1);

require_once dirname(__DIR__) . '/_bootstrap.php';

golder_require_method('POST');
$ctx = golder_api_auth('desktop_sync');
$master = $ctx['master'];
$customerId = (int)$ctx['customer_id'];

golder_ensure_backup_tables($master);

$stBackup = $master->prepare(
    "SELECT COUNT(*) FROM backup_files
     WHERE customer_id = :cid
       AND backup_type = 'manual'
       AND DATE(created_at) = UTC_DATE()"
);
$stBackup->execute([':cid' => $customerId]);
$backupToday = (int)$stBackup->fetchColumn();

$stRestore = $master->prepare(
    "SELECT COUNT(*) FROM backup_files
     WHERE customer_id = :cid
       AND restored_at IS NOT NULL
       AND DATE(restored_at) = UTC_DATE()"
);
$stRestore->execute([':cid' => $customerId]);
$restoreToday = (int)$stRestore->fetchColumn();

$backupLimit = 3;
$restoreLimit = 3;

golder_json_response([
    'status' => 'ok',
    'backup_used' => $backupToday,
    'backup_limit' => $backupLimit,
    'backup_remaining' => max(0, $backupLimit - $backupToday),
    'restore_used' => $restoreToday,
    'restore_limit' => $restoreLimit,
    'restore_remaining' => max(0, $restoreLimit - $restoreToday),
    'date_utc' => gmdate('Y-m-d'),
]);


