<?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'] ?? '');
$registrationEmail = trim($_POST['registration_email'] ?? '');

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

if ($registrationEmail !== '' && !filter_var($registrationEmail, FILTER_VALIDATE_EMAIL)) {
    json_response(['success' => false, 'message' => 'Please enter a valid email address.']);
}

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,
        'registration_email' => (string)($contract['registration_email'] ?? $contract['email'] ?? ''),
        'already_signed' => true,
    ]);
}

$updates = ['registration_email' => $registrationEmail];
if ($registrationEmail !== '' && trim((string)($contract['email'] ?? '')) === '') {
    $updates['email'] = $registrationEmail;
    $updates['partner_email'] = $registrationEmail;
}

try {
    $updated = null;
    if (local_store_find($token) !== null) {
        $updated = local_store_update($token, $updates);
    }

    if (api_is_configured() && api_feature_enabled('registration_email')) {
        $updated = api_update_contract($token, $updates) ?? $updated;
    }

    if ($updated === null) {
        $contract = api_ensure_local_contract_record($contract, $token);
        $updated = local_store_update($token, $updates);
    }
} 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,
    'registration_email' => $registrationEmail,
    'saved_at' => date('Y-m-d H:i:s'),
]);
