<?php
// syncUsers.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;
}

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

$method = $_SERVER['REQUEST_METHOD'];

try {
    if ($method === 'GET') {
        // PULL: send all users to desktop
        pullUsers($pdo);
        exit;
    }

    if ($method === 'POST') {
        // PUSH: receive users from desktop
        $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;
        }

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

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

// ---------- GET: PULL USERS TO DESKTOP ----------

function pullUsers(PDO $pdo)
{
    // Matches what your desktop expects: Id, FullName, Username, Email, Role, AllowWebAccess, PasswordHash, LastModified
    $stmt = $pdo->query("
        SELECT
            Id,
            FullName,
            Username,
            Email,
            Role,
            AllowWebAccess,
            PasswordHash,
            LastModified
        FROM Users
        ORDER BY Id
    ");
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($rows);
}

// ---------- POST: PUSH USERS FROM DESKTOP (CONFLICT-AWARE) ----------

// Same logic as your existing syncUsers() in old sync.php, just in its own file
function syncUsers(PDO $pdo, array $users)
{
    $pdo->beginTransaction();

    // Get current LastModified for an existing user by Id
    $select = $pdo->prepare("SELECT LastModified FROM Users WHERE Id = :Id");

    // Insert new user
    $insert = $pdo->prepare("
        INSERT INTO Users
        (Id, FullName, Username, Email, Role, AllowWebAccess, PasswordHash, LastModified)
        VALUES
        (:Id, :FullName, :Username, :Email, :Role, :AllowWebAccess, :PasswordHash, :LastModified)
    ");

    // Update existing user if desktop is newer
    $update = $pdo->prepare("
        UPDATE Users
        SET FullName       = :FullName,
            Username       = :Username,
            Email          = :Email,
            Role           = :Role,
            AllowWebAccess = :AllowWebAccess,
            PasswordHash   = :PasswordHash,
            LastModified   = :LastModified
        WHERE Id = :Id
    ");

    $count = 0;

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

        $fullName = $u['FullName']    ?? '';
        $username = $u['Username']    ?? '';
        $email    = $u['Email']       ?? '';
        $role     = $u['Role']        ?? '';
        $allow    = !empty($u['AllowWebAccess']) ? 1 : 0;
        $hash     = $u['PasswordHash'] ?? '';

        // Incoming LastModified from desktop (ISO)
        $incomingLast = $u['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);

        // 1) Try find by Id
        $select->execute([':Id' => $id]);
        $row = $select->fetch(PDO::FETCH_ASSOC);

        if (!$row) {
            // 2) If not found by Id, try find by Username
            $selectByUsername = $pdo->prepare("SELECT Id, LastModified FROM Users WHERE Username = :Username");
            $selectByUsername->execute([':Username' => $username]);
            $rowByUser = $selectByUsername->fetch(PDO::FETCH_ASSOC);

            if ($rowByUser) {
                // Treat as same user: adopt server Id and LastModified
                $serverId   = (int)$rowByUser['Id'];
                $serverLast = $rowByUser['LastModified'];

                $serverTime = $serverLast ? strtotime($serverLast) : null;
                if ($serverTime !== null && $incomingTime <= $serverTime) {
                    // Server is newer or equal → skip
                    continue;
                }

                // Update existing row (by server Id)
                $update->execute([
                    ':Id'             => $serverId,
                    ':FullName'       => $fullName,
                    ':Username'       => $username,
                    ':Email'          => $email,
                    ':Role'           => $role,
                    ':AllowWebAccess' => $allow,
                    ':PasswordHash'   => $hash,
                    ':LastModified'   => $incomingLastMysql,
                ]);

                $count++;
                continue;
            }

            // 3) Not found by Id or Username → INSERT new user
            $insert->execute([
                ':Id'             => $id,
                ':FullName'       => $fullName,
                ':Username'       => $username,
                ':Email'          => $email,
                ':Role'           => $role,
                ':AllowWebAccess' => $allow,
                ':PasswordHash'   => $hash,
                ':LastModified'   => $incomingLastMysql,
            ]);

            $count++;
            continue;
        }

        // Existing row found by Id → compare LastModified and UPDATE if desktop is newer
        $serverLast = $row['LastModified'];
        if (!empty($serverLast)) {
            $serverTime = strtotime($serverLast);
            if ($incomingTime <= $serverTime) {
                // Server is newer or equal → skip
                continue;
            }
        }

        $update->execute([
            ':Id'             => $id,
            ':FullName'       => $fullName,
            ':Username'       => $username,
            ':Email'          => $email,
            ':Role'           => $role,
            ':AllowWebAccess' => $allow,
            ':PasswordHash'   => $hash,
            ':LastModified'   => $incomingLastMysql,
        ]);

        $count++;
    }

    $pdo->commit();

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