<?php
// syncClients.php

// DEBUG: show PHP errors (remove or lower in production)
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", "*");
header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
header("Access-Control-Allow-Headers", "Content-Type");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    echo json_encode(["status" => "ok", "message" => "OPTIONS"]);
    exit;
}

// Include config.php which creates $pdo
require_once __DIR__ . '/../../config.php';

$method    = $_SERVER['REQUEST_METHOD'];
$direction = isset($_GET['direction']) ? strtolower($_GET['direction']) : null;

if ($direction === null && $method !== 'OPTIONS') {
    http_response_code(400);
    echo json_encode(["error" => "Missing 'direction' parameter (pull|push)."]);
    exit;
}

try {
    if ($method === 'GET' && $direction === 'pull') {
        pullClients($pdo);
        exit;
    }

    if ($method === 'POST' && $direction === 'push') {
        $raw  = file_get_contents('php://input');
        $data = json_decode($raw, true);

        if (!is_array($data)) {
            http_response_code(400);
            echo json_encode(["error" => "Invalid JSON payload"]);
            exit;
        }

        syncClients($pdo, $data);
        exit;
    }

    http_response_code(405);
    echo json_encode([
        "error"     => "Method/direction not allowed",
        "method"    => $method,
        "direction" => $direction
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        "error"   => "Server error",
        "details" => $e->getMessage()
    ]);
}

/**
 * GET: send all clients to desktop.
 * Must match ClientSyncDto in ClientsSync.cs:
 *  Id, ClientId, Surname, FirstName, OtherName, FullName,
 *  Gender, DateOfBirth, MaritalStatus, Nationality, StateOfOrigin,
 *  Lga, Address, Phone, AltPhone, Email,
 *  NokName, NokRelationship, NokPhone, NokAddress,
 *  CreatedAt, LastModified
 */
