<?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/reservation.php'; 
include_once '../objects/reservation_detail.php'; 
include_once '../objects/deposit.php';

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

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

$reservation = new Reservation($db);
$reservation_detail = new ReservationDetail($db);
$deposit = new Deposit($db);

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

// $reservation->reservation_no = 'R-' . date('ym') . '-' . uniqid();
$reservation->date_time = $data->date_time;
$reservation->reservation_no = $data->reservation_no;
$reservation->reservation_no_old = $data->reservation_no_old;
$reservation->folio_no = $data->folio_no;
$reservation->agent_id = $data->agent_id;
$reservation->agent_name = $data->agent_name;
$reservation->guest_id = $data->guest_id;
$reservation->guest_name = $data->guest_name;
$reservation->remark = $data->remark;
$reservation->adult = $data->adult;
$reservation->child = $data->child;

$reservation->room_type = $data->room_type;
$reservation->bed_type = $data->bed_type;
$reservation->room_no = $data->room_no;

$reservation->entry_by = isset($_SESSION['user']) ? $_SESSION['user'] : "";
$reservation->update_by = isset($_SESSION['user']) ? $_SESSION['user'] : "";

$reservation_detail->reservation_no_old = $reservation->reservation_no_old;
$reservation_detail->reservation_no = $reservation->reservation_no; 

$deposit->reservation_no_old = $reservation->reservation_no_old; 
$deposit->reservation_no = $reservation->reservation_no; 

if ($reservation->checkReservation()) {
    echo json_encode(array("message" => "duplicate"));
    die();
} 

$reservation_detail->DeleteReservationReal();

foreach ($data->stayDetails as $detail) {

    $reservation_detail->date = $detail->date;    
    $reservation_detail->room_rate = $detail->room_rate; 
    $reservation_detail->extra_bed = $detail->extra_bed; 
    $reservation_detail->extra_bed_rate = $detail->extra_bed_rate; 
    $reservation_detail->extra_person = $detail->extra_person;
    $reservation_detail->extra_person_rate = $detail->extra_person_rate;
    $reservation_detail->create();

}

$deposit->updateReservation();

if ($reservation->updateReservation()) {
    echo json_encode(array("message" => "created"));
    die();
} 



?>
