<?php
require_once("class.setting.php");
require_once("class.kbelocale.php");
class Booking
{
    /////
    private $helper;
    /////////
    private $restapi;
    ////
    public $settings;
    ////////
    public $utils;
    ////////////
    public $setting;
    ////////////////
    private $dbUtils;

    public $locale;

    public function __construct($auth, $restapi = null)
    {
        $company = $auth["company"];
        extract($company);
        ///////////////////////////////////////////
        $this->restapi = $restapi;
        $this->utils = new Utils();

        /////////////////////////////////////////////
        $this->dbUtils = new DBUtils($db_name);
        $this->setting = new Setting($restapi, $db_name);
        $this->settings = $this->setting->getSettings($id);
        /////////////////////////////////////////////
        $timezone = $this->settings["PMS_TIME_ZONE"]["entry_value"];
        ////////////////////////////////////////////////
        date_default_timezone_set($timezone);
        /////////////////////////////////////////
        if (!$this->dbUtils->isDBInService()) {
            die($this->restapi->Response(["message" => "Failed to connect to the database, please try again laiter", "success" => false], 500));
        }
        /////////////////////////////////////////
        $this->locale = new KBELocale($auth, $restapi);
    }
    ###########################################
    public function getAllPackages()
    {
        $results = [];
        $stmt = $this->dbUtils->runQuery("SELECT * FROM pm_package");
        $stmt->execute();
        while ($response = $stmt->fetch(PDO::FETCH_ASSOC)) {
            array_push($results, $response);
        }
        return $results;
    }

    public function getPackageById($packageid)
    {
        $response = array();
        $stmt = $this->dbUtils->runQuery("SELECT * FROM pm_package WHERE id=:upkgid");
        $stmt->bindparam(":upkgid", $packageid);
        $stmt->execute();
        $counter = $stmt->rowCount();
        if ($counter > 0) {
            $response = $stmt->fetch(PDO::FETCH_ASSOC);
            $response["success"] = true;
        } else {
            return array("message" => "Package doesn't exist", "success" => false);
        }
        ///////////////
        return $response;
    }


    ###########################################
    public function getAllRooms()
    {
        $lang = $this->locale->_initLang();
        $results = [];
        $stmt = $this->dbUtils->runQuery("SELECT * FROM pm_room WHERE lang=:ulang");
        $stmt->bindparam(":ulang", $lang["id"]);
        $stmt->execute();
        while ($response = $stmt->fetch(PDO::FETCH_ASSOC)) {
            array_push($results, $response);
        }
        return $results;
    }

    public function getRoomsById($roomid)
    {
        $response = array();
        $stmt = $this->dbUtils->runQuery("SELECT * FROM pm_room WHERE id=:uroomid");
        $stmt->bindparam(":uroomid", $roomid);
        $stmt->execute();
        $counter = $stmt->rowCount();
        if ($counter > 0) {
            $response = $stmt->fetch(PDO::FETCH_ASSOC);
            $response["success"] = true;
        } else {
            return array("message" => "Room doesn't exist", "success" => false);
        }
        ///////////////
        return $response;
    }


    public function RoomsExits($roomid)
    {
        $stmt = $this->dbUtils->runQuery("SELECT * FROM pm_room WHERE id=:uroomid");
        $stmt->bindparam(":uroomid", $roomid);
        $stmt->execute();
        $counter = $stmt->rowCount();
        if ($counter > 0) {
            return true;
        } else {
            return true;
        }
    }

    ###########################################
    public function getAllRoomRates($roomid)
    {
        $results = [];
        $stmt = $this->dbUtils->runQuery("SELECT * FROM pm_rate WHERE id_room=:uroomid");
        $stmt->bindparam(":uroomid", $roomid);
        $stmt->execute();
        while ($response = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $id_room = $response["id_room"];
            $id_package = $response["id_package"];
            $response["room"] = $this->getRoomsById($id_room);
            $response["package"] = $this->getPackageById($id_package);
            array_push($results, $response);
        }
        return $results;
    }

