<?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';
date_default_timezone_set('Asia/Bangkok');
$database = new Database();
$db = $database->getConnection();

$validate = new Validate($db);

$data = json_decode(file_get_contents("php://input"));

$validate->checkin_id = $data->checkin_id;
$validate->checkout_date = $data->checkout_date;

$check_in_items = array();

$stmt = $validate->getCheckInDetailForCheckOutWithDate();
$num = $stmt->rowCount();

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

        if($description=="Cash"){
            $des="Deposit (Cash)";
        }else if($description=="Online"){
            $des="Deposit (Online)";
        }else{
            $des=$description;
        }

        $item = array(
            "date" => $date,
            "description" => $des,
            "deposit" => floatval($deposit),
            "charges" => floatval($charges),
        );
        array_push($check_in_items, $item);
    }
}

$deposit_charges = array_sum(array_column($check_in_items, 'deposit'));
$check_in_charges = array_sum(array_column($check_in_items, 'charges'));

$net_amount = $check_in_charges - $deposit_charges;

$check_in = array(
    "check_in_items" => $check_in_items,
    "total_charges" => round($check_in_charges, 2),
    "deposit_charges" => round($deposit_charges, 2),
    "net_amount" => round($net_amount, 2),
);

echo json_encode($check_in);
?>
