<?php

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

if ($conn->connect_error) {
    die("DB Connection Failed");
}

$conn->set_charset("utf8");

/* PHP 5.6 compatible input handling */
$token = isset($_GET['token']) ? $_GET['token'] : '';
$lastSync = isset($_GET['last_sync']) ? $_GET['last_sync'] : '1970-01-01 00:00:00';
$limit = 300;

/* Security check */
if ($token !== 'BOOKING_SYNC_SECRET') {
    header("HTTP/1.1 403 Forbidden");
    exit('Unauthorized');
}

$sql = "
    SELECT *
    FROM bookings
    WHERE created_at > ?
    ORDER BY created_at ASC
    LIMIT $limit
";

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

$stmt->bind_param("s", $lastSync);
$stmt->execute();

/* ✅ PHP 5.6 way (NO get_result) */
$result = $stmt->bind_result(
    $id,
    $room_no,
    $customer_id,
    $check_in,
    $user,
    $status,
    $created_at,
    $ostatus,
    $additional_ser,
    $addi_pax,
    $rprice,
    $bill_id
);

$data = array();

while ($stmt->fetch()) {
    $data[] = array(
        'id' => $id,
        'room_no' => $room_no,
        'customer_id' => $customer_id,
        'check_in' => $check_in,
        'user' => $user,
        'status' => $status,
        'created_at' => $created_at,
        'ostatus' => $ostatus,
        'additional_ser' => $additional_ser,
        'addi_pax' => $addi_pax,
        'rprice' => $rprice,
        'bill_id' => $bill_id
    );
}

echo json_encode($data);

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