    public function getRoomRateById($roomrateid)
    {
        $response = array();
        $stmt = $this->dbUtils->runQuery("SELECT * FROM pm_rate WHERE id=:uroomrateid");
        $stmt->bindparam(":uroomrateid", $roomrateid);
        $stmt->execute();
        $counter = $stmt->rowCount();
        if ($counter > 0) {
            $response = $stmt->fetch(PDO::FETCH_ASSOC);
            $response["success"] = true;
        } else {
            return array("message" => "Room rate doesn't exist", "success" => false);
        }
        ///////////////
        return $response;
    }

    ###########################################
    public function getAllRoomServices()
    {
        $lang = $this->locale->_initLang();
        $results = [];
        $stmt = $this->dbUtils->runQuery("SELECT * FROM pm_service WHERE lang=:ulang");
        $stmt->bindparam(":ulang", $lang["id"]);
        $stmt->execute();
        while ($response = $stmt->fetch(PDO::FETCH_ASSOC)) {
            array_push($results, $response);
        }
        return $results;
    }

    public function getRoomServiceById($serviceid)
    {
        $response = array();
        $stmt = $this->dbUtils->runQuery("SELECT * FROM pm_service WHERE id=:uroomserviceid");
        $stmt->bindparam(":uroomserviceid", $serviceid);
        $stmt->execute();
        $counter = $stmt->rowCount();
        if ($counter > 0) {
            $response = $stmt->fetch(PDO::FETCH_ASSOC);
            $response["success"] = true;
        } else {
            return array("message" => "Room service doesn't exist", "success" => false);
        }
        ///////////////
        return $response;
    }

    ###########################################
    public function getAllActivities()
    {
        $lang = $this->locale->_initLang();
        $results = [];
        $stmt = $this->dbUtils->runQuery("SELECT * FROM pm_activity WHERE lang=:ulang");
        $stmt->bindparam(":ulang", $lang["id"]);
        $stmt->execute();
        while ($response = $stmt->fetch(PDO::FETCH_ASSOC)) {
            array_push($results, $response);
        }
        return $results;
    }

    public function getActivityById($activityid)
    {
        $response = array();
        $stmt = $this->dbUtils->runQuery("SELECT * FROM pm_activity WHERE id=:uactivityid");
        $stmt->bindparam(":uactivityid", $activityid);
        $stmt->execute();
        $counter = $stmt->rowCount();
        if ($counter > 0) {
            $response = $stmt->fetch(PDO::FETCH_ASSOC);
            $response["success"] = true;
        } else {
            return array("message" => "Activity doesn't exist", "success" => false);
        }
        ///////////////
        return $response;
    }

    public function isBookingStatus($status)
    {
        try {
            $status = intval($status);
            if ($status == 1 || $status == 2 || $status == 3 || $status == 4) {
                return true;
            } else {
                return false;
            }
        } catch (Exception $e) {
            return false;
        }
    }

