<?php
// required headers
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/check_in_detail.php';
include_once '../objects/check_out.php';
include_once '../objects/check_out_detail.php';	
include_once '../objects/validate.php';
include_once '../objects/room.php';
include_once '../objects/deposit.php';

session_start();
date_default_timezone_set('Asia/Bangkok'); 

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

$checkin_detail = new CheckInDetail($db); 
$check_out = new CheckOut($db);
$check_out_detail = new CheckOutDetail($db);
$validate = new Validate($db);
$room = new Room($db);
$deposit = new Deposit($db);

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


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

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

$check_out->checkin_id = $data->checkin_id;
$check_out->room_no = $data->room_no;
$check_out->reservation_no = $data->reservation_no;
$check_out->guest_id = $data->guest_id;
$check_out->guest_name = $data->guest_name;
$check_out->checkin_date= $data->checkin_date;
$check_out->checkout_date = $data->checkout_date;
$check_out->cashier = $data->cashier;
$check_out->total_charges = $data->total_charges;
$check_out->total_payment = $data->total_deposit;	
$check_out->entry_by = isset($_SESSION['userid']) ? $_SESSION['userid'] : "";

$check_out_detail->checkin_id = $data->checkin_id;

$room->room_number = $data->room_no;

	if($checkin_detail->deleteC()){
	 	if($validate->deleteC()){
	 		$room->updateFromOccupied();
		 	$checkin_detail->updateCheckOut();
			$deposit->updateCheckOut();
		 	if($check_out->create()){
				foreach($data->details as $detail){
					$check_out_detail->checkout_id = $check_out->id;
					$check_out_detail->date = $detail->date;
					$check_out_detail->description = $detail->description;
					$check_out_detail->payment = $detail->payment;
					$check_out_detail->charges = $detail->charges;

					if(!$check_out_detail->create()){
						$msg_arr = array(
							"message" => "error",
							"table" => "check_out_detail"
						);
						echo json_encode($msg_arr);
						die();
					}
				}
				
				$msg_arr = array(
					"message" => "created",
					"checkout_id" => $check_out->id
				);
				echo json_encode($msg_arr);	
			}
		}
	 }else{
		$msg_arr = array(
			"message" => "error",
			"table" => "checkout"
		);
		echo json_encode($msg_arr);
	}

?>