<?php
// api/update_client.php
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';

try {
    // Read JSON body
    $raw = file_get_contents('php://input');
    $data = json_decode($raw, true);

    if (!$data || !isset($data['Id'])) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Invalid payload'
        ]);
        exit;
    }

    $sql = "
        UPDATE Clients
        SET 
            FullName        = :FullName,
            Gender          = :Gender,
            DateOfBirth     = :DateOfBirth,
            MaritalStatus   = :MaritalStatus,
            Nationality     = :Nationality,
            StateOfOrigin   = :StateOfOrigin,
            Lga             = :Lga,
            Address         = :Address,
            Phone           = :Phone,
            AltPhone        = :AltPhone,
            Email           = :Email,
            NokName         = :NokName,
            NokRelationship = :NokRelationship,
            NokPhone        = :NokPhone,
            NokAddress      = :NokAddress
        WHERE Id = :Id
        LIMIT 1
    ";

    $stmt = $pdo->prepare($sql);

    // DateOfBirth will be "YYYY-MM-DD" or null
    $dob = !empty($data['DateOfBirth']) ? $data['DateOfBirth'] : null;

    $stmt->execute([
        ':FullName'        => $data['FullName']        ?? null,
        ':Gender'          => $data['Gender']          ?? null,
        ':DateOfBirth'     => $dob,
        ':MaritalStatus'   => $data['MaritalStatus']   ?? null,
        ':Nationality'     => $data['Nationality']     ?? null,
        ':StateOfOrigin'   => $data['StateOfOrigin']   ?? null,
        ':Lga'             => $data['Lga']             ?? null,
        ':Address'         => $data['Address']         ?? null,
        ':Phone'           => $data['Phone']           ?? null,
        ':AltPhone'        => $data['AltPhone']        ?? null,
        ':Email'           => $data['Email']           ?? null,
        ':NokName'         => $data['NokName']         ?? null,
        ':NokRelationship' => $data['NokRelationship'] ?? null,
        ':NokPhone'        => $data['NokPhone']        ?? null,
        ':NokAddress'      => $data['NokAddress']      ?? null,
        ':Id'              => (int)$data['Id'],
    ]);

    echo json_encode([
        'success' => true,
        'message' => 'Client updated'
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to update client',
        'details' => $e->getMessage()
    ]);
}
