<?php


$conn = new mysqli(
    "localhost",
    "ahresortmy_usenfi",
    "O2rb17Iuah3j",
    "ahresortmy_newfi"
);

if ($conn->connect_error) {
    http_response_code(500);
    exit("DB Connection Failed");
}

$conn->set_charset("latin1");

/* ---------- LAST SYNC STATE ---------- */
$stateFile = __DIR__ . '/last_booking_sync.txt';
$lastSync = file_exists($stateFile)
    ? trim(file_get_contents($stateFile))
    : '1970-01-01 00:00:00';

/* ---------- API CALL ---------- */
$url = "https://arnimresort.com/corn/web_bookings.php"
     . "?token=BOOKING_SYNC_SECRET"
     . "&last_sync=" . urlencode($lastSync);

$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_TIMEOUT => 30
]);

$json = curl_exec($ch);

if ($json === false) {
    die("cURL Error: " . curl_error($ch));
}
curl_close($ch);

/* ---------- JSON DECODE ---------- */
$data = json_decode($json, true);
if (!is_array($data) || empty($data)) {
    exit("No new data");
}

/* ---------- INSERT / UPDATE ---------- */
foreach ($data as $b) {

    $stmt = $conn->prepare("
        INSERT INTO web_booking
        (
            id, name, phone, date1, date2,
            room, room_id, sms, vcad, vcch,
            user_ip, input_time
        )
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?)
        ON DUPLICATE KEY UPDATE
            name       = VALUES(name),
            phone      = VALUES(phone),
            date1      = VALUES(date1),
            date2      = VALUES(date2),
            room       = VALUES(room),
            room_id    = VALUES(room_id),
            sms        = VALUES(sms),
            vcad       = VALUES(vcad),
            vcch       = VALUES(vcch),
            user_ip    = VALUES(user_ip)
    ");

    if (!$stmt) {
        die("Prepare failed: " . $conn->error);
    }

    $stmt->bind_param(
        "issssiiiiiss",
        $b['id'],
        $b['name'],
        $b['phone'],
        $b['date1'],
        $b['date2'],
        $b['room'],
        $b['room_id'],
        $b['sms'],
        $b['vcad'],
        $b['vcch'],
        $b['user_ip'],
        $b['input_time']
    );

    $stmt->execute();
    $stmt->close();

    // update last sync time
    $lastSync = $b['input_time'];
}

/* ---------- SAVE LAST SYNC ---------- */
file_put_contents($stateFile, $lastSync);

$conn->close();
echo "Complete";