function pullClients(PDO $pdo)
{
    $stmt = $pdo->query("
        SELECT
            Id,
            ClientId,
            Surname,
            FirstName,
            OtherName,
            FullName,
            Gender,
            DateOfBirth,
            MaritalStatus,
            Nationality,
            StateOfOrigin,
            Lga,
            Address,
            Phone,
            AltPhone,
            Email,
            NokName,
            NokRelationship,
            NokPhone,
            NokAddress,
            CreatedAt,
            LastModified
        FROM Clients
        ORDER BY Id
    ");
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($rows);
}

/**
 * POST: receive clients from desktop.
 *
 * Conflict rules:
 *  - Incoming LastModified is ISO text from desktop; convert to MySQL datetime.
 *  - If server row exists and its LastModified is newer or equal → skip.
 *  - Otherwise insert or update full profile fields.
 */
function syncClients(PDO $pdo, array $clients)
{
    $pdo->beginTransaction();

    // Read current LastModified for an Id
    $select = $pdo->prepare("
        SELECT LastModified
        FROM Clients
        WHERE Id = :Id
    ");

    // Insert new client
    $insert = $pdo->prepare("
        INSERT INTO Clients
        (Id, ClientId, Surname, FirstName, OtherName,
         FullName, Gender, DateOfBirth, MaritalStatus, Nationality,
         StateOfOrigin, Lga, Address, Phone, AltPhone, Email,
         NokName, NokRelationship, NokPhone, NokAddress,
         CreatedAt, LastModified)
        VALUES
        (:Id, :ClientId, :Surname, :FirstName, :OtherName,
         :FullName, :Gender, :DateOfBirth, :MaritalStatus, :Nationality,
         :StateOfOrigin, :Lga, :Address, :Phone, :AltPhone, :Email,
         :NokName, :NokRelationship, :NokPhone, :NokAddress,
         :CreatedAt, :LastModified)
    ");

    // Update existing client
    $update = $pdo->prepare("
        UPDATE Clients
        SET ClientId       = :ClientId,
            Surname        = :Surname,
            FirstName      = :FirstName,
            OtherName      = :OtherName,
            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,
            CreatedAt      = :CreatedAt,
            LastModified   = :LastModified
        WHERE Id = :Id
    ");

    $count = 0;

    foreach ($clients as $c) {
        $id = isset($c['Id']) ? (int)$c['Id'] : null;
        if ($id === null) {
            continue;
        }

        $clientId  = $c['ClientId']  ?? null;
        $surname   = $c['Surname']   ?? null;
        $firstName = $c['FirstName'] ?? null;
        $otherName = $c['OtherName'] ?? null;
        $fullName  = $c['FullName']  ?? '';
        $gender    = $c['Gender']    ?? null;
        $dob       = $c['DateOfBirth'] ?? null;     // "YYYY-MM-DD" or null
        $marital   = $c['MaritalStatus'] ?? null;
        $nation    = $c['Nationality'] ?? null;
        $state     = $c['StateOfOrigin'] ?? null;
        $lga       = $c['Lga'] ?? null;
        $address   = $c['Address'] ?? null;
        $phone     = $c['Phone'] ?? null;
        $altPhone  = $c['AltPhone'] ?? null;
        $email     = $c['Email'] ?? null;
        $nokName   = $c['NokName'] ?? null;
        $nokRel    = $c['NokRelationship'] ?? null;
        $nokPhone  = $c['NokPhone'] ?? null;
        $nokAddr   = $c['NokAddress'] ?? null;
        $createdAt = $c['CreatedAt'] ?? date('Y-m-d H:i:s');

        // Incoming LastModified from desktop (ISO)
        $incomingLast = $c['LastModified'] ?? null;
        if ($incomingLast === null) {
            $incomingLast = gmdate('Y-m-d\TH:i:s\Z');
        }
        $incomingTime = strtotime($incomingLast);
        if ($incomingTime === false) {
            $incomingTime = time();
        }
        $incomingLastMysql = gmdate('Y-m-d H:i:s', $incomingTime);

        // Check existing server row
        $select->execute([':Id' => $id]);
        $row = $select->fetch(PDO::FETCH_ASSOC);

        if (!$row) {
            // New client → INSERT
            $insert->execute([
                ':Id'            => $id,
                ':ClientId'      => $clientId,
                ':Surname'       => $surname,
                ':FirstName'     => $firstName,
                ':OtherName'     => $otherName,
                ':FullName'      => $fullName,
                ':Gender'        => $gender,
                ':DateOfBirth'   => $dob,
                ':MaritalStatus' => $marital,
                ':Nationality'   => $nation,
                ':StateOfOrigin' => $state,
                ':Lga'           => $lga,
                ':Address'       => $address,
                ':Phone'         => $phone,
                ':AltPhone'      => $altPhone,
                ':Email'         => $email,
                ':NokName'       => $nokName,
                ':NokRelationship'=> $nokRel,
                ':NokPhone'      => $nokPhone,
                ':NokAddress'    => $nokAddr,
                ':CreatedAt'     => $createdAt,
                ':LastModified'  => $incomingLastMysql,
            ]);

            $count++;
            continue;
        }

        // Existing row → compare LastModified
        $serverLast = $row['LastModified'];
        if (!empty($serverLast)) {
            $serverTime = strtotime($serverLast);
            if ($serverTime !== false && $incomingTime <= $serverTime) {
                // Server newer or equal → skip
                continue;
            }
        }

        // Desktop newer → UPDATE
        $update->execute([
            ':Id'            => $id,
            ':ClientId'      => $clientId,
            ':Surname'       => $surname,
            ':FirstName'     => $firstName,
            ':OtherName'     => $otherName,
            ':FullName'      => $fullName,
            ':Gender'        => $gender,
            ':DateOfBirth'   => $dob,
            ':MaritalStatus' => $marital,
            ':Nationality'   => $nation,
            ':StateOfOrigin' => $state,
            ':Lga'           => $lga,
            ':Address'       => $address,
            ':Phone'         => $phone,
            ':AltPhone'      => $altPhone,
            ':Email'         => $email,
            ':NokName'       => $nokName,
            ':NokRelationship'=> $nokRel,
            ':NokPhone'      => $nokPhone,
            ':NokAddress'    => $nokAddr,
            ':CreatedAt'     => $createdAt,
            ':LastModified'  => $incomingLastMysql,
        ]);

        $count++;
    }

    $pdo->commit();

    echo json_encode([
        "status" => "ok",
        "entity" => "clients",
        "synced" => $count
    ]);
}
