<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

include_once '../config/database.php';
include_once '../objects/validate.php';
include_once '../objects/room.php';

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

$validate = new Validate($db);
$room = new Room($db);
$data = json_decode(file_get_contents("php://input"));

// Validate input dates
$validate->df = $data->s;
$validate->dt = $data->e;

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

// Get total number of rooms
$arr["total_rooms"] = $room->getRoomCount(); 

// Get room status counts by date
$stmt = $validate->getRoomStatusCountByDate();
$num = $stmt->rowCount();

$totalCheckin = 0;
$totalConfirm = 0;
$totalReserve = 0;
$today = date('Y-m-d');

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

        // Add record to the array
        $item = array(
            "date" => $date,
            "no_of_room" => $count,
            "reservation_status" => $status
        );
        array_push($arr["records"], $item);

        // Sum counts for today's date
        if ($date == $today) {
            if ($status == "checkin") {
                $totalCheckin += $count;
            } elseif ($status == "confirm") {
                $totalConfirm += $count;
            } elseif ($status == "reserve") {
                $totalReserve += $count;
            }
        }
    }
}

// Add totals to the response
$arr["total_checkin"] = $totalCheckin;
$arr["total_confirm"] = $totalConfirm;
$arr["total_reserve"] = $totalReserve;
$arr["total_vacant"] = $arr["total_rooms"] - $totalCheckin - $totalConfirm - $totalReserve;
echo json_encode($arr);
?>