    ###########################################
    public function getAllBookings($id_user = null, $status = null)
    {
        $lang = $this->locale->_initLang();
        $currency = $this->locale->getDefaultCurrency();
        ///////////////////////////////////////
        $results = [];
        if ($id_user == null) {
            ///////////////////////////////////////
            if ($status == null) {
                $status_query = " WHERE status=1 OR status=4";
            } else {
                if ($this->isBookingStatus($status)) {
                    $status = intval($status);
                    $status_query = " WHERE status=$status";
                } else {
                    $status_query = " WHERE status=1 OR status=4";
                }
            }
            //////////////////////////////////////
            $stmt = $this->dbUtils->runQuery("SELECT * FROM pm_booking $status_query");
            $stmt->execute();
        } else {
            ///////////////////////////////////////
            if ($status == null) {
                $status_query = " AND status=1 OR status=4";
            } else {
                if ($this->isBookingStatus($status)) {
                    $status = intval($status);
                    $status_query = " WHERE status=$status";
                } else {
                    $status_query = " WHERE status=1 OR status=4";
                }
            }
            //////////////////////////////////////
            $stmt = $this->dbUtils->runQuery("SELECT * FROM pm_booking WHERE id_user=:uid_user $status_query");
            $stmt->bindparam(":uid_user", $id_user);
            $stmt->execute();
        }
        while ($response = $stmt->fetch(PDO::FETCH_ASSOC)) {
            // Services
            $rooms_item = [];
            $bookingid = $response["id"];
            $status = intval($response["status"]);
            //////////////////////////////////////////////
            $statusname = "";
            if ($status == 1) {
                $statusname = "Pending";
            } else if ($status == 2) {
                $statusname = "Cancelled";
            } else if ($status = 3) {
                $statusname = "Payment rejected";
            } else {
                $statusname = "Confirmed";
            }
            //////////////////////////////////////////
            $rooms = $this->getBookedRoomsById($bookingid);
            foreach ($rooms as $room) {
                $children = $room["children"] == null ? 0   : $room["children"];
                $totalpax = $room["adults"] + $children;
                ////////////////////////////////////
                array_push(
                    $rooms_item,
                    array(
                        "service_id" => $room["id_room"],
                        "service_name" => $room["title"],
                        "quantity" => $totalpax,
                        "amount" => $room["amount"],
                        "children" => $children,
                        "adults" => $room["adults"],
                        "mark" => "room_service",
                        "default_currency" => "1",
                        "description" => "room"
                    )
                );
            }
            ////////////////////////////////////////////////////////////
            $services = $this->getBookedServicesById($bookingid);
            foreach ($services as $service) {
                $schildren = $response["children"] == null ? 0   : $response["children"];
                $stotalpax = $response["adults"] + $schildren;
                ////////////////////////////////////
                array_push(
                    $rooms_item,
                    array(
                        "service_id" => $service["id_service"],
                        "service_name" => $service["title"],
                        "quantity" => $stotalpax,
                        "amount" => $service["amount"],
                        "children" => $schildren,
                        "adults" => $response["adults"],
                        "mark" => "additional_service",
                        "default_currency" => "1",
                        "description" => "extra_service"
                    )
                );
            }
            //////////////////////////////////////////////////////////////////////
            $payments = $this->getBookedPaymentsById($bookingid);
            ////////////////////////////
            $checkin = $this->formartDateUnixTime($response["from_date"]);
            $checkout = $this->formartDateUnixTime($response["to_date"]);
            $restime = $this->formartDateTimeUnixTime($response["add_date"]);
            $edit_date = $this->formartDateTimeUnixTime($response["edit_date"]);
            $child_count = $response["children"] == null ? 0   : $response["children"];
            $restotalpax = $response["adults"] + $child_count;
            // //// reservation
            // payment_options
            // MO : Money Order
            // CC : Credit Card given
            // POS : Payed with payment system
            // PayPal : Payed with PayPal
            $reservation_item = array(
                "client_id" => $response["id_user"],
                "first_name" => trim($response["firstname"]),
                "surname" => trim($response["lastname"]),
                "title" => "1",
                "street_addr" => trim($response["address"]),
                "city" => $response["city"],
                "province" => "state",
                "zip" => $response["postcode"],
                "country" => trim($response["country"]),
                "phone" => $response["phone"],
                "fax" => "9090",
                "email" => $response["email"],
                "password" => "",
                "id_type" => "National",
                "id_number" => "12345",
                "additional_comments" => $response["comments"],
                "ip" => "185.196.21.115",
                "existing_client" => "1",
                "offline_status" => $status,
                "offline_status_name" => $statusname,
                "booking_id" => $response["id"],
                "booking_time" => $restime,
                "start_date" => $checkin,
                "end_date" => $checkout,
                "nights" => $response["nights"],
                "edit_date" => $edit_date,
                "edit_date_unix" => $response["edit_date"],
                "child_count" => $response["children"] == null ? 0   : $response["children"],
                "extra_guest_count" => "0",
                "discount_coupon" => null,
                "total_cost" => $response["total"],
                "payment_amount" => $response["paid"],
                "payment_type" => $response["payment_option"],
                "payment_success" => $response["payment_option"] == "arrival" ? "0" : "1",
                "payment_txnid" => "",
                "payments" => $this->isSequential($payments) ? $payments : [],
                "otaname" => "Karibu Booking engine",
                "source" => "Website",
                "paypal_email" => $response["payment_option"] == "paypal" ? $response["email"] : null,
                "special_id" => "0",
                "special_requests" => $response["comments"],
                "is_block" => "0",
                "is_deleted" => "0",
                "changetoken" => "",
                "res_code" => "",
                "block_name" => null,
                "pax" => $restotalpax,
                "default_currency" => "1",
                "currency" => $currency,
                "lang" => $lang,
                "additional_services" => $rooms_item,

            );
            array_push($results, $reservation_item);
        }
        return $results;
    }


