<?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);
}

$latitudeRaw = trim((string)($_POST['latitude'] ?? ''));
$longitudeRaw = trim((string)($_POST['longitude'] ?? ''));
$fullAddress = trim((string)($_POST['full_address'] ?? ''));
$geoStatus = trim((string)($_POST['geo_status'] ?? 'unknown'));
$accuracyRaw = trim((string)($_POST['accuracy_meters'] ?? ''));
$userAgent = trim((string)($_POST['user_agent'] ?? ($_SERVER['HTTP_USER_AGENT'] ?? '')));
$timezone = trim((string)($_POST['timezone'] ?? ''));
$screenResolution = trim((string)($_POST['screen_resolution'] ?? ''));

$latitude = $latitudeRaw !== '' ? (float)$latitudeRaw : null;
$longitude = $longitudeRaw !== '' ? (float)$longitudeRaw : null;
$accuracy = $accuracyRaw !== '' ? (float)$accuracyRaw : null;

if ($latitude !== null && $longitude !== null && $fullAddress === '') {
    $fullAddress = reverse_geocode_coordinates($latitude, $longitude);
}

$access = [
    'accessed_at' => date('Y-m-d H:i:s'),
    'ip_address' => client_ip(),
    'latitude' => $latitude,
    'longitude' => $longitude,
    'full_address' => $fullAddress,
    'accuracy_meters' => $accuracy,
    'geo_status' => $geoStatus !== '' ? $geoStatus : 'unknown',
    'user_agent' => $userAgent,
    'timezone' => $timezone,
    'screen_resolution' => $screenResolution,
];

try {
    $updated = api_record_link_access($token, $access);
} 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,
    'access' => $access,
    'link_last_access' => $updated['link_last_access'] ?? $access,
]);
