<?php
// syncAreas.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 areas to desktop
        pullAreas($pdo);
        exit;
    }

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

        syncAreas($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 AREAS TO DESKTOP ----------

function pullAreas(PDO $pdo)
{
    // Include LastModified so desktop can do conflict resolution
    $stmt = $pdo->query("
        SELECT
            Id,
            Name,
            Description,
            BasePricePerPlot,
            LastModified
        FROM Areas
        ORDER BY Id
    ");
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($rows);
}

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

function syncAreas(PDO $pdo, array $areas)
{
    $pdo->beginTransaction();

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

    // Insert new area
    $insert = $pdo->prepare("
        INSERT INTO Areas
        (Id, Name, Description, BasePricePerPlot, LastModified)
        VALUES
        (:Id, :Name, :Description, :BasePricePerPlot, :LastModified)
    ");

    // Update existing area if desktop is newer
    $update = $pdo->prepare("
        UPDATE Areas
        SET Name            = :Name,
            Description     = :Description,
            BasePricePerPlot= :BasePricePerPlot,
            LastModified    = :LastModified
        WHERE Id = :Id
    ");

    $count = 0;

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

        $name        = $a['Name'] ?? '';
        $description = $a['Description'] ?? null;
        $basePrice   = isset($a['BasePricePerPlot']) && $a['BasePricePerPlot'] !== ''
            ? (float)$a['BasePricePerPlot']
            : null;

        // Incoming LastModified from desktop (ISO text)
        $incomingLast = $a['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) Look up existing row by Id
        $select->execute([':Id' => $id]);
        $row = $select->fetch(PDO::FETCH_ASSOC);

        if (!$row) {
            // 2) Not found → INSERT
            $insert->execute([
                ':Id'              => $id,
                ':Name'            => $name,
                ':Description'     => $description,
                ':BasePricePerPlot'=> $basePrice,
                ':LastModified'    => $incomingLastMysql,
            ]);

            $count++;
            continue;
        }

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

        $update->execute([
            ':Id'              => $id,
            ':Name'            => $name,
            ':Description'     => $description,
            ':BasePricePerPlot'=> $basePrice,
            ':LastModified'    => $incomingLastMysql,
        ]);

        $count++;
    }

    $pdo->commit();

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