    public function getBookingById($bookingid)
    {
        $lang = $this->locale->_initLang();
        $currency = $this->locale->getDefaultCurrency();
        ///////////////////////////////////////
        $response = array();
        $stmt = $this->dbUtils->runQuery("SELECT * FROM pm_booking WHERE id=:ubookingid");
        $stmt->bindparam(":ubookingid", $bookingid);
        $stmt->execute();
        $counter = $stmt->rowCount();
        if ($counter > 0) {
            $response = $stmt->fetch(PDO::FETCH_ASSOC);
            // Services
            $rooms_item = [];
            $bookingid = $response["id"];
            $status = intval($response["status"]);
            //////////////////////////////////////////////
            $statusname = "";
            if ($status == 1) {
                $statusname = "Pending";
            } else if ($status == 2) {
                $statusname = "Cancelled";
            } else if ($status = 3) {
                $statusname = "Payment rejected";
            } else {
                $statusname = "Confirmed";
            }
            //////////////////////////////////////////
            $rooms = $this->getBookedRoomsById($bookingid);
            foreach ($rooms as $room) {
                $children = $room["children"] == null ? 0   : $room["children"];
                $totalpax = $room["adults"] + $children;
                ////////////////////////////////////
                array_push(
                    $rooms_item,
                    array(
                        "service_id" => $room["id_room"],
                        "service_name" => $room["title"],
                        "quantity" => $totalpax,
                        "amount" => $room["amount"],
                        "children" => $children,
                        "adults" => $room["adults"],
                        "mark" => "room_service",
                        "default_currency" => "1",
                        "description" => "room"
                    )
                );
            }
            ////////////////////////////////////////////////////////////
            $services = $this->getBookedServicesById($bookingid);
            foreach ($services as $service) {
                $schildren = $response["children"] == null ? 0   : $response["children"];
                $stotalpax = $response["adults"] + $schildren;
                ////////////////////////////////////
                array_push(
                    $rooms_item,
                    array(
                        "service_id" => $service["id_service"],
                        "service_name" => $service["title"],
                        "quantity" => $stotalpax,
                        "amount" => $service["amount"],
                        "children" => $schildren,
                        "adults" => $response["adults"],
                        "mark" => "additional_service",
                        "default_currency" => "1",
                        "description" => "extra_service"
                    )
                );
            }
            //////////////////////////////////////////////////////////////////////
            $payments = $this->getBookedPaymentsById($bookingid);
            ////////////////////////////
            $checkin = $this->formartDateUnixTime($response["from_date"]);
            $checkout = $this->formartDateUnixTime($response["to_date"]);
            $restime = $this->formartDateTimeUnixTime($response["add_date"]);
            $edit_date = $this->formartDateTimeUnixTime($response["edit_date"]);
            $child_count = $response["children"] == null ? 0   : $response["children"];
            $restotalpax = $response["adults"] + $child_count;
            // //// reservation
            // payment_options
            // MO : Money Order
            // CC : Credit Card given
            // POS : Payed with payment system
            // PayPal : Payed with PayPal
            return array(
                "client_id" => $response["id_user"],
                "first_name" => trim($response["firstname"]),
                "surname" => trim($response["lastname"]),
                "title" => "1",
                "street_addr" => trim($response["address"]),
                "city" => $response["city"],
                "province" => "state",
                "zip" => $response["postcode"],
                "country" => trim($response["country"]),
                "phone" => $response["phone"],
                "fax" => "9090",
                "email" => $response["email"],
                "password" => "",
                "id_type" => "National",
                "id_number" => "12345",
                "additional_comments" => $response["comments"],
                "ip" => "185.196.21.115",
                "existing_client" => "1",
                "offline_status" => $status,
                "offline_status_name" => $statusname,
                "booking_id" => $response["id"],
                "booking_time" => $restime,
                "start_date" => $checkin,
                "end_date" => $checkout,
                "nights" => $response["nights"],
                "edit_date" => $edit_date,
                "edit_date_unix" => $response["edit_date"],
                "child_count" => $response["children"] == null ? 0   : $response["children"],
                "extra_guest_count" => "0",
                "discount_coupon" => null,
                "total_cost" => $response["total"],
                "payment_amount" => $response["paid"],
                "payment_type" => $response["payment_option"],
                "payment_success" => $response["payment_option"] == "arrival" ? "0" : "1",
                "payment_txnid" => "",
                "payments" => $this->isSequential($payments) ? $payments : [],
                "otaname" => "Karibu Booking engine",
                "source" => "Website",
                "paypal_email" => $response["payment_option"] == "paypal" ? $response["email"] : null,
                "special_id" => "0",
                "special_requests" => $response["comments"],
                "is_block" => "0",
                "is_deleted" => "0",
                "changetoken" => "",
                "res_code" => "",
                "block_name" => null,
                "pax" => $restotalpax,
                "default_currency" => "1",
                "currency" => $currency,
                "lang" => $lang,
                "additional_services" => $rooms_item,
                "success" => true,

            );
        } else {
            return array("message" => "Booking doesn't exist", "success" => false);
        }
        ///////////////
        return $response;
    }

