<?php
// api/get_client_details.php?id=123
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

require_once __DIR__ . '/../../config.php';

$clientId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($clientId <= 0) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing or invalid client id']);
    exit;
}

try {
    $stmt = $pdo->prepare("
        SELECT
            Id,
            ClientId,
            Surname,
            FirstName,
            OtherName,
            FullName,
            Gender,
            DateOfBirth,
            MaritalStatus,
            Nationality,
            StateOfOrigin,
            Lga,
            Address,
            Phone,
            AltPhone,
            Email,
            NokName,
            NokRelationship,
            NokPhone,
            NokAddress,
            CreatedAt
        FROM Clients
        WHERE Id = :id
        LIMIT 1
    ");
    $stmt->execute([':id' => $clientId]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        http_response_code(404);
        echo json_encode(['error' => 'Client not found']);
        exit;
    }

    // Normalize CreatedAt and DateOfBirth for System.Text.Json
    if (!empty($row['CreatedAt'])) {
        $dt = DateTime::createFromFormat('Y-m-d H:i:s', $row['CreatedAt']);
        if ($dt !== false) {
            $row['CreatedAt'] = $dt->format('c'); // ISO 8601
        }
    }

    if (!empty($row['DateOfBirth'])) {
        $dob = DateTime::createFromFormat('Y-m-d', $row['DateOfBirth']);
        if ($dob !== false) {
            $row['DateOfBirth'] = $dob->format('Y-m-d'); // date only
        }
    }

    echo json_encode($row);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'error'   => 'Failed to load client details',
        'details' => $e->getMessage()
    ]);
}
