<?php

declare(strict_types=1);

require_once __DIR__ . '/../includes/api_service.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(['success' => false, 'message' => 'Method not allowed'], 405);
}

$token = trim($_POST['token'] ?? '');

if ($token === '') {
    json_response(['success' => false, 'message' => 'Missing token.'], 400);
}

try {
    $contract = api_find_contract($token);
} catch (Throwable $e) {
    json_response(['success' => false, 'message' => api_error_message($e)], 502);
}

if (!$contract) {
    json_response(['success' => false, 'message' => 'Record not found.'], 404);
}

if (($contract['status'] ?? '') === 'signed') {
    json_response([
        'success' => true,
        'pdf_viewed_at' => $contract['pdf_viewed_at'] ?? null,
        'already_signed' => true,
    ]);
}

try {
    $updated = api_record_pdf_viewed($token);
} catch (Throwable $e) {
    json_response(['success' => false, 'message' => api_error_message($e)], 502);
}

if ($updated === null) {
    json_response(['success' => false, 'message' => 'Record not found.'], 404);
}

json_response([
    'success' => true,
    'pdf_viewed_at' => $updated['pdf_viewed_at'] ?? date('Y-m-d H:i:s'),
]);