    public function ConfirmBooking($bookingid)
    {
        ///////////////////////////////////////
        $response = array();
        $stmt = $this->dbUtils->runQuery("SELECT * FROM pm_booking WHERE id=:ubookingid");
        $stmt->bindparam(":ubookingid", $bookingid);
        $stmt->execute();
        $counter = $stmt->rowCount();
        if ($counter > 0) {
            $response = $stmt->fetch(PDO::FETCH_ASSOC);
            ////////////////////////////////////////////////////////////////
            $edit_date = time(); // Returns current Unix timestamp
            $status = 4; // confirm booking
            $stmt2 = $this->dbUtils->runQuery("UPDATE pm_booking SET edit_date=:ueditdate, `status`=:ustatus WHERE id=:ubookingid");
            $stmt2->bindparam(":ueditdate", $edit_date);
            $stmt2->bindparam(":ustatus", $status);
            $stmt2->bindparam(":ubookingid", $bookingid);
            if ($stmt2->execute()) {
                /////////////////////////////////////////////////////////
                return array(
                    "message" => "Booking confirmed successfully",
                    "success" => true,
                    "booking" => $this->getBookingById($bookingid),
                );
            } else {
                return array("message" => "Something went wrong, please try again", "success" => false);
            }
        } else {
            return array("message" => "Booking doesn't exist", "success" => false);
        }
        ///////////////
        return $response;
    }

    public function getBookedRoomsById($bookingid)
    {
        $results = [];
        $stmt = $this->dbUtils->runQuery("SELECT * FROM pm_booking_room WHERE id_booking=:ubookingid");
        $stmt->bindparam(":ubookingid", $bookingid);
        $stmt->execute();
        while ($response = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $id_room = $response["id_room"];
            $response["room"] = $this->getRoomsById($id_room);
            array_push($results, $response);
        }
        return $results;
    }

    public function getBookedServicesById($bookingid)
    {
        $results = [];
        $stmt = $this->dbUtils->runQuery("SELECT * FROM pm_booking_service WHERE id_booking=:ubookingid");
        $stmt->bindparam(":ubookingid", $bookingid);
        $stmt->execute();
        while ($response = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $id_service = $response["id_service"];
            $response["service"] = $this->getRoomServiceById($id_service);
            array_push($results, $response);
        }
        return $results;
    }

