<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

include_once '../config/database.php';
include_once '../objects/reservation_deleted.php';

$database = new Database();
$db = $database->getConnection();

$reservation = new ReservationDelete($db);

$all_reservation_details = array();
$stmt = $reservation->getReservationListDetail();
$num = $stmt->rowCount();

if ($num > 0) {
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        extract($row);

        $detail_item = array(
            "reservation_no" => $reservation_no,
            "date" => $date,
            "room_no" => $room_no,
            "room_rate" => $room_rate,
            "extra_bed" => $extra_bed,
            "extra_bed_rate" => $extra_bed_rate,
            "extra_person" => $extra_person,
            "extra_person_rate" => $extra_person_rate,
            "total" => $room_rate + ($extra_bed * $extra_bed_rate) + ($extra_person * $extra_person_rate)
        );
        array_push($all_reservation_details, $detail_item);
    }
}

$stmt = $reservation->getReservationList();
$num = $stmt->rowCount();

$response = array();
$response["records"] = array();

if ($num > 0) {
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        extract($row);

        $filtered_reservation_items = array_filter($all_reservation_details, function ($item) use ($reservation_no, $room_no) {
            return $item['reservation_no'] === $reservation_no && $item['room_no'] === $room_no;
        });

        $item = array(
            $reservation_no,
            $agent_name,
            $guest_name,
            $room_no,
            $checkin_date,
            $checkout_date,
            $nights,
            $net_amount,
            $deposit,
            $date_time,
            $remark,
            array_values($filtered_reservation_items) 
        );

        array_push($response["records"], $item);
    }

}

echo json_encode($response);
?>
