<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

    class Order extends CI_Controller {

        function __construct() {

            parent::__construct();
            $this->load->library('Formatslist');
            
        }
        public function set_timezone() {
            $this->db->select('TIMEZONE');
            $this->db->from('CONFIGURATION');
            $query = $this->db->get();
            if ($query->num_rows() > 0) {
                date_default_timezone_set($query->row()->TIMEZONE);
            } else {
                return false;
            }
        }

        // public function post() {
        //     try {
        //         $jsonStr = file_get_contents('php://input');
        //         $jsonObj = json_decode($jsonStr);
        
        //         // Assuming $jsonObj->order is already an object, not a JSON string
        //         $jsonOrder = $jsonObj->order;
        
        //         $apporderid = uniqid();
        //         // $timezone = date_default_timezone_get();
        //         // print_r($timezone);
        //         $data = array(
        //             'ID'           => $apporderid,
        //             'CREATED_AT'   => date('Y-m-d H:i:s', time()),
        //             'WAITERID'     => $jsonOrder->waiter_id,
        //             'TABLEID'      => $jsonOrder->table_id,
        //             'AMOUNT'       => $jsonOrder->total,
        //             'ORDERCONTENT' => $jsonOrder->items,
        //         );
        
        //         $this->db->insert('APPORDERS', $data);
        
        //         $sql = "SELECT T.TICKETID, AO.* FROM APPORDERS AO LEFT JOIN TICKETS T ON AO.RECEIPT = T.ID  WHERE  AO.ID='" . $apporderid . "' LIMIT 1;";
        //         $arr = $this->db->query($sql)->result();
        
        //         $dataorder = array();
        //         if ($arr) {
        //             array_push($dataorder, array(
        //                 'id'         => $arr[0]->ID,
        //                 'order_id'   => $arr[0]->TICKETID,
        //                 'total'      => $this->formatslist->formatCurrencywithHash($arr[0]->AMOUNT),
        //                 'date'       => $arr[0]->CREATED_AT,
        //                 'table_name' => $arr[0]->TABLEID,
        //                 'order'      => $arr[0]->ORDERCONTENT,
        //             ));
        //         }
        
        //         $data = array(
        //             'status'  => "1",
        //             'orderid' => $apporderid,
        //             'data'    => $dataorder,
        //             'message' => 'Your order completed successfully.',
        //         );
        
        //         header('Content-Type: application/json');
        //         echo json_encode(array("data" => $data));
        //         exit;
        //     } catch (Exception $e) {
        //         $data = array(
        //             'status'  => "0",
        //             'message' => $e->getMessage(),
        //         );
        
        //         header('Content-Type: application/json');
        //         echo json_encode(array("data" => $data));
        //         exit;
        //     }
        // }
        

       
        public function post() {
            
              
            try
            {

                $this->set_timezone();
    $jsonStr = file_get_contents('php://input');
    $jsonObj = json_decode($jsonStr);
    
    $jsonOrder = json_decode($jsonObj->order);
    $apporderid=uniqid();
    $data = array(
        
        'ID'=> $apporderid,
        'CREATED_AT'=>date('Y-m-d H:i:s', time()),
        'WAITERID'=>$jsonOrder->waiter_id,
        'TABLEID'=>$jsonOrder->table_id,
        'AMOUNT'=>$jsonOrder->total,
        'ORDERCONTENT'=>$jsonOrder->items,
    );

    $this->db->insert('APPORDERS',$data);
    
    
    $sql = "SELECT T.TICKETID, AO.* FROM APPORDERS AO LEFT JOIN TICKETS T ON AO.RECEIPT=T.ID  WHERE  AO.ID='". $apporderid ."' LIMIT 1;";
        $arr = $this->db->query($sql)->result();
    
    
        $dataorder = array();
    if ($arr) {
        array_push($dataorder,
                    array(
         'id'               => $arr[0]->ID,
            'order_id'         => $arr[0]->TICKETID,
            'total'            =>  $this->formatslist->formatCurrencywithHash($arr[0]->AMOUNT),
            'date'             => $arr[0]->CREATED_AT,
            'table_name'       => $arr[0]->TABLEID,
            'order'            => $arr[0]->ORDERCONTENT,
                    ));
    }
    
    $data= array(
        'status' => "1",
        'orderid' => $apporderid,
        'data' => $dataorder,
        'message' => 'You order completed successfully.'
                    );
    
     header('Content-Type: application/json');
    echo json_encode(array("data"=>$data));
    exit;
            }
            catch (Exception $e) {
        // this will not catch DB related errors. But it will include them, because this is more general. 
         $data= array(
        'status' => "0",
        'message' => $e->getMessage(),
                    );
    
     header('Content-Type: application/json');
    echo json_encode(array("data"=>$data));
                
        exit;
    }
            
        }
        
        public function makebill() {
            
              
            try
            {
        $this->set_timezone();
    $jsonStr = file_get_contents('php://input');
    
    $jsonObj = json_decode($jsonStr);
    
    $jsonOrder = json_decode($jsonObj->order);
    
    $sqlmoney = "SELECT MONEY FROM CLOSEDCASH WHERE DATEEND IS NULL AND HOST LIKE '". $jsonOrder->cash_closing_host ."' LIMIT 1;";
        $arrmoney = $this->db->query($sqlmoney)->result();
        $money="";
        if($arrmoney)
        {
            $money=$arrmoney[0]->MONEY;
        }
        
        $sqlticketid = "SELECT ID+1 AS TICKETID FROM TICKETSNUM LIMIT 1;";
        $arrticketid = $this->db->query($sqlticketid)->result();
        $ticketid= "0";
        if($arrticketid){
            $ticketid=$arrticketid[0]->TICKETID;

            $this->db->query("UPDATE TICKETSNUM SET ID = ID + 1;");
        } else {
        // Handle the case where no result is obtained
         throw new Exception("No result found for the next ticket ID.");
}           
    
    
    $apporderid=uniqid();
    $data = array(
        
        'ID'=> $apporderid,
        'CREATED_AT'=>date('Y-m-d H:i:s', time()),
        'WAITERID'=>$jsonOrder->waiter_id,
        'DEVICEID'=>$jsonOrder->device_name,
        'TABLEID'=>$jsonOrder->table,
        'AMOUNT'=>$jsonOrder->total,
        'MONEY'=>$money,
        'TICKETID'=>$ticketid,
        
        'ORDERCONTENT'=>$jsonOrder->items,
    );

    $this->db->insert('APPORDERS',$data);
    
    
    $sql = "SELECT T.TICKETID, AO.* FROM APPORDERS AO LEFT JOIN TICKETS T ON AO.RECEIPT=T.ID  WHERE  AO.ID='". $apporderid ."' LIMIT 1;";
        $arr = $this->db->query($sql)->result();
    
    
        $dataorder = array();
    if ($arr) {
        array_push($dataorder,
                    array(
         'id'               => $arr[0]->ID,
            'order_id'         => $arr[0]->TICKETID,
            'total'            =>  $this->formatslist->formatCurrencywithHash($arr[0]->AMOUNT),
            'date'             => $arr[0]->CREATED_AT,
            'table_name'       => $arr[0]->TABLEID,
            'order'            => $arr[0]->ORDERCONTENT,
                    ));
    }
    
    $data= array(
        'status' => "1",
        'header' => "XYZ Company\nAddress\nPhone",
        'footer' => "Thank you for visiting.",
        'orderid' => $apporderid,
        'ticketid' => $ticketid,
        'data' => $dataorder,
        'message' => 'You order completed successfully.'
                    );
    
     header('Content-Type: application/json');
    echo json_encode(array("data"=>$data));
    exit;
            }
            catch (Exception $e) {
        // this will not catch DB related errors. But it will include them, because this is more general. 
         $data= array(
        'status' => "0",
        'message' => $e->getMessage(),
                    );
    
     header('Content-Type: application/json');
    echo json_encode(array("data"=>$data));
                
        exit;
    }
            
        }
        
         public function list() {
             
             
              $jsonStr = file_get_contents('php://input');
    $jsonObj = json_decode($jsonStr);
    $data=array();
    if(isset($jsonObj->waiter))
    {
        
        $sql = "SELECT  APPORDERS.* ,PLACES.NAME AS TABLENAME FROM APPORDERS LEFT JOIN PLACES ON APPORDERS.TABLEID = PLACES.ID
        WHERE APPORDERS.WAITERID = '" . $jsonObj->waiter . "'
        ORDER BY APPORDERS.CREATED_AT DESC
        LIMIT 50;";	   
        $arr = $this->db->query($sql)->result();
    
    
    if ($arr != '') {
        foreach ($arr as $key => $aRow) {
            
             array_push($data,
                    array(
        'id' => $aRow->ID,
                    'order_id'    => $aRow->TICKETID,
        'total'    => $this->formatslist->formatCurrencywithHash($aRow->AMOUNT),
        'date'    => $aRow->CREATED_AT,
        'table_name'    => $aRow->TABLENAME
                    ));
        }
       
        
    }
    }

            
     header('Content-Type: application/json');
    echo json_encode(array('status' => 200,'data'=>$data));

    
    }
    
    public function view() {
        
         $jsonStr = file_get_contents('php://input');
    $jsonObj = json_decode($jsonStr);
    $data=array();
    if(isset($jsonObj->orderid))
    {
        $sql = "SELECT T.TICKETID, AO.*, PLACES.NAME AS TABLENAME
        FROM APPORDERS AO
        LEFT JOIN TICKETS T ON AO.RECEIPT = T.ID
        LEFT JOIN PLACES ON AO.TABLEID = PLACES.ID
        WHERE AO.ID = '" . $jsonObj->orderid . "'
        LIMIT 1;";
        $arr = $this->db->query($sql)->result();
    
    
    if ($arr) {
        
        header('Content-Type: application/json');
    echo json_encode(array(
         'id'               => $arr[0]->ID,
            'order_id'         => $arr[0]->TICKETID,
            'total'            =>  $this->formatslist->formatCurrencywithHash($arr[0]->AMOUNT),
            'date'             => $arr[0]->CREATED_AT,
            'table_name'       => $arr[0]->TABLENAME,
            'order'            => json_decode($arr[0]->ORDERCONTENT),
                    ));
        
    }
    else
    {
        
    }
        
    }
         
     
        
    }
    
    }