    public function getBookedPaymentsById($bookingid)
    {
        $results = array();
        $stmt = $this->dbUtils->runQuery("SELECT * FROM pm_booking_payment WHERE id=:ubookingid");
        $stmt->bindparam(":ubookingid", $bookingid);
        $stmt->execute();
        $counter = $stmt->rowCount();
        if ($counter > 0) {
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $row["success"] = true;
                array_push($results, $row);
            }
        } else {
            return array("message" => "Booking doesn't exist", "success" => false);
        }
        ///////////////
        return $results;
    }


    public function getUnixTimestamp($dateString, $timeZone = "Africa/Kampala")
    {
        // Create a DateTimeZone object for the specified timezone.
        try {
            $tz = new DateTimeZone($timeZone);

            // Create a new DateTime object from the date string, applying the timezone.
            // We set the time to the start of the day (midnight) to be consistent.
            $datetime = new DateTime($dateString . ' 00:00:00', $tz);

            // Return the Unix timestamp.
            return $datetime->getTimestamp();
        } catch (Exception $e) {
            // Handle any exceptions, for example, an invalid timezone name.
            echo "An error occurred: " . $e->getMessage();
            return false;
        }
    }

    public function RoomInventoryAlreadyExits($roomid, $from, $to)
    {
        $stmt = $this->dbUtils->runQuery("SELECT * FROM pm_room_closing WHERE id_room=:uroomid AND from_date=:ufrom AND to_date=:uto");
        $stmt->bindparam(":uroomid", $roomid);
        $stmt->bindparam(":ufrom", $from);
        $stmt->bindparam(":uto", $to);
        $stmt->execute();
        $counter = $stmt->rowCount();
        if ($counter > 0) {
            return true;
        } else {
            return false;
        }
    }

    function getDaysBetweenTimestamps($timestamp1, $timestamp2)
    {
        // Ensure the timestamps are in the correct order for calculation.
        $startDate = min($timestamp1, $timestamp2);
        $endDate = max($timestamp1, $timestamp2);

        // Create DateTime objects from the timestamps. The '@' symbol tells PHP
        // to treat the number as a Unix timestamp.
        $dt1 = new DateTime("@$startDate");
        $dt2 = new DateTime("@$endDate");

        // Calculate the difference between the two dates.
        // This returns a DateInterval object.
        $interval = $dt1->diff($dt2);

        // The 'days' property of the DateInterval object gives the total
        // number of days.
        return $interval->days;
    }


    function checkExpiry($timestamp)
    {
        // Get the current Unix timestamp.
        $currentTimestamp = time();
        $isExpired = false;
        $daysPassed = 0;

        // Check if the expiration timestamp is in the past.
        if ($timestamp < $currentTimestamp) {
            $isExpired = true;

            // Calculate the number of full days passed.
            // We use the DateTime class for accurate calculation.
            $dtExpiration = new DateTime("@$timestamp");
            $dtCurrent = new DateTime("@$currentTimestamp");
            $interval = $dtExpiration->diff($dtCurrent);
            $daysPassed = $interval->days;
        }

        return [
            'is_expired' => $isExpired,
            'days_passed' => $daysPassed
        ];
    }

    public function DeleteExpiredRoomClosing()
    {
        $results = array();
        //// delete expired room closing
        $stmt = $this->dbUtils->runQuery("SELECT * FROM pm_room_closing");
        $stmt->execute();
        $counter = $stmt->rowCount();
        if ($counter > 0) {
            while ($response = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $to_date = $response["to_date"];
                $from_date = $response["from_date"];
                $expiry = $this->checkExpiry($to_date);
                ///////////////////////////////////////////
                $from = $this->formartDateUnixTime($from_date);
                $to = $this->formartDateUnixTime($to_date);
                $stock = $response["stock"];
                $response["expiry"] = $expiry;
                $response["from"] = $from;
                $response["to"] = $to;
                /////////////////////////////////////////////
                if ($expiry["is_expired"] && $expiry["days_passed"] >= 30) {
                    $id = $response["id"];
                    //////////////////////////////////////
                    $stmt = $this->dbUtils->runQuery("DELETE FROM pm_room_closing WHERE `id` = :uid");
                    $stmt->bindparam(":uid", $id);
                    if ($stmt->execute()) {
                        array_push($results, array(
                            "message" => "Room closing stock $stock from $from to $to deleted successfully",
                            "success" => true,
                            "response" => $response,
                        ));
                    } else {
                        array_push($results, array(
                            "message" => "Something went wrong, please try again laiter",
                            "success" => false,
                            "response" => $response,
                        ));
                    }

                    ////////////////////////////////////////////

                } else {
                    // Delete all closing dates that are 30 days old
                    array_push($results, $response);
                }
            }
            return $results;
        } else {
            return array("message" => "No room closing dates found", "success" => false);
        }
    }
    public function PostRoomClosing($inventory)
    {
        // 30d
        $this->DeleteExpiredRoomClosing();
        $response = array();
        /////////////////////////////////////////////
        $timezone = $this->settings["PMS_TIME_ZONE"]["entry_value"];
        ////////////////////////////////////////////////
        foreach ($inventory as $inventory_item) {
            /////////////////////////////////
            $from = $inventory_item->from;
            $to = $inventory_item->to;
            ////////////////////////////////////////////////////
            $fromUnix = $this->getUnixTimestamp($from, $timezone);
            $toUnix = $this->getUnixTimestamp($to, $timezone);
            array_push($response, array("fromUnix" => $fromUnix, "toUnix" => $toUnix));
            /////////////////////////////////////////////////////
            $roomtypes = $inventory_item->roomtypes;
            foreach ($roomtypes as $roomtype) {
                $roomid = $roomtype->roomid;
                $availability = $roomtype->availability;
                if ($this->RoomsExits($roomid)) {
                    if ($this->RoomInventoryAlreadyExits($roomid, $fromUnix, $toUnix)) {
                        /// update
                        $stmt = $this->dbUtils->runQuery("
                                UPDATE pm_room_closing SET
                                stock=:ustock
                                WHERE id_room=:uroomid AND from_date=:ufrom AND to_date=:uto");
                        $stmt->bindparam(":uroomid", $roomid);
                        $stmt->bindparam(":ufrom", $fromUnix);
                        $stmt->bindparam(":uto", $toUnix);
                        $stmt->bindparam(":ustock", $availability);
                        if ($stmt->execute()) {
                            array_push($response, array(
                                "from" => $from,
                                "to"  => $to,
                                "room" => $roomtype,
                                "message" => "Updated room inventory $availability from $from to $to successfully",
                                "success" => true
                            ));
                        } else {
                            array_push($response, array(
                                "from" => $from,
                                "to"  => $to,
                                "room" => $roomtype,
                                "message" => "Something went wrong, please try again laiter",
                                "success" => true
                            ));
                        }
                    } else {
                        // insert
                        $stmt3 = $this->dbUtils->runQuery("
                        INSERT INTO pm_room_closing SET
                        id_room=:uroomid,
                        from_date=:ufrom,
                        to_date=:uto,
                        stock=:ustock");
                        $stmt3->bindparam(":uroomid", $roomid);
                        $stmt3->bindparam(":ufrom", $fromUnix);
                        $stmt3->bindparam(":uto", $toUnix);
                        $stmt3->bindparam(":ustock", $availability);
                        if ($stmt3->execute()) {
                            array_push($response, array(
                                "from" => $from,
                                "to"  => $to,
                                "room" => $roomtype,
                                "message" => "Saved room inventory $availability from $from to $to successfully",
                                "success" => true
                            ));
                        } else {
                            array_push($response, array(
                                "from" => $from,
                                "to"  => $to,
                                "room" => $roomtype,
                                "message" => "Something went wrong, please try again laiter",
                                "success" => false
                            ));
                        }
                    }
                }
            }
        }
        return array(
            "message" => "",
            "success" => true,
            "response" => $response,
        );
    }


    public function convertToJson($json)
    {
        return json_decode($json, true);
    }


    public function isSequential($arr)
    {
        return array_keys($arr) === range(0, count($arr) - 1);
    }

    public function getData()
    {
        $data_object = file_get_contents("php://input");
        if (!empty($data_object)) {
            return json_decode($data_object);
        } else {
            return null;
        }
    }

    public function formartDate($mdate)
    {
        $date = date_create($mdate);
        return date_format($date, "Y-m-d");
    }

    public function formartDateTime($mdatetime)
    {
        $datetime = date_create($mdatetime);
        return date_format($datetime, "Y-m-d H:i:s");
    }

    public function formartDateUnixTime($unixtime)
    {
        return date('Y-m-d', $unixtime);
    }

    public function formartDateTimeUnixTime($unixtime)
    {
        return date('Y-m-d H:i:s', $unixtime);
    }


    public function JsonResponse($response, $status = 200)
    {
        header("Content-Type: application/json; charset=UTF-8");
        http_response_code($status);
        return json_encode($response);
    }
}
