<?php
declare(strict_types=1);

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

golder_require_method('POST');
$ctx = golder_api_auth('desktop_sync');
$input = golder_api_input();

$profileId = trim((string)($input['profile_id'] ?? ''));
$backupUuid = trim((string)($input['backup_uuid'] ?? ''));
$filePath = trim((string)($input['file_path'] ?? ''));

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

if ($filePath === '') {
    golder_json_response(['status' => 'error', 'message' => 'backup_uuid or file_path is required'], 400);
}

$result = golder_restore_profile_backup($ctx['master'], $ctx['customer'], $profileId, $filePath);
if (empty($result['ok'])) {
    golder_json_response(['status' => 'error', 'message' => (string)($result['message'] ?? 'Restore failed')], 400);
}

golder_json_response(['status' => 'ok', 'result' => $result]);


