<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
App::uses('UtilityController', 'Controller');
App::uses('AppController', 'Controller');
App::uses('CakeTime', 'Utility');
/**
 * CakePHP ApisController
 * @author aetherss
 */
class ApisController extends AppController {
    public function beforeFilter() {
            parent::beforeFilter();
            // Allow users to register and logout.
            $this->Auth->allow();
            $this->layout = false;
            $this->autoRender = false;
            error_reporting(0);
        }
        
        public function index()
        {
            echo "Welcome to PhyloPos";
        }
        // Global Use Private Functions 
     
     /************************* MOBILE APP APIS ******************************/
     
     
    public function login()
    {
        $username = $_REQUEST['username'];
        $password = $_REQUEST['password'];
        $device_id = $_REQUEST['device_id'];
        
        if(!isset($username)){
            $response['status']= false;
            $response['message']= "username missing..!";
            return json_encode($response);
        }
        if($password==''){
            $response['status']= false;
            $response['message']= "Password missing..!";
            return json_encode($response);
        }
        $password = AuthComponent::password($password);
        $response = array();
        
        $users = $this->User->find('first', array('conditions'=>array('User.username'=>$username,'User.password'=>$password,'User.role'=>'cashier')));
        if(!empty($users))
        {
            if(isset($device_id)){
                $id=$users['User']['id'];
                $this->User->query("UPDATE users SET device_id = '$device_id' WHERE id = $id");
            }
            
            if(isset($users['User']['username'])){
                $username=$users['User']['username'];
            }else{
                $username='';
            }
            if(isset($users['User']['name'])){
                $name=$users['User']['name'];
            }else{
                $name='';
            }
            if(isset($users['User']['mobile'])){
                $mobile=$users['User']['mobile'];
            }else{
                $mobile='';
            }
            $modules=modules;
            
            $flags = [];
            foreach ($modules as $module) {
                $flags[$module] = false;
            }
            
            $usermodules = $this->User_module->find('all', array('conditions'=>array('User_module.user_id'=>$users['User']['id'])));
            if($usermodules){
                foreach($usermodules as $usermodule){
                    $moduleName = $usermodule['User_module']['name'];
                    // print_r($moduleName);exit;
                    if (array_key_exists($moduleName, $flags)) {
                        $flags[$moduleName] = true;
                    }
                }
            }
            $loc_id=0;
            $userlocations = $this->User_location->find('first', array('conditions'=>array('user_id'=>$users['User']['id'],'status'=>1,'billing_location'=>1)));
            if($userlocations){
                $loc_id=$userlocations['User_location']['location_id'];
                $locations = $this->Location->find('first', array('conditions'=>array('Location.id'=>$loc_id,'Location.status'=>1)));
            
            }
            
            //print_r($locations['Location']['name']);exit;
            
            $response['status']= true;
            $response['message']= "Success..!";
            $response['id']= $users['User']['id'];
            $response['username']= $username;
            $response['name']= $name;
            $response['role']= $users['User']['role'];
            $response['can_settlement']= $users['User']['can_settlement'];
            $response['billprint_ip']= $users['User']['billprint_ip'];
            $response['mobile']= $mobile;
            $response['location_id']= $loc_id;
            $response['location_name']= $locations['Location']['name'] ?? '';
            $response['print_line1']= $locations['Location']['print_line1'] ?? '';
            $response['print_line2']= $locations['Location']['print_line2'] ?? '';
            $response['print_line3']= $locations['Location']['print_line3'] ?? '';
            $response['print_line4']= $locations['Location']['print_line4'] ?? '';
            $response['print_line5']= $locations['Location']['print_line5'] ?? '';
            $response['print_line6']= $locations['Location']['print_line6'] ?? '';
            $response['print_line7']= $locations['Location']['print_line7'] ?? '';
            $response['print_line8']= $locations['Location']['print_line8'] ?? '';
            $response['print_line9']= $locations['Location']['print_line9'] ?? '';
            $response['print_line10']= $locations['Location']['print_line10'] ?? '';
            $response['footer_msg']= $locations['Location']['footer_msg'] ?? '';
            $response['currency_symbol']= $locations['Location']['currency_symbol'] ?? '';
            $response['created']= $users['User']['created'];
            
            foreach ($modules as $module) {
                $response[$module] = $flags[$module];
            }
            
            
        }
        else
        {
            $response['status']= false;
            $response['message']= "Failed..!";
        }
        return json_encode($response);
    }
     
    public function cardstatuscheck()
    {
        //$sendmessage= new UtilityController;
        
        $cashierid = $_REQUEST['id'];
        $cardno=preg_replace('/\D/', '', $_REQUEST['cardno']);

        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id Missing",
            );
            return json_encode($response);
        }
        if($cardno==''){
            $response =array(
                'status'=> false,
                'message'=> "Card No Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found or User Deactivated",
            );
            return json_encode($response);
        }
        
        $card = $this->Card->find('first', array('conditions'=>array('Card.cardnumber'=>$cardno)));
        if(empty($card))
        {
            $response =array(
                'status'=> false,
                'message'=> "Card not found",
            );
            return json_encode($response);
        }else{
            if($card[Card]['name']){
                $name=$card['Card']['name'];
            }else{
                $name='';
            }
            $phone=$card['Card']['mobile'];
            $response['status']= true;
            $response['statusvalue']= $card[Card]['status'];
            $response['customername']= $name;
            $response['cardbalance']= $card[Card]['cardbalance'];
            $response['message']= "Card is diabled please contact to support.";
        }
        return json_encode($response);
    }
    
    public function generateotp()
    {
        $sendmessage= new UtilityController;
        
        $cashierid = $_REQUEST['id'];
        $cardno=preg_replace('/\D/', '', $_REQUEST['cardno']);

        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id Missing",
            );
            return json_encode($response);
        }
        if($cardno==''){
            $response =array(
                'status'=> false,
                'message'=> "Card No Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found or User Deactivated",
            );
            return json_encode($response);
        }
        
        $card = $this->Card->find('first', array('conditions'=>array('Card.cardnumber'=>$cardno)));
        if(empty($card))
        {
            $response =array(
                'status'=> false,
                'message'=> "Card not found",
            );
            return json_encode($response);
        }else{
            $name=$card['Card']['name'];
            $phone=$card['Card']['mobile'];
            // $otp = mt_rand(1000, 9999);
            // print_r($otpp);
            $otp=1111;
            $this->Card->query("UPDATE cards SET otp = '$otp' WHERE cardnumber = '$cardno'");
            $message = "Hi $name, please use $otp to login to PhyloPay.";
//          $sendmessage->message($message,$phone);
            
            $response['status']= true;
            $response['message']= "Success..!";
            $response['otp']= $otp;
        }
        return json_encode($response);
    }
    
    public function cardaddbalance()
    {
        $cashierid = $_REQUEST['id'];
        $cardno=preg_replace('/\D/', '', $_REQUEST['cardno']);
        $amount = $_REQUEST['amount'];
        // $otp = $_REQUEST['otp'];
        $mode = $_REQUEST['mode'];
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id Missing",
            );
            return json_encode($response);
        }
        if($cardno==''){
            $response =array(
                'status'=> false,
                'message'=> "Card no Missing",
            );
            return json_encode($response);
        }
        if($amount==''){
            $response =array(
                'status'=> false,
                'message'=> "Amount Missing",
            );
            return json_encode($response);
        }
        if($amount<1){
            $response =array(
                'status'=> false,
                'message'=> "Amount need to be greater than 0",
            );
            return json_encode($response);
        }
        // if($otp==''){
        //     $response =array(
        //         'status'=> false,
        //         'message'=> "Otp Missing",
        //     );
        //     return json_encode($response);
        // }
        if($mode==''){
            $response =array(
                'status'=> false,
                'message'=> "payment mode Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found or User Deactivated",
            );
            return json_encode($response);
        }else{
            $cashiername=$users['User']['name'];
        }
        
        $card = $this->Card->find('first', array('conditions'=>array('Card.cardnumber'=>$cardno,'Card.status'=>2)));
        if(empty($card))
        {
            $response =array(
                'status'=> false,
                'message'=> "Card not found or Card Deactivated",
            );
            return json_encode($response);
        }else{
            // $card = $this->Card->find('first', array('conditions'=>array('Card.cardnumber'=>$cardno,'Card.otp'=>$otp,'Card.status'=>2)));
            // if(empty($card))
            // {
            //     $response =array(
            //         'status'=> false,
            //         'message'=> "Wrong OTP ",
            //     );
            //     return json_encode($response);
            // }
            $name=$card['Card']['name'];
            $mobile=$card['Card']['mobile'];
            $oldbal=$card['Card']['cardbalance'];
            $newbal=$oldbal+$amount;
            
            do {
                $txnid = '';
                for ($i = 0; $i < 10; $i++) {
                    $txnid .= rand(0, 9);
                }
                $existingOTP = $this->Cardtracking->find('first', array(
                    'conditions' => array(
                        'txnid' => $txnid
                    )
                ));
            } while ($existingOTP); // Continue generating OTP until it doesn't exist
            
            $data['Cardtracking']=array(
                'cardnumber'=>$cardno,
                'cashierID'=>$cashierid,
                'txnid'=>$txnid,
                'cashierName'=>$cashiername,
                'customername'=>$name,
                'customerphone'=>$mobile,
                'purpose'=>'add',
                'oldbalance'=>$oldbal,
                'amount'=>$amount,
                'newbalance'=>$newbal,
                'type'=>1,
                'payment_mode'=>$mode
            );
          
            if($this->Cardtracking->saveAll($data['Cardtracking']))
            {
                $this->Card->query("UPDATE cards SET cardbalance = $newbal WHERE cardnumber = '$cardno'");
            
                $response= array('status'=> true,
                    'message'=> "Balance Added successfully",
                    'cardno'=>$cardno,
                    'balance'=>$newbal
                );
            }else{
                $response =array(
                    'status'=> false,
                    'message'=> "failed",
                );
            }
        }
        return json_encode($response);
    }
    
    public function cardwithdrawalbalance()
    {
        $cashierid = $_REQUEST['id'];
        $cardno=preg_replace('/\D/', '', $_REQUEST['cardno']);
        $amount = $_REQUEST['amount'];
        $otp = $_REQUEST['otp'];
        $mode = $_REQUEST['mode'];
        $reference_id = $_REQUEST['reference_id'];
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id Missing",
            );
            return json_encode($response);
        }
        if($cardno==''){
            $response =array(
                'status'=> false,
                'message'=> "Card no Missing",
            );
            return json_encode($response);
        }
        if($amount==''){
            $response =array(
                'status'=> false,
                'message'=> "Amount Missing",
            );
            return json_encode($response);
        }
        
        if($mode==''){
            $response =array(
                'status'=> false,
                'message'=> "payment mode Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found or User Deactivated",
            );
            return json_encode($response);
        }else{
            $cashiername=$users['User']['name'];
        }
        
        $card = $this->Card->find('first', array('conditions'=>array('Card.cardnumber'=>$cardno,'Card.status'=>2)));
        if(empty($card))
        {
            $response =array(
                'status'=> false,
                'message'=> "Card not found or Card Deactivated",
            );
            return json_encode($response);
        }else{
            $pinreq=$card['Card']['pin_required'];
            if($pinreq){
                if($otp==''){
                    $response =array(
                        'status'=> false,
                        'message'=> "PIN Missing",
                    );
                    return json_encode($response);
                }
                $card = $this->Card->find('first', array('conditions'=>array('Card.cardnumber'=>$cardno,'Card.pin'=>$otp,'Card.status'=>2)));
                if(empty($card))
                {
                    $response =array(
                        'status'=> false,
                        'message'=> "Wrong PIN ",
                    );
                    return json_encode($response);
                }
            }
            $card = $this->Card->find('first', array('conditions'=>array('Card.cardnumber'=>$cardno,'Card.cardbalance >= '=>$amount)));
            if(empty($card))
            {
                $response =array(
                    'status'=> false,
                    'message'=> "Withdrawal Amount not exist in card ",
                );
                return json_encode($response);
            }
            
            $today = date("Y-m-d H:i:s");
            $currentDate = new DateTime($today);
            $newdate = $currentDate->modify('-2 minute')->format('Y-m-d H:i:s');

            $cardtrackingchk = $this->Cardtracking->query("SELECT * FROM cardtracking where cardnumber='$cardno' and amount='$amount' and created between '$newdate' and '$today' and type=2");
            if(!empty($cardtrackingchk))
            {
                $response =array(
                    'status'=> false,
                    'message'=> "Withdraw blocked for 2 minutes",
                );
                return json_encode($response);
            }
            
            $name=$card['Card']['name'];
            $mobile=$card['Card']['mobile'];
            $oldbal=$card['Card']['cardbalance'];
            $newbal=$oldbal-$amount;
            
            do {
                $txnid = '';
                for ($i = 0; $i < 10; $i++) {
                    $txnid .= rand(0, 9);
                }
                $existingOTP = $this->Cardtracking->find('first', array(
                    'conditions' => array(
                        'txnid' => $txnid
                    )
                ));
            } while ($existingOTP); // Continue generating OTP until it doesn't exist
            
            $data['Cardtracking']=array(
                'cardnumber'=>$cardno,
                'cashierID'=>$cashierid,
                'txnid'=>$txnid,
                'reference_id'=>$reference_id,
                'cashierName'=>$cashiername,
                'customername'=>$name,
                'customerphone'=>$mobile,
                'purpose'=>'withdrawal',
                'oldbalance'=>$oldbal,
                'amount'=>$amount,
                'newbalance'=>$newbal,
                'type'=>2,
                'payment_mode'=>$mode
            );
          
            if($this->Cardtracking->saveAll($data['Cardtracking']))
            {
                $this->Card->query("UPDATE cards SET cardbalance = $newbal WHERE cardnumber = '$cardno'");
            
                $response= array('status'=> true,
                    'message'=> "money paid sucessfully",
                    'cardno'=>$cardno,
                    'balance'=>$newbal
                );
            }else{
                $response =array(
                    'status'=> false,
                    'message'=> "failed",
                );
            }
        }
        return json_encode($response);
    }
    
    public function carddeactivate()
    {
        $cashierid = $_REQUEST['id'];
        $cardno = $_REQUEST['cardno'];
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id Missing",
            );
            return json_encode($response);
        }
        if($cardno==''){
            $response =array(
                'status'=> false,
                'message'=> "Card no Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found or User Deactivated",
            );
            return json_encode($response);
        }
        $card = $this->Card->find('first', array('conditions'=>array('Card.cardnumber'=>$cardno,'Card.status'=>2)));
        if(empty($card))
        {
            $response =array(
                'status'=> false,
                'message'=> "Card not found or Card already Deactivated",
            );
            return json_encode($response);
        }else{
            $this->Card->query("UPDATE cards SET status = 0 WHERE cardnumber = '$cardno'");
        
            $response= array('status'=> true,
                'message'=> "Card Deactivated successfully",
            );
        
        }
        return json_encode($response);
    }
    
    public function cardtransfer()
    {
        $cashierid = $_REQUEST['id'];
        $cardno=preg_replace('/\D/', '', $_REQUEST['cardno']);
        // $otp = $_REQUEST['otp'];
        $newcardno = $_REQUEST['newcardno'];
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id Missing",
            );
            return json_encode($response);
        }
        if($cardno==''){
            $response =array(
                'status'=> false,
                'message'=> "Card no Missing",
            );
            return json_encode($response);
        }
        // if($otp==''){
        //     $response =array(
        //         'status'=> false,
        //         'message'=> "OTP Missing",
        //     );
        //     return json_encode($response);
        // }
        if($newcardno==''){
            $response =array(
                'status'=> false,
                'message'=> "New Card No Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found or User Deactivated",
            );
            return json_encode($response);
        }else{
            $cashiername=$users['User']['name'];
        }
        
        $card = $this->Card->find('first', array('conditions'=>array('Card.cardnumber'=>$cardno,'Card.status'=>2)));
        if(empty($card))
        {
            $response =array(
                'status'=> false,
                'message'=> "Card not found or Card Deactivated",
            );
            return json_encode($response);
        }else{
            // $card = $this->Card->find('first', array('conditions'=>array('Card.cardnumber'=>$cardno,'Card.status'=>2,'Card.otp'=>$otp)));
            // if(empty($card))
            // {
            //     $response =array(
            //         'status'=> false,
            //         'message'=> "Wrong OTP",
            //     );
            //     return json_encode($response);
            // }
            $newcard = $this->Card->find('first', array('conditions'=>array('Card.cardnumber'=>$newcardno)));
            if(!empty($newcard))
            {
                $status=$newcard['Card']['status'];
                if($status==1){
                    $response =array(
                        'status'=> false,
                        'message'=> "New Card No Already Exist",
                    );
                    return json_encode($response);
                }else{
                    $response= array('status'=> true,
                        'message'=> "New Card no Already Exist But Card Deactivated"
                    );
                    return json_encode($response);
                }
            }else{
            
                $name=$card['Card']['name'];
                $mobile=$card['Card']['mobile'];
                $oldbal=$card['Card']['cardbalance'];
                
                $data['Card']=array(
                    'cardnumber'=>$newcardno,
                    'cardbalance'=>$oldbal,
                    'name'=>$name,
                    'mobile'=>$mobile,
                    'status'=>2
                );
              
                if($this->Card->saveAll($data['Card']))
                {
                    $this->Card->query("UPDATE cards SET cardbalance = 0,status=0 WHERE cardnumber = '$cardno'");
                    
                    do {
                        $txnid = '';
                        for ($i = 0; $i < 10; $i++) {
                            $txnid .= rand(0, 9);
                        }
                        $existingOTP = $this->Cardtracking->find('first', array(
                            'conditions' => array(
                                'txnid' => $txnid
                            )
                        ));
                    } while ($existingOTP); // Continue generating OTP until it doesn't exist
                    
                    $data['Cardtracking']=array(
                        'cardnumber'=>$newcardno,
                        'cashierID'=>$cashierid,
                        'txnid'=>$txnid,
                        'cashierName'=>$cashiername,
                        'customername'=>$name,
                        'customerphone'=>$mobile,
                        'purpose'=>'transferto',
                        'oldbalance'=>0,
                        'amount'=>$oldbal,
                        'newbalance'=>$oldbal,
                        'type'=>1,
                        'payment_mode'=>'transfer'
                    );
                  
                    if($this->Cardtracking->saveAll($data['Cardtracking']))
                    {
                        do {
                            $txnid = '';
                            for ($i = 0; $i < 10; $i++) {
                                $txnid .= rand(0, 9);
                            }
                            $existingOTP = $this->Cardtracking->find('first', array(
                                'conditions' => array(
                                    'txnid' => $txnid
                                )
                            ));
                        } while ($existingOTP); // Continue generating OTP until it doesn't exist
                        
                        $data1['Cardtracking']=array(
                            'cardnumber'=>$cardno,
                            'cashierID'=>$cashierid,
                            'txnid'=>$txnid,
                            'cashierName'=>$cashiername,
                            'customername'=>$name,
                            'customerphone'=>$mobile,
                            'purpose'=>'transferfrom',
                            'oldbalance'=>$oldbal,
                            'amount'=>$oldbal,
                            'newbalance'=>0,
                            'type'=>2,
                            'payment_mode'=>'transfer'
                        );
                        if($this->Cardtracking->saveAll($data1['Cardtracking']))
                        {
                            $response= array('status'=> true,
                                'message'=> "Card Transfer successfully",
                                'cardno'=>$newcardno,
                                'balance'=>$oldbal
                            );
                        }else{
                            $response =array(
                                'status'=> false,
                                'message'=> "failed to save card tracking 101",
                            ); 
                        }
                    }else{
                        $response =array(
                            'status'=> false,
                            'message'=> "failed to save card tracking",
                        );
                    }
                    
                }else{
                    $response =array(
                        'status'=> false,
                        'message'=> "failed to save card",
                    );
                }
            }
        }
        return json_encode($response);
    }
    
    public function cardcreate()
    {
        $sendmessage= new UtilityController;
        
        $cashierid = $_REQUEST['id'];
        $cardno=preg_replace('/\D/', '', $_REQUEST['cardno']);
        $name = $_REQUEST['name'];
        $mobile = $_REQUEST['mobile'];
        $email = $_REQUEST['email'];
        $valid_to = $_REQUEST['validto'];
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id Missing",
            );
            return json_encode($response);
        }
        if($cardno==''){
            $response =array(
                'status'=> false,
                'message'=> "Card no Missing",
            );
            return json_encode($response);
        }
        if($name==''){
            $response =array(
                'status'=> false,
                'message'=> "Name Missing",
            );
            return json_encode($response);
        }
        if($mobile==''){
            $response =array(
                'status'=> false,
                'message'=> "Mobile no Missing",
            );
            // return json_encode($response);
        }
        
        if($email==''){
            $response =array(
                'status'=> false,
                'message'=> "Email Missing",
            );
            // return json_encode($response);
        }
        if (!preg_match('/^\d{10}$/', $mobile)) {
            $response =array(
                'status'=> false,
                'message'=> "Mobile no is not valid",
            );
            return json_encode($response);
        }
        // print_r();exit;
        if($valid_to==''){
            $response =array(
                'status'=> false,
                'message'=> "Validity Missing",
            );
            //return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found or User Deactivated",
            );
            return json_encode($response);
        }else{
            $cashiername=$users['User']['name'];
        }
        
        $card = $this->Card->find('first', array('conditions'=>array('Card.cardnumber'=>$cardno,'Card.status'=>2)));
        if(!empty($card))
        {
            $response =array(
                'status'=> false,
                'message'=> "Card Already Exist",
            );
            return json_encode($response);
        }else{
            $card = $this->Card->find('first', array('conditions'=>array('Card.cardnumber'=>$cardno,'Card.status'=>0)));
            if(!empty($card))
            {
                $response =array(
                    'status'=> false,
                    'message'=> "Card Already deactivated!! kindly contact to support!!!",
                );
                return json_encode($response);
            }
            $today = date("Y-m-d");
            $currentDate = new DateTime($today);
            $valid_to = $currentDate->modify('+1 day')->format('Y-m-d');

            $card = $this->Card->find('first', array('conditions'=>array('Card.cardnumber'=>$cardno,'Card.status'=>1)));
            if(!empty($card))
            {
                //$otp = mt_rand(1000, 9999);
                 $otp=1111;
                $cardCharge=0.0;
                $cardCharge=-card_charge;
                $query=$this->Card->query("UPDATE cards SET name = '$name',email = '$email',mobile = '$mobile',valid_to='$valid_to',otp='$otp',cardbalance=$cardCharge,status = '2' WHERE cardnumber = '$cardno'");
                
    //             $message = "Hi $name, please use $otp to login to PhyloPay.";
    //          $sendmessage->message($message,$mobile);
                
                do {
                    $txnid = '';
                    for ($i = 0; $i < 10; $i++) {
                        $txnid .= rand(0, 9);
                    }
                    $existingOTP = $this->Cardtracking->find('first', array(
                        'conditions' => array(
                            'txnid' => $txnid
                        )
                    ));
                } while ($existingOTP); // Continue generating OTP until it doesn't exist
            
                $data1['Cardtracking']=array(
                    'cardnumber'=>$cardno,
                    'cashierID'=>$cashierid,
                    'txnid'=>$txnid,
                    'cashierName'=>$cashiername,
                    'customername'=>$name,
                    'customerphone'=>$mobile,
                    'purpose'=>'create',
                    'oldbalance'=>0,
                    'amount'=>security,
                    'newbalance'=>security,
                    'type'=>3,
                    'payment_mode'=>'security'
                );
            
                if($this->Cardtracking->saveAll($data1['Cardtracking']))
                {
                    do {
                        $txnid = '';
                        for ($i = 0; $i < 10; $i++) {
                            $txnid .= rand(0, 9);
                        }
                        $existingOTP = $this->Cardtracking->find('first', array(
                            'conditions' => array(
                                'txnid' => $txnid
                            )
                        ));
                    } while ($existingOTP); // Continue generating OTP until it doesn't exist
                    
                    $data11['Cardtracking']=array(
                        'cardnumber'=>$cardno,
                        'cashierID'=>$cashierid,
                        'txnid'=>$txnid,
                        'cashierName'=>$cashiername,
                        'customername'=>$name,
                        'customerphone'=>$mobile,
                        'purpose'=>'card_charge',
                        'oldbalance'=>0,
                        'amount'=>-card_charge,
                        'newbalance'=>-card_charge,
                        'type'=>2,
                        'payment_mode'=>'card_charge'
                    );
                    if($this->Cardtracking->saveAll($data11['Cardtracking']))
                    {
                        $response= array('status'=> true,
                            'message'=> "Card Created successfully",
                            'cardno'=>$cardno,
                            'name'=>$name,
                            'email'=>$email,
                            'mobile'=>$mobile,
                            'valid_to'=>$valid_to,
                            'balance'=>-card_charge,
                        );
                    }
                }
            }else{
            
                // $otp = mt_rand(1000, 9999); 
                $otp=1111;
                $data['Card']=array(
                    'cardnumber'=>$cardno,
                    'cardbalance'=>-card_charge,
                    'name'=>$name,
                    'email'=>$email,
                    'mobile'=>$mobile,
                    'valid_to'=>$valid_to,
                    'status'=>2
                );
          
                if($this->Card->saveAll($data['Card']))
                {
        //          $message = "Hi $name, please use $otp to login to PhyloPay.";
        //          $sendmessage->message($message,$mobile);
                    
                    do {
                        $txnid = '';
                        for ($i = 0; $i < 10; $i++) {
                            $txnid .= rand(0, 9);
                        }
                        $existingOTP = $this->Cardtracking->find('first', array(
                            'conditions' => array(
                                'txnid' => $txnid
                            )
                        ));
                    } while ($existingOTP); // Continue generating OTP until it doesn't exist
                
                    $data1['Cardtracking']=array(
                        'cardnumber'=>$cardno,
                        'cashierID'=>$cashierid,
                        'txnid'=>$txnid,
                        'cashierName'=>$cashiername,
                        'customername'=>$name,
                        'customerphone'=>$mobile,
                        'purpose'=>'create',
                        'oldbalance'=>0,
                        'amount'=>security,
                        'newbalance'=>security,
                        'type'=>3,
                        'payment_mode'=>'security'
                    );
                
                    if($this->Cardtracking->saveAll($data1['Cardtracking']))
                    {
                        do {
                            $txnid = '';
                            for ($i = 0; $i < 10; $i++) {
                                $txnid .= rand(0, 9);
                            }
                            $existingOTP = $this->Cardtracking->find('first', array(
                                'conditions' => array(
                                    'txnid' => $txnid
                                )
                            ));
                        } while ($existingOTP); // Continue generating OTP until it doesn't exist
                        
                        $data11['Cardtracking']=array(
                            'cardnumber'=>$cardno,
                            'cashierID'=>$cashierid,
                            'txnid'=>$txnid,
                            'cashierName'=>$cashiername,
                            'customername'=>$name,
                            'customerphone'=>$mobile,
                            'purpose'=>'card_charge',
                            'oldbalance'=>0,
                            'amount'=>-card_charge,
                            'newbalance'=>-card_charge,
                            'type'=>2,
                            'payment_mode'=>'card_charge'
                        );
                        if($this->Cardtracking->saveAll($data11['Cardtracking']))
                        {
                            $response= array('status'=> true,
                                'message'=> "Card Created successfully",
                                'cardno'=>$cardno,
                                'name'=>$name,
                                'email'=>$email,
                                'mobile'=>$mobile,
                                'valid_to'=>$valid_to,
                                'balance'=>-card_charge,
                            );
                        }
                    }
                }else{
                    $response =array(
                        'status'=> false,
                        'message'=> "failed to save card",
                    ); 
                }
            }
        }
        return json_encode($response);
    }
    
    public function cardcreate_verify()
    {
        $sendlink= new UtilityController;
        
        $cashierid = $_REQUEST['id'];
        $cardno=preg_replace('/\D/', '', $_REQUEST['cardno']);
        $otp = $_REQUEST['otp'];
        $pinrequired = $_REQUEST['pinrequired'];
        if(!$pinrequired){
            $pinrequired=0;
        }
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id Missing",
            );
            return json_encode($response);
        }
        if($cardno==''){
            $response =array(
                'status'=> false,
                'message'=> "Card no Missing",
            );
            return json_encode($response);
        }
        if($otp==''){
            $response =array(
                'status'=> false,
                'message'=> "OTP Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found or User Deactivated",
            );
            return json_encode($response);
        }else{
            $cashiername=$users['User']['name'];
        }
        
        $card = $this->Card->find('first', array('conditions'=>array('Card.cardnumber'=>$cardno,'Card.otp'=>$otp)));
        if(empty($card))
        {
            $response =array(
                'status'=> false,
                'message'=> "Wrong OTP",
            );
            return json_encode($response);
        }else{
            $cardid=$card['Card']['id'];
            $name=$card['Card']['name'];
            $mobile=$card['Card']['mobile'];
            
            $this->Card->query("UPDATE cards SET status = '2',pin_required='$pinrequired' WHERE cardnumber = '$cardno'");
            
            do {
                $txnid = '';
                for ($i = 0; $i < 10; $i++) {
                    $txnid .= rand(0, 9);
                }
                $existingOTP = $this->Cardtracking->find('first', array(
                    'conditions' => array(
                        'txnid' => $txnid
                    )
                ));
            } while ($existingOTP); // Continue generating OTP until it doesn't exist
            
            $data1['Cardtracking']=array(
                'cardnumber'=>$cardno,
                'cashierID'=>$cashierid,
                'txnid'=>$txnid,
                'cashierName'=>$cashiername,
                'customername'=>$name,
                'customerphone'=>$mobile,
                'purpose'=>'create',
                'oldbalance'=>0,
                'amount'=>security,
                'newbalance'=>security,
                'type'=>3,
                'payment_mode'=>'security'
            );
                if($this->Cardtracking->saveAll($data1['Cardtracking']))
                {
                    do {
                        $txnid = '';
                        for ($i = 0; $i < 10; $i++) {
                            $txnid .= rand(0, 9);
                        }
                        $existingOTP = $this->Cardtracking->find('first', array(
                            'conditions' => array(
                                'txnid' => $txnid
                            )
                        ));
                    } while ($existingOTP); // Continue generating OTP until it doesn't exist
                    
                    $data11['Cardtracking']=array(
                        'cardnumber'=>$cardno,
                        'cashierID'=>$cashierid,
                        'txnid'=>$txnid,
                        'cashierName'=>$cashiername,
                        'customername'=>$name,
                        'customerphone'=>$mobile,
                        'purpose'=>'card_charge',
                        'oldbalance'=>0,
                        'amount'=>-card_charge,
                        'newbalance'=>-card_charge,
                        'type'=>2,
                        'payment_mode'=>'card_charge'
                    );
                    if($this->Cardtracking->saveAll($data11['Cardtracking']))
                    {
                        if($pinrequired){
                            $smslink=smslink;
                            $message = "Hi $name, please go to $smslink.$cardid to set your PIN for Gourmet Pay, powered by PhyloPay.";
                            $lin=$sendlink->createpinlinkmsg($message,$mobile);
                        }
                        $response= array('status'=> true,
                            'message'=> "Card Verified successfully",
                            'cardno'=>$cardno,
                            'name'=>$name,
                            'mobile'=>$mobile,
                            'balance'=>-card_charge,
                            'pinrequired'=>$pinrequired
                        );
                    }
                }
        }
        return json_encode($response);
    }
    
    public function dasboarddata()
    {
        $cashierid = $_REQUEST['id'];
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found or User Deactivated",
            );
            return json_encode($response);
        }
        
        $todayDate = date("Y-m-d");
        $card = $this->Cardtracking->query("SELECT SUM(IF(type=1,1,0))+SUM(IF(type=2,1,0)) AS total_txnid, SUM(IF(type=3,1,0)) AS cardissue, SUM(IF(type=1 and purpose='add',amount,0)) AS deposit, SUM(IF(type=2 and purpose='withdrawal',amount,0)) AS deduct FROM cardtracking WHERE cashierID=$cashierid and date(created)='$todayDate'");
        
        if(!empty($card))
        {
            if($card[0][0]['deposit']){
                $deposit=$card[0][0]['deposit'];
            }else{
                $deposit="0";
            }
            if($card[0][0]['deduct']){
                $deduct=$card[0][0]['deduct'];
            }else{
                $deduct="0";
            }
            if($card[0][0]['total_txnid']){
                $total_txnid=$card[0][0]['total_txnid'];
            }else{
                $total_txnid="0";
            }
            if($card[0][0]['cardissue']){
                $cardissue=$card[0][0]['cardissue'];
            }else{
                $cardissue="0";
            }
            
            $response= array('status'=> true,
                'message'=> "success",
                'total_txn' => $total_txnid,
                'card_issued' => $cardissue,   
                'amount_collected' => $deposit,   
                'amount_deducted' => $deduct
            );
        }else{
            $response =array(
                'status'=> false,
                'message'=> "No data found",
            );
        }
        return json_encode($response);
    }
    
    public function card_history()
    {
        $cashierid = $_REQUEST['id'];
        $cardno=preg_replace('/\D/', '', $_REQUEST['cardno']);
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id Missing",
            );
            return json_encode($response);
        }
        if($cardno==''){
            $response =array(
                'status'=> false,
                'message'=> "Card no Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found or User Deactivated",
            );
            return json_encode($response);
        }
        
        $card = $this->Card->find('first', array('conditions'=>array('Card.cardnumber'=>$cardno)));
        if(empty($card))
        {
            $response =array(
                'status'=> false,
                'message'=> "Card Not found ",
            );
            return json_encode($response);
        }else{
            $cardtracks = $this->Cardtracking->find('all', array('conditions'=>array('Cardtracking.cardnumber'=>$cardno),'order' => array('Cardtracking.id' => 'desc')));
            foreach($cardtracks as $cardtrack){
                if($cardtrack['Cardtracking']['type']==1){
                    $type_value='add';
                }elseif($cardtrack['Cardtracking']['type']==2){
                    $type_value='deduct';
                }elseif($cardtrack['Cardtracking']['type']==3){
                    $type_value='security';
                }else{
                    $type_value='refund';
                }
                if($cardtrack['Cardtracking']['cashierName']){
                    $cashierName=$cardtrack['Cardtracking']['cashierName'];
                }else{
                    $cashierName='';
                }
                if($cardtrack['Cardtracking']['customername']){
                    $customername=$cardtrack['Cardtracking']['customername'];
                }else{
                    $customername='';
                }
                if($cardtrack['Cardtracking']['customerphone']){
                    $customerphone=$cardtrack['Cardtracking']['customerphone'];
                }else{
                    $customerphone='';
                }
                if($cardtrack['Cardtracking']['payment_mode']){
                    $payment_mode=$cardtrack['Cardtracking']['payment_mode'];
                }else{
                    $payment_mode='';
                }
                $item[]=array(
                    'id' => $cardtrack['Cardtracking']['id'],
                    'cardnumber' =>  $cardtrack['Cardtracking']['cardnumber'],
                    'cashierID' =>  $cardtrack['Cardtracking']['cashierID'],
                    'txnid' =>  $cardtrack['Cardtracking']['txnid'],
                    'cashierName' =>  $cashierName,
                    'customername' =>  $customername,
                    'customerphone' =>  $customerphone,
                    'purpose' =>  $cardtrack['Cardtracking']['purpose'],
                    'oldbalance' =>  $cardtrack['Cardtracking']['oldbalance'], 
                    'amount' =>  $cardtrack['Cardtracking']['amount'], 
                    'newbalance' =>  $cardtrack['Cardtracking']['newbalance'], 
                    'type' =>  $cardtrack['Cardtracking']['type'], 
                    'type_value' =>  $type_value, 
                    'payment_mode' =>  $payment_mode,  
                    'created' =>  $cardtrack['Cardtracking']['created']
                );
            }
            $response= array('status'=> true,
                'message'=> "success",
                'users'=>$item
            );
        }
        return json_encode($response);
    }
    
    public function user_modules()
    {
        $id = $_REQUEST['id'];
        
        if(!isset($id)){
            $response['status']= false;
            $response['message']= "user id missing..!";
            return json_encode($response);
        }
        $response = array();
        
        $users = $this->User_module->find('all', array('conditions'=>array('user_id'=>$id)));
        if(!empty($users))
        {
            $card=false;
            $catalogue=false;
            $reporting=false;
            $ordering=false;
            foreach($users as $user){
                $name=$user['User_module']['name'];
                if($name=='card'){
                    $card=true;
                }
                if($name=='catalogue'){
                    $catalogue=true;
                }
                if($name=='reporting'){
                    $reporting=true;
                }
                if($name=='ordering'){
                    $ordering=true;
                }
            }
            
            $response['status']= true;
            $response['message']= "Success..!";
            $response['id']= $id;
            $response['card']= $card;
            $response['catalogue']= $catalogue;
            $response['reporting']= $reporting;
            $response['ordering']= $ordering;
        }
        else
        {
            $response['status']= false;
            $response['message']= "Failed..!";
        }
        return json_encode($response);
    }
    
    //Ordering API's
    
    public function category_list()
    {
        $cashierid = $_REQUEST['id'];
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $categoreis = $this->Catalog_category->find('all', array('conditions'=>array('Catalog_category.status'=>1)));
        if(empty($categoreis))
        {
            $response =array(
                'status'=> false,
                'message'=> "Category Not found ",
            );
            return json_encode($response);
        }else{
            foreach($categoreis as $categorei){
                $image='';
                $cat_id=$categorei['Catalog_category']['id'];
                $subitem=[];
                if($categorei['Catalog_category']['is_subcategory']){
                    $subcats = $this->Catalog_subcategory->find('all', array('conditions'=>array('Catalog_subcategory.cat_id'=>$cat_id,'status'=>1)));
                    foreach($subcats as $subcat){
                        $subitem[]=array(
                            'id' => $subcat['Catalog_subcategory']['id'],
                            'name' =>  $subcat['Catalog_subcategory']['name'],
                            'image'=>$image,
                            'created' =>  $subcat['Catalog_subcategory']['created']
                        );
                    }
                }
                $item[]=array(
                    'id' => $categorei['Catalog_category']['id'],
                    'name' =>  $categorei['Catalog_category']['name'],
                    'is_subcategory' =>  $categorei['Catalog_category']['is_subcategory'],
                    'subcategory'=>$subitem,
                    'image'=>$image,
                    'created' =>  $categorei['Catalog_category']['created']
                );
            }
            $response= array('status'=> true,
                'message'=> "success",
                'category'=>$item
            );
        }
        return json_encode($response);
    }
    
    public function product_list()
    {
        $cashierid = $_REQUEST['id'];
        $catid = $_REQUEST['catid'];
        $subcatid = $_REQUEST['subcatid'];
        if(isset($subcatid)){
            $catid=$subcatid;
        }
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id Missing",
            );
            return json_encode($response);
        }
        if($catid==''){
            $response =array(
                'status'=> false,
                'message'=> "Category Id Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        if($catid==0){
            $products = $this->Catalog_product->find('all', array('conditions'=>array('Catalog_product.status'=>1)));
        }else{
            $products = $this->Catalog_product->find('all', array(
                'conditions' => array(
                    'Catalog_product.status' => 1,
                    'OR' => array(
                        'Catalog_product.cat_id' => $catid,
                        'Catalog_product.subcat_id' => $catid
                    )
                )
            ));
        }
        
        if(empty($products))
        {
            $response =array(
                'status'=> false,
                'message'=> "Products Not found ",
            );
            return json_encode($response);
        }else{
            foreach($products as $product){
                
                $taxesitems=[];
                $taxess = $this->Catalog_product_tax->find('all', array('conditions'=>array('Catalog_product_tax.product_id'=>$product['Catalog_product']['id'])));
                foreach($taxess as $tax){
                    $taxesitems[]=array(
                        'tax_id' => $tax['Catalog_product_tax']['tax_id'],
                        'tax_name' =>  $tax['Catalog_product_tax']['tax_name'],
                        'tax_percentage' =>  $tax['Catalog_product_tax']['tax_percentage']
                    );
                }
            
            
                $addonitems=[];
                if($product['Catalog_product']['addon']){
                    $addons = $this->Catalog_product_addon->find('all', array('conditions'=>array('Catalog_product_addon.product_id'=>$product['Catalog_product']['id'])));
                    foreach($addons as $addon){
                        $addonitems[]=array(
                            'id' => $addon['Catalog_product_addon']['id'],
                            'name' =>  $addon['Catalog_product_addon']['name'],
                            'created' =>  $addon['Catalog_product_addon']['created']
                        );
                    }
                }
                
                if(!$product['Catalog_product']['image']){
                    $product['Catalog_product']['image']='';
                }
                
                if($product['Catalog_product']['image']){
                    $imgpth=Router::url('/', true) . DS . 'uploads' . DS . 'product_images' . DS . $product['Catalog_product']['image'];
                }else{
                    $imgpth=''; 
                }        
                $item[]=array(
                    'id' => $product['Catalog_product']['id'],
                    'name' =>  $product['Catalog_product']['name'],
                    'cat_id' =>  $product['Catalog_product']['cat_id'],
                    'cat_name' =>  $product['Catalog_product']['cat_name'],
                    'description' => $product['Catalog_product']['description'],
                    'food_type' =>  $product['Catalog_product']['food_type'],
                    'sort_order' =>  $product['Catalog_product']['sort_order'],
                    'recommended' =>  $product['Catalog_product']['recommended'],
                    'variation' =>  $product['Catalog_product']['variation'],
                    'price' => $product['Catalog_product']['price'],
                    'kds' => $product['Catalog_product']['kds'],
                    'markup_price' =>  $product['Catalog_product']['markup_price'],
                    'allergy_tags' =>  $product['Catalog_product']['allergy_tags'],
                    'weight' =>  $product['Catalog_product']['weight'],
                    'serves_people' =>  $product['Catalog_product']['serves_people'],
                    'image' => $imgpth,
                    'taxes'=>$taxesitems,
                    'addons'=>$addonitems,
                    'status' =>  $product['Catalog_product']['status'],
                    'created' =>  $product['Catalog_product']['created']
                );
            }
            $response= array('status'=> true,
                'message'=> "success",
                'products'=>$item
            );
        }
        return json_encode($response);
    }
    
    public function allproduct_list()
    {
        $cashierid = $_REQUEST['id'];
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $categoreis = $this->Catalog_category->find('all', array('conditions'=>array('Catalog_category.status'=>1)));
        if(!empty($categoreis)){
            foreach($categoreis as $categorei){
                $image='';
                $cat_id=$categorei['Catalog_category']['id'];
                
                if($categorei['Catalog_category']['is_subcategory']){
                    $subcats = $this->Catalog_subcategory->find('all', array('conditions'=>array('Catalog_subcategory.cat_id'=>$cat_id,'status'=>1)));
                    foreach($subcats as $subcat){
                        $products = $this->Catalog_product->find('all', array('conditions'=>array('Catalog_product.status'=>1,'Catalog_product.cat_id'=>$subcat['Catalog_subcategory']['id'])));
                        
                        if(!empty($products))
                        {
                            foreach($products as $product){
                                $taxesitems=[];
                                $taxess = $this->Catalog_product_tax->find('all', array('conditions'=>array('Catalog_product_tax.product_id'=>$product['Catalog_product']['id'])));
                                foreach($taxess as $tax){
                                    $taxesitems[]=array(
                                        'tax_id' => $tax['Catalog_product_tax']['tax_id'],
                                        'tax_name' =>  $tax['Catalog_product_tax']['tax_name'],
                                        'tax_percentage' =>  $tax['Catalog_product_tax']['tax_percentage']
                                    );
                                }
                            
                            
                                $addonitems=[];
                                if($product['Catalog_product']['addon']){
                                    $addons = $this->Catalog_product_addon->find('all', array('conditions'=>array('Catalog_product_addon.product_id'=>$product['Catalog_product']['id'])));
                                    foreach($addons as $addon){
                                        $addonitems[]=array(
                                            'id' => $addon['Catalog_product_addon']['id'],
                                            'name' =>  $addon['Catalog_product_addon']['name'],
                                            'created' =>  $addon['Catalog_product_addon']['created']
                                        );
                                    }
                                }
                                
                                if($product['Catalog_product']['image']){
                                    $imgpth=Router::url('/', true) . DS . 'uploads' . DS . 'product_images' . DS . $product['Catalog_product']['image'];
                                }else{
                                    $imgpth=''; 
                                }        
                                // print_r($imgpth);exit;
                                
                                $item[]=array(
                                    'id' => $product['Catalog_product']['id'],
                                    'name' =>  $product['Catalog_product']['name'],
                                    'cat_id' =>  $product['Catalog_product']['cat_id'],
                                    'cat_name' =>  $product['Catalog_product']['cat_name'],
                                    'description' => $product['Catalog_product']['description'],
                                    'food_type' =>  $product['Catalog_product']['food_type'],
                                    'sort_order' =>  $product['Catalog_product']['sort_order'],
                                    'recommended' =>  $product['Catalog_product']['recommended'],
                                    'variation' =>  $product['Catalog_product']['variation'],
                                    'price' => $product['Catalog_product']['price'],
                                    'kds' => $product['Catalog_product']['kds'],
                                    'markup_price' =>  $product['Catalog_product']['markup_price'],
                                    'allergy_tags' =>  $product['Catalog_product']['allergy_tags'],
                                    'weight' =>  $product['Catalog_product']['weight'],
                                    'serves_people' =>  $product['Catalog_product']['serves_people'],
                                    'image' => $imgpth,
                                    'taxes'=>$taxesitems,
                                    'addons'=>$addonitems,
                                    'status' =>  $product['Catalog_product']['status'],
                                    'created' =>  $product['Catalog_product']['created']
                                );
                            }
                        }
                    }
                }else{
                    $products = $this->Catalog_product->find('all', array('conditions'=>array('Catalog_product.status'=>1,'Catalog_product.cat_id'=>$cat_id)));
                        
                    if(!empty($products))
                    {
                        foreach($products as $product){
                            $taxesitems=[];
                            $taxess = $this->Catalog_product_tax->find('all', array('conditions'=>array('Catalog_product_tax.product_id'=>$product['Catalog_product']['id'])));
                            foreach($taxess as $tax){
                                $taxesitems[]=array(
                                    'tax_id' => $tax['Catalog_product_tax']['tax_id'],
                                    'tax_name' =>  $tax['Catalog_product_tax']['tax_name'],
                                    'tax_percentage' =>  $tax['Catalog_product_tax']['tax_percentage']
                                );
                            }
                        
                        
                            $addonitems=[];
                            if($product['Catalog_product']['addon']){
                                $addons = $this->Catalog_product_addon->find('all', array('conditions'=>array('Catalog_product_addon.product_id'=>$product['Catalog_product']['id'])));
                                foreach($addons as $addon){
                                    $addonitems[]=array(
                                        'id' => $addon['Catalog_product_addon']['id'],
                                        'name' =>  $addon['Catalog_product_addon']['name'],
                                        'created' =>  $addon['Catalog_product_addon']['created']
                                    );
                                }
                            }
                            
                            if($product['Catalog_product']['image']){
                                $imgpth=Router::url('/', true) . DS . 'uploads' . DS . 'product_images' . DS . $product['Catalog_product']['image'];
                            }else{
                                $imgpth=''; 
                            } 
                            
                            $item[]=array(
                                'id' => $product['Catalog_product']['id'],
                                'name' =>  $product['Catalog_product']['name'],
                                'cat_id' =>  $product['Catalog_product']['cat_id'],
                                'cat_name' =>  $product['Catalog_product']['cat_name'],
                                'description' => $product['Catalog_product']['description'],
                                'food_type' =>  $product['Catalog_product']['food_type'],
                                'sort_order' =>  $product['Catalog_product']['sort_order'],
                                'recommended' =>  $product['Catalog_product']['recommended'],
                                'variation' =>  $product['Catalog_product']['variation'],
                                'price' => $product['Catalog_product']['price'],
                                'kds' => $product['Catalog_product']['kds'],
                                'markup_price' =>  $product['Catalog_product']['markup_price'],
                                'allergy_tags' =>  $product['Catalog_product']['allergy_tags'],
                                'weight' =>  $product['Catalog_product']['weight'],
                                'serves_people' =>  $product['Catalog_product']['serves_people'],
                                'image' => $imgpth,
                                'taxes'=>$taxesitems,
                                'addons'=>$addonitems,
                                'status' =>  $product['Catalog_product']['status'],
                                'created' =>  $product['Catalog_product']['created']
                            );
                        }
                    }
                }
            }
        }
        $response= array('status'=> true,
            'message'=> "success",
            'products'=>$item
        );
        return json_encode($response);
    }
    
    public function table_list()
    {
        $cashierid = $_REQUEST['id'];
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        if(isset($_REQUEST['status'])){
            $tbles = $this->Order_table->find('all', array('conditions'=>array('status'=>$_REQUEST['status'],'is_takeaway'=>0)));
        }else{
            $tbles = $this->Order_table->find('all', array('conditions'=>array('status !='=>0,'is_takeaway'=>0)));
        }
        if(empty($tbles))
        {
            $response =array(
                'status'=> false,
                'message'=> "Tables Not found ",
            );
            return json_encode($response);
        }else{
            foreach($tbles as $tble){
                $sc=0;
                $disc=0;
                $tablereference_id=$tble['Order_table']['reference_id'];
                $orderdata=$this->ordercomputewithdiscount($tablereference_id,$cashierid,$sc,$disc);
                $amount=$orderdata['totalprice'];
                
                $item[]=array(
                    'id' => $tble['Order_table']['number'],
                    'number' =>  $tble['Order_table']['number'],
                    'reference_id' =>  $tble['Order_table']['reference_id'],
                    'amount' =>  isset($amount) ? (string)$amount : "0",
                    'is_alert' =>  $tble['Order_table']['is_alert'],
                    'is_waiter_required' =>  $tble['Order_table']['is_waiter_required'],
                    'is_customer_detail_required' =>  $tble['Order_table']['is_customer_detail_required']?$tble['Order_table']['is_customer_detail_required']:"0",
                    'status' =>  $tble['Order_table']['status'],
                    'is_takeaway' =>  $tble['Order_table']['is_takeaway']
                );
            }
            $response= array('status'=> true,
                'message'=> "success",
                'tables'=>$item
            );
        }
        return json_encode($response);
    }
    
    public function orderhistorysave_table()
    {
        $response['status']= false;
        $response['message']= "fail";
        
        $cashierid = $_REQUEST['id'];
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id is Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }else{
            if (isset($_REQUEST['data'])) {
                $data = $_REQUEST['data'];
            } else {
                $response =array(
                    'status'=> false,
                    'message'=> "data not found",
                );
                return json_encode($response);
            }
            
            $data = json_decode($data, true);
            // print_r($data);exit;
            if(isset($data['table_number'])){
                $tableno=$data['table_number'];
            }else{
                $response =array(
                    'status'=> false,
                    'message'=> "Table Number missing",
                );
                return json_encode($response);
            }
            
            if(isset($data['tablereference_id'])){
                $tablereference_id=$data['tablereference_id'];
            }else{
                $response =array(
                    'status'=> false,
                    'message'=> "Table Refrence Id missing",
                );
                return json_encode($response);
            }
            
            $device_id=$data['device_id'];
            
            $tables = $this->Order_table->find('first', array(
                'conditions' => array(
                    'Order_table.number' => $tableno,
                    'Order_table.reference_id' => $tablereference_id,
                    'Order_table.status IN' => array(1, 2),
                    'Order_table.status !=' => 4
                )
            ));
            if(!empty($tables))
            {
                
                $groupid .= rand(0, 9).$cashierid.time();
                
                $prepTimes = [];
            
                foreach ($data['orderhistory'] as $orderhistory) {
                    $packagechck = $this->Catalog_product->find('first', [
                        'conditions' => [
                            'Catalog_product.id' => $orderhistory['product_id'],
                            'Catalog_product.status' => 1,
                        ],
                        'fields' => ['Catalog_product.id','Catalog_product.preparation_time'],
                        'recursive' => -1
                    ]);
                
                    $prep = !empty($packagechck) ? intval($packagechck['Catalog_product']['preparation_time']) : 0;
                    $prepTimes[] = $prep;
                }
                
                $maxPrep = !empty($prepTimes) ? max($prepTimes) : 0;
                
                foreach($data['orderhistory'] as $orderhistory){
                    $cat_id=$orderhistory['cat_id'];
                    $cat_name=$orderhistory['cat_name'];
                    
                    if(isset($orderhistory['kds'])){
                        $kds=$orderhistory['kds'];
                    }else{
                        $kds=1;
                    }
                    
                    $packagechck = $this->Catalog_product->find('first', [
                        'conditions' => [
                            'Catalog_product.id' => $orderhistory['product_id'],
                            'Catalog_product.status' => 1,
                        ],
                        'fields' => ['Catalog_product.id','Catalog_product.preparation_time'],
                        'recursive' => -1
                    ]);
                    
                    $prep = !empty($packagechck) ? intval($packagechck['Catalog_product']['preparation_time']) : 0;
                
                    if ($maxPrep == 0) {
                        $delaySeconds = 10; // default
                    } elseif ($prep == $maxPrep) {
                        $delaySeconds = 10; // longest prep fires immediately (+ buffer)
                    } else {
                        $diff = max(0, $maxPrep - $prep);
                        $delaySeconds = $diff * 60; // convert minutes → seconds
                    }
                
                    $fireTime = time() + $delaySeconds;
        
                    $datas['Order_orderhistory']=array(
                        'reference_id'=>$tablereference_id,
                        'group_id'=>$groupid,
                        'store_id'=>$orderhistory['store_id'],
                        'cashier_id'=>$cashierid,
                        'category'=>$orderhistory['cat_id'],
                        'category_name'=>$orderhistory['cat_name'],
                        'product_id'=>$orderhistory['product_id'],
                        'product_name'=>$orderhistory['product_name'],
                        'quantity'=>$orderhistory['quantity'],
                        'price'=>$orderhistory['price'],
                        'kds'=>$kds,
                        'total_tax'=>$orderhistory['total_tax'],
                        'total_tax_percentage'=>$orderhistory['total_tax_percentage'],
                        'total_price'=>$orderhistory['total_price'],
                        'discount'=>$orderhistory['discount'],
                        'table_number'=>$tableno,
                        'remarks'=>$orderhistory['remarks'],
                        'device_id'=>$device_id,
                        'prep_time'=>$prep,
                        'fire_at' => date('Y-m-d H:i:s', $fireTime) // human readable timestamp
                    );
                    if($this->Order_orderhistory->saveAll($datas['Order_orderhistory']))
                    {
                        $lastorder_id = $this->Order_orderhistory->id;
                        
                        foreach($orderhistory['order_tax'] as $tax){
                            $datas['Order_tax']=array(
                                'orderhistory_id'=>$lastorder_id,
                                'product_id'=>$orderhistory['product_id'],
                                'product_name'=>$orderhistory['product_name'],
                                'kds'=>$kds,
                                'price'=>$orderhistory['price'],
                                'taxable_price'=>round($orderhistory['price']*$orderhistory['quantity'],2),
                                'cat_id'=>$cat_id,
                                'cat_name'=>$cat_name,
                                'quantity'=>$orderhistory['quantity'],
                                'tax_id'=>$tax['id'],
                                'tax_name'=>$tax['tax_name'],
                                'tax_percentage'=>$tax['tax_percentage'],
                                'tax_value'=>$tax['tax_value'],
                                'reference_id'=>$tablereference_id
                            );
                            if($this->Order_tax->saveAll($datas['Order_tax']))
                            {
                                // $lastorder_taxid = $this->Order_tax->id;
                            }else{
                                $response['status']= false;
                                $response['message']= "Tax not saved Error:102";
                            }
                        }
                        
                        foreach($orderhistory['selected_modifiers'] as $group_modifier){
                            $modifier_group_id=$group_modifier['modifier_group_id'];
                            $modifier_group_name=$group_modifier['modifier_group_name'];
                            $modifier_group_type=$group_modifier['group_type'];
                            
                            foreach($group_modifier['modifiers'] as $modifier){
                                
                                $modifier_id=$modifier['id'];
                                $modifier_name=$modifier['name'];
                                $modifier_price=$modifier['price'];
                                
                                $datas['Order_modifier']=array(
                                    'orderhistory_id'=>$lastorder_id,
                                    'product_id'=>$orderhistory['product_id'],
                                    'product_name'=>$orderhistory['product_name'],
                                    'modifier_group_id'=>$modifier_group_id,
                                    'modifier_group_name'=>$modifier_group_name,
                                    'modifier_group_type'=>$modifier_group_type,
                                    'modifier_id'=>$modifier_id,
                                    'modifier_name'=>$modifier_name,
                                    'modifier_price'=>$modifier_price,
                                    'quantity'=>$orderhistory['quantity'],
                                    'reference_id'=>$tablereference_id
                                );
                                if($this->Order_modifier->saveAll($datas['Order_modifier']))
                                {
                                    // $lastorder_taxid = $this->Order_tax->id;
                                }else{
                                    $response['status']= false;
                                    $response['message']= "Modifier not saved Error:102";
                                }
                            }
                        }
                        // $this->Order_tax->query("UPDATE order_tax SET orderhistory_id  = '$lastorder_id' WHERE id = '$lastorder_taxid'");
                        
                        $this->Order_table->query("UPDATE order_tables SET status = 2 WHERE number = '$tableno'");
            
                        $response['status']= true;
                        $response['message']= "Orderhistory Data Saved Successfully..!";
                        $response['group_id']= $groupid;
                        $response['reference_id']= $tablereference_id;
                    }else{
                        $response['status']= false;
                        $response['message']= "Orderhistory Data not saved Error:101";
                    }
                }
            }else{
                $response['status']= false;
                $response['message']= "Table is not Available";
            }
        }
        return json_encode($response);
    }
/*
    public function orderhistorysave()
    {
        $response['status']= false;
        $response['message']= "fail";
        
        $cashierid = $_REQUEST['id'];
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id is Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }else{
            if (isset($_REQUEST['data'])) {
                $data = $_REQUEST['data'];
            } else {
                $response =array(
                    'status'=> false,
                    'message'=> "data not found",
                );
                return json_encode($response);
            }
            
            $data = json_decode($data, true);
            $waiter_id='';
            $waiter_name='';
            $reference_id=$data['reference_id'];
            $device_id=$data['device_id'];
            $name=$data['name'];
            $phone=$data['phone'];
            $address=$data['address'];
            $waiter_id=$data['waiter_id'];
            $waiter_name=$data['waiter_name'];
            
            //txnid check
            $trxchck = $this->Order_transaction->find('first', array('conditions'=>array('Order_transaction.reference_id'=>$reference_id)));
            if(!empty($trxchck))
            {
                $response =array(
                    'status'=> false,
                    'message'=> "Reference Id already Exist",
                );
                return json_encode($response);
            }        
            
            //orderhistory save
            
            $groupid .= rand(0, 9).$cashierid.time();
            
            foreach($data['orderhistory'] as $orderhistory){
                $order=false;
                $cat_id=$orderhistory['cat_id'];
                $cat_name=$orderhistory['cat_name'];
                
                if(isset($orderhistory['kds'])){
                    $kds=$orderhistory['kds'];
                }else{
                    $kds=1;
                }
                
                
                
                $datas['Order_orderhistory']=array(
                    'reference_id'=>$reference_id,
                    'group_id'=>$groupid,
                    'cashier_id'=>$cashierid,
                    'category'=>$orderhistory['cat_id'],
                    'category_name'=>$orderhistory['cat_name'],
                    'product_id'=>$orderhistory['product_id'],
                    'product_name'=>$orderhistory['product_name'],
                    'quantity'=>$orderhistory['quantity'],
                    'price'=>$orderhistory['price'],
                    'kds'=>$kds,
                    'total_tax'=>$orderhistory['total_tax'],
                    'total_tax_percentage'=>$orderhistory['total_tax_percentage'],
                    'total_price'=>$orderhistory['total_price'],
                    'discount'=>$orderhistory['discount'],
                    'remarks'=>$orderhistory['remarks'],
                    'device_id'=>$device_id
                );
                if($this->Order_orderhistory->saveAll($datas['Order_orderhistory']))
                {
                    $order=true;
                    $lastorder_id = $this->Order_orderhistory->id;
                    
                    foreach($orderhistory['order_tax'] as $tax){
                        $datas['Order_tax']=array(
                            'orderhistory_id'=>$lastorder_id,
                            'product_id'=>$orderhistory['product_id'],
                            'product_name'=>$orderhistory['product_name'],
                            'kds'=>$kds,
                            'price'=>$orderhistory['price'],
                            'taxable_price'=>round($orderhistory['price']*$orderhistory['quantity'],2),
                            'cat_id'=>$cat_id,
                            'cat_name'=>$cat_name,
                            'quantity'=>$orderhistory['quantity'],
                            'tax_id'=>$tax['id'],
                            'tax_name'=>$tax['tax_name'],
                            'tax_percentage'=>$tax['tax_percentage'],
                            'tax_value'=>$tax['tax_value'],
                            'reference_id'=>$reference_id
                        );
                        if($this->Order_tax->saveAll($datas['Order_tax']))
                        {
                            // $lastorder_taxid = $this->Order_tax->id;
                        }else{
                            $response['status']= false;
                            $response['message']= "Tax not saved Error:102";
                        }
                    }
                    // $this->Order_tax->query("UPDATE order_tax SET orderhistory_id  = '$lastorder_id' WHERE id = '$lastorder_taxid'");
                }else{
                    $response['status']= false;
                    $response['message']= "Orderhistory Data not saved Error:101";
                }
            }
            if($order){
                $todayDate = date("Y-m-d");
                $tdaytrx=$this->Order_transaction->query("SELECT COUNT(id) as tkn FROM `order_transactions` WHERE date(created)='$todayDate'");
                $token=$tdaytrx['0']['0']['tkn']+1;
                $currenttime=date("H:i:s");
                
                $orderdata=$this->Order_orderhistory->query("SELECT SUM(price) as price,sum(discount) as discount,sum(total_tax) as total_tax,SUM(total_price) as total_price FROM `order_orderhistories` WHERE reference_id='$reference_id'");
                // print_r($orderdata);exit;
                $datas['Order_transaction']=array(
                    'reference_id'=>$reference_id,
                    'device_id'=>$device_id,
                    'cashier_id'=>$cashierid,
                    'price'=>$orderdata[0][0]['total_price'],
                    'total_tax'=>$orderdata[0][0]['total_tax'],
                    'discount'=>$orderdata[0][0]['discount'],
                    'amount'=>round(($orderdata[0][0]['total_price']+$orderdata[0][0]['total_tax'])-$orderdata[0][0]['discount']),
                    'round'=>round(round(($orderdata[0][0]['total_price']+$orderdata[0][0]['total_tax'])-$orderdata[0][0]['discount'])-($orderdata[0][0]['total_price']+$orderdata[0][0]['total_tax'])-$orderdata[0][0]['discount'],2),
                    'name'=>$name,
                    'phone'=>$phone,
                    'address'=>$address,
                    'waiter_id'=>$waiter_id,
                    'waiter_name'=>$waiter_name,
                    'tokenno'=>$token,
                    'createtime'=>$currenttime
                );
                if($this->Order_transaction->saveAll($datas['Order_transaction']))
                {
                    $response['status']= true;
                    $response['message']= "Transaction Data Saved Successfully..!";
                }else{
                    $response['status']= false;
                    $response['message']= "Transaction Data not saved Error:102";
                }
            }
        }
        return json_encode($response);
    }
*/
    public function orderhistorysave_package()
    {
        $response['status']= false;
        $response['message']= "fail";
        
        $cashierid = $_REQUEST['id'];
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id is Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }else{
            if (isset($_REQUEST['data'])) {
                $data = $_REQUEST['data'];
            } else {
                $response =array(
                    'status'=> false,
                    'message'=> "data not found",
                );
                return json_encode($response);
            }
            
            $data = json_decode($data, true);
            $waiter_id='';
            $waiter_name='';
            $reference_id=$data['reference_id'];
            $device_id=$data['device_id'];
            $name=$data['name'];
            $phone=$data['phone'];
            $address=$data['address'];
            $waiter_id=$data['waiter_id'];
            $waiter_name=$data['waiter_name'];
            
            //txnid check
            $trxchck = $this->Order_transaction->find('first', array('conditions'=>array('Order_transaction.reference_id'=>$reference_id)));
            if(!empty($trxchck))
            {
                $response =array(
                    'status'=> false,
                    'message'=> "Reference Id already Exist",
                );
                return json_encode($response);
            }        
            
            if($phone!=''){
                //customer save
                $customerchk = $this->Order_customers->find('first', [
                    'conditions' => ['Order_customers.phone' => $phone],
                    'fields' => ['Order_customers.id'],
                    'recursive' => -1
                ]);
                
                if (empty($customerchk)) {
                
                // Insert new customer
                    $data = [
                        'Order_customers' => [
                            'phone'   => $phone,
                            'name'    => $name,
                            'address' => $address
                        ]
                    ];
                    
                    $this->Order_table->updateAll(
                        [
                            'Order_table.waiter_id' => "'0'",
                            'Order_table.waiter_name' => "''",
                            'Order_table.customer_name' => "''",
                            'Order_table.customer_phone' => "''",
                            'Order_table.customer_address' => "''"
                        ],
                        ['Order_table.reference_id' => $reference_id]
                    );
                    
                    if (!$this->Order_customers->saveAll($data)) {
                        $response =array(
                            'status'=> false,
                            'message'=> "Customer data not inserted",
                        );
                        return json_encode($response);
                    } 
                } else {
                    $this->Order_customers->id = $customerchk['Order_customers']['id'];
                    $this->Order_customers->save([
                        'name' => $name,
                        'address' => $address
                    ]);
                    $this->Order_table->updateAll(
                        [
                            'Order_table.waiter_id' => "'0'",
                            'Order_table.waiter_name' => "''",
                            'Order_table.customer_name' => "''",
                            'Order_table.customer_phone' => "''",
                            'Order_table.customer_address' => "''"
                        ],
                        ['Order_table.reference_id' => $reference_id]
                    );
                }
            }
            
            //orderhistory save
            $groupid .= rand(0, 9).$cashierid.time();
            $prepTimes = [];
            
            foreach ($data['orderhistory'] as $orderhistory) {
                $prep_timechck = $this->Catalog_product->find('first', [
                    'conditions' => [
                        'Catalog_product.id' => $orderhistory['product_id'],
                        'Catalog_product.status' => 1
                    ],
                    'fields' => ['Catalog_product.id','Catalog_product.preparation_time'],
                    'recursive' => -1
                ]);
            
                $prep = !empty($prep_timechck) ? intval($prep_timechck['Catalog_product']['preparation_time']) : 0;
                $prepTimes[] = $prep;
            }
            
            $maxPrep = !empty($prepTimes) ? max($prepTimes) : 0;

            foreach($data['orderhistory'] as $orderhistory){
                $order=false;
                $cat_id=$orderhistory['cat_id'];
                $cat_name=$orderhistory['cat_name'];
                $store_id = $orderhistory['store_id'];
                
                if(isset($orderhistory['kds'])){
                    $kds=$orderhistory['kds'];
                }else{
                    $kds=1;
                }
                
                $package = 0;
                
                $packagechck = $this->Catalog_product->find('first', [
                    'conditions' => [
                        'Catalog_product.id' => $orderhistory['product_id'],
                        'Catalog_product.status' => 1,
                        'Catalog_product.package' => 1
                    ],
                    'fields' => ['Catalog_product.id','Catalog_product.preparation_time'], // only fetch needed field
                    'recursive' => -1
                ]);
                
                if (!empty($packagechck)) {
                    $package = 1;
                }
                
                $prep_timechck = $this->Catalog_product->find('first', [
                    'conditions' => [
                        'Catalog_product.id' => $orderhistory['product_id'],
                        'Catalog_product.status' => 1
                    ],
                    'fields' => ['Catalog_product.id','Catalog_product.preparation_time'], // only fetch needed field
                    'recursive' => -1
                ]);
                $prep = !empty($prep_timechck) ? intval($prep_timechck['Catalog_product']['preparation_time']) : 0;
                
                if ($maxPrep == 0) {
                    $delaySeconds = 10; // default
                } elseif ($prep == $maxPrep) {
                    $delaySeconds = 10; // longest prep fires immediately (+ buffer)
                } else {
                    $diff = max(0, $maxPrep - $prep);
                    $delaySeconds = $diff * 60; // convert minutes → seconds
                }
                
                $fireTime = time() + $delaySeconds;
                $fireTime=date('Y-m-d H:i:s', $fireTime);
                $datas['Order_orderhistory']=array(
                    'reference_id'=>$reference_id,
                    'group_id'=>$groupid,
                    'cashier_id'=>$cashierid,
                    'category'=>$orderhistory['cat_id'],
                    'category_name'=>$orderhistory['cat_name'],
                    'product_id'=>$orderhistory['product_id'],
                    'product_name'=>$orderhistory['product_name'],
                    'quantity'=>$orderhistory['quantity'],
                    'price'=>$orderhistory['price'],
                    'package'=>$package,
                    'kds'=>$kds,
                    'total_tax'=>$orderhistory['total_tax'],
                    'total_tax_percentage'=>$orderhistory['total_tax_percentage'],
                    'total_price'=>$orderhistory['total_price'],
                    'discount'=>$orderhistory['discount'],
                    'remarks'=>$orderhistory['remarks'],
                    'device_id'=>$device_id,
                    'prep_time'=>$prep,
                    'fire_at' =>  $fireTime,
                    'store_id'=>$store_id
                );
                if($this->Order_orderhistory->saveAll($datas['Order_orderhistory']))
                {
                    $order=true;
                    $lastorder_id = $this->Order_orderhistory->id;
                    
                    foreach($orderhistory['order_tax'] as $tax){
                        $datas['Order_tax']=array(
                            'orderhistory_id'=>$lastorder_id,
                            'product_id'=>$orderhistory['product_id'],
                            'product_name'=>$orderhistory['product_name'],
                            'kds'=>$kds,
                            'price'=>$orderhistory['price'],
                            'taxable_price'=>round($orderhistory['price']*$orderhistory['quantity'],2),
                            'cat_id'=>$cat_id,
                            'cat_name'=>$cat_name,
                            'quantity'=>$orderhistory['quantity'],
                            'tax_id'=>$tax['id'],
                            'tax_name'=>$tax['tax_name'],
                            'tax_percentage'=>$tax['tax_percentage'],
                            'tax_value'=>$tax['tax_value'],
                            'reference_id'=>$reference_id,
                            'store_id'=>$store_id
                        );
                        if($this->Order_tax->saveAll($datas['Order_tax']))
                        {
                            // $lastorder_taxid = $this->Order_tax->id;
                        }else{
                            $response['status']= false;
                            $response['message']= "Tax not saved Error:102";
                        }
                    }
                    
                    foreach($orderhistory['selected_modifiers'] as $group_modifier){
                            $modifier_group_id=$group_modifier['modifier_group_id'];
                            $modifier_group_name=$group_modifier['modifier_group_name'];
                            $modifier_group_type=$group_modifier['group_type'];
                            
                            foreach($group_modifier['modifiers'] as $modifier){
                                
                                $modifier_id=$modifier['id'];
                                $modifier_name=$modifier['name'];
                                $modifier_price=$modifier['price'];
                                
                                $datas['Order_modifier']=array(
                                    'orderhistory_id'=>$lastorder_id,
                                    'product_id'=>$orderhistory['product_id'],
                                    'product_name'=>$orderhistory['product_name'],
                                    'modifier_group_id'=>$modifier_group_id,
                                    'modifier_group_name'=>$modifier_group_name,
                                    'modifier_group_type'=>$modifier_group_type,
                                    'modifier_id'=>$modifier_id,
                                    'modifier_name'=>$modifier_name,
                                    'modifier_price'=>$modifier_price,
                                    'quantity'=>$orderhistory['quantity'],
                                    'reference_id'=>$reference_id,
                                    'store_id'=>$store_id
                                );
                                if($this->Order_modifier->saveAll($datas['Order_modifier']))
                                {
                                    // $lastorder_taxid = $this->Order_tax->id;
                                }else{
                                    $response['status']= false;
                                    $response['message']= "Modifier not saved Error:102";
                                }
                            }
                        }
                    // $this->Order_tax->query("UPDATE order_tax SET orderhistory_id  = '$lastorder_id' WHERE id = '$lastorder_taxid'");
                }else{
                    $response['status']= false;
                    $response['message']= "Orderhistory Data not saved Error:101";
                }
            }
            // 1. Set package=1 for packaged items using JOIN (efficient)
            $this->Order_orderhistory->query("
                UPDATE order_orderhistories o
                JOIN catalog_package p ON o.product_id = p.main_product_id AND p.status = 1
                SET o.package = 1
                WHERE o.reference_id = '$reference_id' AND o.status != 0
            ");
            
            $this->Order_tax->query("
                UPDATE order_tax t
                JOIN catalog_package p ON t.product_id = p.main_product_id AND p.status = 1
                SET t.package = 1
                WHERE t.reference_id = '$reference_id' AND t.status = 1
            ");            
                        
            // 2. Get total packaged quantity
            $total_package = 0;
            $totalpackagechkorder = $this->Order_orderhistory->query("
                SELECT SUM(package) AS total_package
                FROM order_orderhistories 
                WHERE reference_id = '$reference_id' AND status != 0 AND package = 1
            ");
            $packagechngchk=false;
            if (!empty($totalpackagechkorder[0][0]['total_package'])) {
                
                $total_package = isset($totalpackagechkorder[0][0]['total_package']) 
                    ? $totalpackagechkorder[0][0]['total_package'] 
                    : 0;
                      
                // 3. Non-package items and discount percentage logic
                $discount_percentage = 0;
                $nonpackagechkorder = $this->Order_orderhistory->query("
                    SELECT product_id, SUM(quantity) as order_quantity
                    FROM order_orderhistories 
                    WHERE reference_id = '$reference_id' AND status != 0 AND package = 0
                    GROUP BY product_id
                ");
                $discount_pro_array = []; // initialize
                
                foreach ($nonpackagechkorder as $row) {
                    $orderproduct_id = $row['order_orderhistories']['product_id'];
                    $orderproduct_quantity = $row[0]['order_quantity'];
                
                    // 4. Find linked package quantity for this non-package item
                    $linkpackagechk = $this->Catalog_package->query("
                        SELECT SUM(link_quantity) AS link_qty
                        FROM catalog_package
                        WHERE link_product_id = '$orderproduct_id' AND status = 1
                        AND main_product_id IN (
                            SELECT product_id 
                            FROM order_orderhistories 
                            WHERE reference_id = '$reference_id' AND package = 1
                        )
                    ");
                
                    $link_package_item_quantity = 0;
                    if (!empty($linkpackagechk[0][0]['link_qty'])) {
                        $link_package_item_quantity = $linkpackagechk[0][0]['link_qty'];
                    }
            
                    // 5. Calculate discount
                    if ($orderproduct_quantity <= $link_package_item_quantity) {
                        $discount_percentage = 100;
                    } elseif ($link_package_item_quantity > 0) {
                        $discount_percentage = round(($link_package_item_quantity * 100) / $orderproduct_quantity, 2);
                    } else {
                        $discount_percentage = 0;
                    }
                    
                    $orderdata = $this->ordercomputewithpackagediscount($reference_id, $cashierid,$orderproduct_id, $discount_percentage);
                    if($orderdata['status'])
                    {
                        $packagechngchk=true;
                    }
                }
            }
    
            if($order){
                $todayDate = date("Y-m-d");
                $currenttime=date("H:i:s");
                
                $locations = $this->Order_orderhistory->query("SELECT store_id FROM `order_orderhistories` WHERE reference_id='$reference_id' and status!=0 group BY store_id");
                
                foreach($locations as $location){
                    $location_id = $location['order_orderhistories']['store_id'];
                    
                    $tdaytrx=$this->Order_transaction->query("SELECT COUNT(id) as tkn FROM `order_transactions` WHERE date(created)='$todayDate' and cashier_id='$cashierid'  ");
                    $token=$tdaytrx['0']['0']['tkn']+1;
                    
                    $orderdata=$this->Order_orderhistory->query("SELECT SUM(price) as price,sum(discount) as discount,sum(total_tax) as total_tax,SUM(total_price) as total_price FROM `order_orderhistories` WHERE reference_id='$reference_id' and store_id='$location_id'");
                    $updated_discount=0;
                    $updated_tax=0;
                    $updated_final_amount=0;
                    
                    if($packagechngchk){
                        $orderstaxdatas = $this->Order_tax->query("SELECT ot.product_id, SUM((ot.price * ot.quantity) * (ot.discount_percentage / 100)) AS discounted_total, SUM(((ot.price * ot.quantity) * (ot.discount_percentage / 100)) * (IFNULL(ooh.tax_percent, 0) / 100)) AS total_tax, SUM(((ot.price * ot.quantity) * (ot.discount_percentage / 100)) * (1 + (IFNULL(ooh.tax_percent, 0) / 100))) AS final_amount FROM order_tax ot LEFT JOIN ( SELECT product_id, SUM(total_tax_percentage) AS tax_percent FROM order_orderhistories WHERE reference_id = '$reference_id' AND status = 1 and store_id='$location_id' GROUP BY product_id ) ooh ON ooh.product_id = ot.product_id WHERE ot.reference_id = '$reference_id' AND ot.package = 0  and ot.store_id='$location_id' AND ot.status = 1");
                        if(!empty($orderstaxdatas))
                        {
                            $updated_discount=$orderstaxdatas[0][0]['discounted_total'];
                            $updated_tax=$orderstaxdatas[0][0]['total_tax'];
                            $updated_final_amount=$orderstaxdatas[0][0]['final_amount'];
                        }
                    }
                    $finalamount = round(($orderdata[0][0]['total_price']+$orderdata[0][0]['total_tax'])-$orderdata[0][0]['discount']-$updated_final_amount);        // Rounded to nearest integer
                    $roundfinalamount = round(($orderdata[0][0]['total_price']+$orderdata[0][0]['total_tax'])-$orderdata[0][0]['discount']-$updated_final_amount,2); // Rounded to 2 decimal places
                    
                    $round_amount = $finalamount - $roundfinalamount;
                    
                    $datas['Order_transaction']=array(
                        'reference_id'=>$reference_id,
                        'device_id'=>$device_id,
                        'cashier_id'=>$cashierid,
                        'price'=>$orderdata[0][0]['total_price']-$updated_discount,
                        'total_tax'=>round($orderdata[0][0]['total_tax']-$updated_tax,3),
                        'discount'=>$orderdata[0][0]['discount'] ?? 0,
                        'amount'=>$finalamount,
                        'round'=>round($round_amount,2),
                        'name'=>$name,
                        'phone'=>$phone,
                        'address'=>$address,
                        'waiter_id'=>$waiter_id,
                        'waiter_name'=>$waiter_name,
                        'tokenno'=>$token,
                        'createtime'=>$currenttime,
                        'store_id'=>$location_id,
                        'group_id'=>$groupid
                    );
                    
                    if($this->Order_transaction->saveAll($datas['Order_transaction']))
                    {
                        $dbsave=true;
                        $error = '';
                    }else{
                        $dbsave=false;
                        $error = $store_id;
                    }
                }    
                
                
                if($dbsave)
                {
                    $response['status']= true;
                    $response['message']= "Transaction Data Saved Successfully..!";
                }else{
                    $response['status']= false;
                    $response['message']= "Transaction Data not saved Error for store - ".$error;
                }
                
            }
        }
        return json_encode($response);
    }

    public function orderpaymentsave()
    {
        $response['status']= false;
        $response['message']= "fail";
        
        $cashierid = $_REQUEST['id'];
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id is Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }else{
            if (isset($_REQUEST['data'])) {
                $data = $_REQUEST['data'];
            } else {
                $response =array(
                    'status'=> false,
                    'message'=> "data not found",
                );
                return json_encode($response);
            }
            
            $data = json_decode($data, true);
            
            $reference_id=$data['reference_id'];
            $device_id=$data['device_id'];
            
            //txn_amount_total sum of payment
            $transactions = $this->Order_transaction->find('first', array(
                'fields' => array('SUM(Order_transaction.amount) AS total_amount'),
                'conditions' => array(
                    'Order_transaction.reference_id' => $reference_id,
                    'Order_transaction.status' => 1
                )
            ));
            
            $total_txn_Amount = !empty($transactions[0]['total_amount']) ? $transactions[0]['total_amount'] : 0;
            
            if (empty($transactions[0]['total_amount'])) {
                $response = array(
                    'status' => false,
                    'message' => "Transaction not found",
                );
                return json_encode($response);
            } else{
                //checkloop  $reference_id from transaction 
                $check_refernce_with_store = $this->Order_transaction->find('all', array(
                    'fields' => array('store_id','id','amount'),
                    'conditions' => array(
                        'Order_transaction.reference_id' => $reference_id,
                        'Order_transaction.status' => 1
                    )
                ));
                
                foreach($check_refernce_with_store as $ref_store){
                
                    $store_id=$ref_store['Order_transaction']['store_id'];
                    $txn_table_id=$ref_store['Order_transaction']['id'];
                    $txn_amount=$ref_store['Order_transaction']['amount'];
                
                    foreach($data['payment'] as $payment){
                        
                        //save store id,txn table id ,round  - 50
                        //calulated amount percent = $payment['amount']/ txn_amount_total
                        // 50/100 =0.333
                        // final_payment= txn_amount * calulated amount percent
                        //round 
                        
                        $amount_percent = $payment['amount'] / $total_txn_Amount;
                        $final_payment = round($txn_amount * $amount_percent);
                        $actual_payment = round($txn_amount * $amount_percent,2);
                        
                        $round = $final_payment - $actual_payment;
                    
                        //round value need to check
                        $datas['Order_payment']=array(
                            'reference_id'=>$reference_id,
                            'device_id'=>$device_id,
                            'cashier_id'=>$cashierid,
                            'type'=>$payment['type'],
                            'type_value'=>$payment['type_value'],
                            'amount'=>$final_payment,
                            'remarks'=>$payment['remarks'],
                            'store_id'=>$store_id,
                            'txn_table_id'=>$txn_table_id,
                            'round'=>round($round,2)
                        );
                        
                        if($this->Order_payment->saveAll($datas['Order_payment']))
                        {
                            $finalpayment=0;
                            $finalamount=0;
                            $allpayments=$this->Order_payment->query("SELECT sum(amount) as pay_amount FROM `order_payments` WHERE reference_id='$reference_id'");
                            if($allpayments){
                                $finalpayment=$allpayments[0][0]['pay_amount']; //150
                            }
                            
                            $finalamount=$total_txn_Amount ?? 0; //txn_amount_total
                        
                            $amount_diff=$finalamount-$finalpayment;
                            if($amount_diff<1){
                                   
                                $this->Order_orderhistory->query("UPDATE order_orderhistories SET status = 2 WHERE reference_id = '$reference_id' and status = 1");
                                $this->Order_transaction->query("UPDATE order_transactions SET status = 2,payment_mode='$type_value' WHERE reference_id = '$reference_id'");
                                $this->Order_payment->query("UPDATE order_payments SET status = 2 WHERE reference_id = '$reference_id'");
                                $this->Order_tax->query("UPDATE order_tax SET status = 2 WHERE reference_id = '$reference_id' and status != 0");
                                
                                
                                //stock update
                                $stockupdate=$this->stock_update($reference_id);
                                if($stockupdate){
                                    $response['status']= true;
                                    $response['message']= "Payment Data Saved Successfully..!";
                                    $response['full_payment']= true;
                                }else{
                                    $response['status']= true;
                                    $response['message']= "Payment Data Saved Successfully..! But stock not updated";
                                    $response['full_payment']= true;
                                }
                            }else{
                                $response['status']= true;
                                $response['message']= "Payment Data Saved Successfully..!";
                                $response['full_payment']= false;
                            }            
                        }else{
                            $response['status']= false;
                            $response['message']= "Payment Data not saved Error:102";
                            $response['full_payment']= false;
                        }
                    }
                    //loop end txn
                }
            }
        }
        return json_encode($response);
    }
    

    
    public function reprint_kot()
    {
        $cashierid = $_REQUEST['id'];
        $reference_id = $_REQUEST['reference_id'];
        $group_id = $_REQUEST['group_id'];
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "User Id Missing",
            );
            return json_encode($response);
        }
        if($reference_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Reference Id Missing",
            );
            return json_encode($response);
        }
        if($group_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Group Id Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        $orderitems=[];
        
        $orderss = $this->Order_orderhistory->query("SELECT * FROM `order_orderhistories` WHERE reference_id='$reference_id' and group_id='$group_id' and status!=0 ");
        // print_r("SELECT id,reference_id,group_id,cashier_id,category,category_name,product_id,product_name,SUM(quantity) as quantity,sum(price) as price,sum(total_tax) as total_tax,sum(total_tax_percentage) as total_tax_percentage,sum(total_price) as total_price,SUM(discount) as discount FROM `order_orderhistories` WHERE reference_id='$reference_id' and status!=0 group BY product_id");exit;
        if(!empty($orderss))
        {
            foreach($orderss as $orders){
                $product_id=$orders['order_orderhistories']['product_id'];
                $order_id=$orders['order_orderhistories']['id'];
                $selected_modifiers=[];
                $orders_modifiers = $this->Order_modifier->query("SELECT * FROM `order_modifier` WHERE reference_id='$reference_id' and product_id='$product_id' and orderhistory_id='$order_id' and status!=0");
                
                // $orders_modifiers = $this->Order_modifier->query("SELECT * FROM `order_modifier` WHERE reference_id='$reference_id' and product_id='$product_id' and status!=0");
                foreach($orders_modifiers as $orders_modifier){
                    
                    $modifiers=$orders_modifier['order_modifier'];
                    $modifier_group_id=$modifiers['modifier_group_id'];
                    $modifier_group_name=$modifiers['modifier_group_name'];
                    $modifier_id=$modifiers['modifier_id'];
                    $modifier_name=$modifiers['modifier_name'];
                    $modifier_price=$modifiers['modifier_price'];
                    
                    $selected_modifiers[]=array(
                        'modifier_group_id' => $modifier_group_id,
                        'modifier_group_name' => $modifier_group_name,
                        'modifier_id' => $modifier_id,
                        'modifier_name' => $modifier_name,
                        'modifier_price' => $modifier_price,
                        );
                    
                }
                
                if(!isset($orders['order_orderhistories']['remarks'])){
                    $orders['order_orderhistories']['remarks']='';
                }
                $orderitems[]=array(
                    'id' => $orders['order_orderhistories']['id'],
                    'reference_id' =>  $orders['order_orderhistories']['reference_id'],
                    'cashier_id' =>  $orders['order_orderhistories']['cashier_id'],
                    'group_id' =>  $orders['order_orderhistories']['group_id'],
                    'category' =>  $orders['order_orderhistories']['category'],
                    'category_name' =>  $orders['order_orderhistories']['category_name'],
                    'kds' =>  $orders['order_orderhistories']['kds'],
                    'product_id' =>  $orders['order_orderhistories']['product_id'],
                    'product_name' =>  $orders['order_orderhistories']['product_name'],
                    'quantity' =>  $orders['order_orderhistories']['quantity'],
                    'price' =>  $orders['order_orderhistories']['price'],
                    'total_tax' =>  $orders['order_orderhistories']['total_tax'],
                    'total_price' =>  $orders['order_orderhistories']['total_price'],
                    'discount' =>  $orders['order_orderhistories']['discount'],
                    'table_number' =>  $orders['order_orderhistories']['table_number'],
                    'remarks' =>  $orders['order_orderhistories']['remarks'],
                    'selected_modifiers' => $selected_modifiers,
                    'status' =>  $orders['order_orderhistories']['status'],
                    'created' =>  $orders['order_orderhistories']['created']
                );
            }
        }
        $finalamount=0;
        $transactionitems=[];
        $transactions = $this->Order_transaction->find('all', array('conditions'=>array('reference_id'=>$reference_id,'status !='=>0)));
        if(!empty($transactions))
        {
            foreach($transactions as $orders){
                if(!$orders['Order_transaction']['remarks']){
                    $orders['Order_transaction']['remarks']='';
                }
                $finalamount=$orders['Order_transaction']['amount'];
                $cashierid=$orders['Order_transaction']['cashier_id'];
                $reference_id=$orders['Order_transaction']['reference_id'];
                
                $discper = $this->Order_tax->query("SELECT discount_percentage FROM `order_tax` WHERE reference_id='$reference_id' and status=2 and discount_percentage!=0 limit 1");
                if(!empty($discper))
                {
                    $discount_percentage=$discper[0]['order_tax']['discount_percentage'];
                }
                if(!isset($discount_percentage)){
                    $discount_percentage="0";
                }
                
                $transactionitems[]=array(
                    'id' => $orders['Order_transaction']['id'],
                    'reference_id' =>  $orders['Order_transaction']['reference_id'],
                    'orderno' =>  $orders['Order_transaction']['orderno'],
                    'device_id' =>  $orders['Order_transaction']['device_id'],
                    'cashier_id' =>  $orders['Order_transaction']['cashier_id'],
                    'table_number' =>  $orders['Order_transaction']['table_number'],
                    'price' =>  $orders['Order_transaction']['price'],
                    'total_tax' =>  $orders['Order_transaction']['total_tax'],
                    'servicecharge' =>  $orders['Order_transaction']['servicecharge'],
                    'discount' =>  $orders['Order_transaction']['discount'],
                    'discount_percentage' =>  $discount_percentage,
                    'discount_type' =>  $orders['Order_transaction']['discount_type'],
                    'discount_type_value' =>  $orders['Order_transaction']['discount_type_value'],
                    'delivery_charge' =>  $orders['Order_transaction']['delivery_charge'],
                    'packing_charge' =>  $orders['Order_transaction']['packing_charge'],
                    'amount' =>  $orders['Order_transaction']['amount'],
                    'round' =>  $orders['Order_transaction']['round'],
                    'name' =>  $orders['Order_transaction']['name'],
                    'phone' =>  $orders['Order_transaction']['phone'],
                    'address' =>  $orders['Order_transaction']['address'],
                    'remarks' =>  $orders['Order_transaction']['remarks'],
                    'status' =>  $orders['Order_transaction']['status'],
                    'tokenno' =>  $orders['Order_transaction']['tokenno'],
                    'createtime' =>  $orders['Order_transaction']['createtime'],
                    'created' =>  $orders['Order_transaction']['created']
                );
            }
        }
        $paymentitems=[];
        $payments = $this->Order_payment->find('all', array('conditions'=>array('reference_id'=>$reference_id,'status !='=>0)));
        if(!empty($payments))
        {
            foreach($payments as $orders){
                if(!isset($orders['Order_payment']['remarks'])){
                    $orders['Order_payment']['remarks']='';
                }
                $paymentitems[]=array(
                    'id' => $orders['Order_payment']['id'],
                    'reference_id' =>  $orders['Order_payment']['reference_id'],
                    'cashier_id' =>  $orders['Order_payment']['cashier_id'],
                    'type' =>  $orders['Order_payment']['type'],
                    'type_value' =>  $orders['Order_payment']['type_value'],
                    'amount' =>  $orders['Order_payment']['amount'],
                    'status' =>  $orders['Order_payment']['status'],
                    'remarks' =>  $orders['Order_payment']['remarks'],
                    'created' =>  $orders['Order_payment']['created']
                );
            }
        }
        $taxitems=[];
        $taxes = $this->Order_tax->query("SELECT tax_id,tax_name,tax_percentage,sum(tax_value) as tax_value FROM `order_tax` WHERE reference_id='$reference_id' and status!=0 GROUP by tax_id");
        if(!empty($taxes))
        {
            foreach($taxes as $tax){
                // print_r($tax);exit;
                
                $taxitems[]=array(
                    'tax_id' => $tax['order_tax']['tax_id'],
                    'tax_name' =>  $tax['order_tax']['tax_name'],
                    'tax_percentage' =>  $tax['order_tax']['tax_percentage'],
                    'tax_value' =>  "" .round($tax[0]['tax_value'],2)
                );
            }
        }
        $finalpayment=0;
        $allpayments=$this->Order_payment->query("SELECT sum(amount) as pay_amount FROM `order_payments` WHERE reference_id='$reference_id'");
        if($allpayments){
            $finalpayment=$allpayments[0][0]['pay_amount'];
        }
        $amount_diff=round(($finalamount-$finalpayment),2);
        
        $cashier_name='';
        $cashname=$this->User->query("SELECT name FROM `users` WHERE id='$cashierid'");
        if($cashname){
           $cashier_name =$cashname[0]['users']['name'];
        }
        
        $printeritems=[];
        $printerss = $this->Pos_printer->query("SELECT * FROM `pos_printers` WHERE status=1");
        if(!empty($printerss))
        {
            foreach($printerss as $printers){
                // print_r($tax);exit;
                
                $printeritems[]=array(
                    'id' => $printers['pos_printers']['id'],
                    'store_id' =>  $printers['pos_printers']['store_id'],
                    'name' =>  $printers['pos_printers']['name'],
                    'kds' =>  $printers['pos_printers']['kds'],
                    'ip' =>  $printers['pos_printers']['ip'],
                    'status' =>  $printers['pos_printers']['status']
                );
            }
        }
        
        $response= array('status'=> true,
                'message'=> "success",
                'cashier_name'=>$cashier_name,
                'orders'=>$orderitems,
                'transactions'=>$transactionitems,
                'payments'=>$paymentitems,
                'taxes'=>$taxitems,
                'printers'=>$printeritems,
                'remaining_amount'=>number_format($amount_diff, 2, '.', '')
            );
        return json_encode($response);
    }
    public function bill_table()
    {
        $response['status']= false;
        $response['message']= "fail";
        
        $cashierid = $_REQUEST['id'];
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id is Missing",
            );
            return json_encode($response);
        }
        $table_number = $_REQUEST['table_number'];
        if($table_number==''){
            $response =array(
                'status'=> false,
                'message'=> "Table Number is Missing",
            );
            return json_encode($response);
        }
        $table_referenceid = $_REQUEST['reference_id'];
        if($table_referenceid==''){
            $response =array(
                'status'=> false,
                'message'=> "Table refernce Id is Missing",
            );
            return json_encode($response);
        }
        $device_id='';
        if(isset($_REQUEST['device_id'])){
            $device_id=$_REQUEST['device_id'];
        }
        $name='';
        if(isset($_REQUEST['name'])){
            $name=$_REQUEST['name'];
        }
        $phone='';
        if(isset($_REQUEST['phone'])){
            $phone=$_REQUEST['phone'];
        }
        $address='';
        if(isset($_REQUEST['address'])){
            $address=$_REQUEST['address'];
        }
        $pax=1;
        if(isset($_REQUEST['pax'])){
            $pax=$_REQUEST['pax'];
        }
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
            
        $tablechk = $this->Order_table->find('first', array('conditions'=>array('Order_table.reference_id'=>$table_referenceid,'Order_table.number'=>$table_number,'Order_table.status'=>2)));
        if(empty($tablechk))
        {
            $response =array(
                'status'=> false,
                'message'=> "Something went wrong for this table kindly check!!!",
            );
            return json_encode($response);
        }
        $waiter_id=$tablechk['Order_table']['waiter_id'];
        $waiter_name = $tablechk['Order_table']['waiter_name'];
        $pax = $tablechk['Order_table']['pax'];
        $is_takeaway = $tablechk['Order_table']['is_takeaway'];
        
        
        //txnid check status chkr not 3,4
        $trxchck = $this->Order_transaction->find('first', array('conditions'=>array('Order_transaction.reference_id'=>$table_referenceid)));
        if(!empty($trxchck))
        {
            $response =array(
                'status'=> false,
                'message'=> "Reference Id already Exist",
            );
            return json_encode($response);
        }        
        //chk package value in table - item in ordergistory link quanti*package
        //discount update in ordertax
        $orderss = $this->Order_orderhistory->query("SELECT sum(price) as price,sum(total_tax) as total_tax,sum(total_price) as total_price,sum(discount) as discount FROM `order_orderhistories` WHERE reference_id='$table_referenceid' and status!=0");
        if(!empty($orderss))
        {
            if($orderss[0][0]['total_price']<1){
                $response =array(
                    'status'=> false,
                    'message'=> "There is no item to bill. Please Check..!",
                );
                return json_encode($response);
            }
            
            $todayDate = date("Y-m-d");
            $tdaytrx=$this->Order_transaction->query("SELECT COUNT(id) as tkn FROM `order_transactions` WHERE date(created)='$todayDate'  and cashier_id='$cashierid' and status=2");
            $token=$tdaytrx['0']['0']['tkn']+1;
            $currenttime=date("H:i:s");
            
            $datas['Order_transaction']=array(
                'reference_id'=>$table_referenceid,
                'device_id'=>$device_id,
                'cashier_id'=>$cashierid,
                'price'=>round($orderss[0][0]['total_price'],2),
                'total_tax'=>round($orderss[0][0]['total_tax'],2),
                'discount'=>round($orderss[0][0]['discount'],2),
                'amount'=>round(($orderss[0][0]['total_price']+$orderss[0][0]['total_tax'])-$orderss[0][0]['discount']),
                'round'=>round(round(($orderss[0][0]['total_price']+$orderss[0][0]['total_tax'])-$orderss[0][0]['discount'])-($orderss[0][0]['total_price']+$orderss[0][0]['total_tax'])-$orderss[0][0]['discount'],2),
                'name'=>$name,
                'phone'=>$phone,
                'address'=>$address,
                'tokenno'=>$token,
                'table_number'=>$table_number,
                'pax'=>$pax,
                'waiter_id'=>$waiter_id,
                'waiter_name'=>$waiter_name,
                'is_takeaway' => $is_takeaway,
                'createtime'=>$currenttime
            );
            if($this->Order_transaction->saveAll($datas['Order_transaction']))
            {
                $this->Order_table->query("UPDATE order_tables SET status = 3 WHERE reference_id = '$table_referenceid'");
        
                $response['status']= true;
                $response['message']= "Bill Generated Successfully..!";
            }else{
                $response['status']= false;
                $response['message']= "Transaction Data not saved Error:103";
            }
        }
        
        return json_encode($response);
    }
    
    public function bill_table_package()
    {
        $response['status']= false;
        $response['message']= "fail";
        
        $cashierid = $_REQUEST['id'];
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id is Missing",
            );
            return json_encode($response);
        }
        $table_number = $_REQUEST['table_number'];
        if($table_number==''){
            $response =array(
                'status'=> false,
                'message'=> "Table Number is Missing",
            );
            return json_encode($response);
        }
        $table_referenceid = $_REQUEST['reference_id'];
        if($table_referenceid==''){
            $response =array(
                'status'=> false,
                'message'=> "Table refernce Id is Missing",
            );
            return json_encode($response);
        }
        $device_id='';
        if(isset($_REQUEST['device_id'])){
            $device_id=$_REQUEST['device_id'];
        }
        $name='';
        if(isset($_REQUEST['name'])){
            $name=$_REQUEST['name'];
        }
        $phone='';
        if(isset($_REQUEST['phone'])){
            $phone=$_REQUEST['phone'];
        }
        $address='';
        if(isset($_REQUEST['address'])){
            $address=$_REQUEST['address'];
        }
        $pax=1;
        if(isset($_REQUEST['pax'])){
            $pax=$_REQUEST['pax'];
        }
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        else{
            $location_id = $users['User']['location_id'];
        }
            
        $tablechk = $this->Order_table->find('first', array('conditions'=>array('Order_table.reference_id'=>$table_referenceid,'Order_table.number'=>$table_number,'Order_table.status'=>2)));
        if(empty($tablechk))
        {
            $response =array(
                'status'=> false,
                'message'=> "Something went wrong for this table kindly check!!!",
            );
            return json_encode($response);
        }
        $waiter_id=$tablechk['Order_table']['waiter_id'];
        $waiter_name = $tablechk['Order_table']['waiter_name'];
        $pax = $tablechk['Order_table']['pax'];
        $name    = trim($tablechk['Order_table']['customer_name']);
        $phone   = trim($tablechk['Order_table']['customer_phone']);
        $address = trim($tablechk['Order_table']['customer_address']);
        $is_takeaway = $tablechk['Order_table']['is_takeaway'];

        $customerchk = $this->Order_customers->find('first', [
            'conditions' => ['Order_customers.phone' => $phone],
            'fields' => ['Order_customers.id'],
            'recursive' => -1
        ]);
    
        if (empty($customerchk)) {
            // Insert new customer
            $data = [
                'Order_customers' => [
                    'phone'   => $phone,
                    'name'    => $name,
                    'address' => $address
                ]
            ];
    
            if ($this->Order_customers->saveAll($data)) {
                
            } else {
                return json_encode([
                    'status' => false,
                    'message' => "Failed to save customer details."
                ]);
            }
        } else {
            // Customer already exists — optional: update their name/address if needed
            $this->Order_customers->id = $customerchk['Order_customers']['id'];
            $this->Order_customers->save([
                'name' => $name,
                'address' => $address
            ]);
    
        }
        
        $this->Order_table->updateAll(
            [
                'Order_table.waiter_id' => "'0'",
                'Order_table.waiter_name' => "''",
                'Order_table.customer_address' => "''",
                'Order_table.customer_phone' => "''",
                'Order_table.customer_phone' => "''",
            ],
            ['Order_table.reference_id' => $table_referenceid]
        );
        
        $trxchck = $this->Order_transaction->find('first', array(
            'conditions' => array(
                'Order_transaction.reference_id' => $table_referenceid,
                'NOT' => array('Order_transaction.status' => array(3, 4))
            )
        ));
        if(!empty($trxchck))
        {
            $response =array(
                'status'=> false,
                'message'=> "Reference Id already Exist",
            );
            return json_encode($response);
        }        
        
        //chk package value in table - item in ordergistory link quanti*package
        // Fetch all product_ids for the given reference_id
        // 1. Set package=1 for packaged items using JOIN (efficient)
        $this->Order_orderhistory->query("
            UPDATE order_orderhistories o
            JOIN catalog_package p ON o.product_id = p.main_product_id AND p.status = 1
            SET o.package = 1
            WHERE o.reference_id = '$table_referenceid' AND o.status != 0
        ");
        
        $this->Order_tax->query("
            UPDATE order_tax t
            JOIN catalog_package p ON t.product_id = p.main_product_id AND p.status = 1
            SET t.package = 1
            WHERE t.reference_id = '$table_referenceid' AND t.status = 1
        ");
        // 2. Get total packaged quantity
        $total_package = 0;
        $totalpackagechkorder = $this->Order_orderhistory->query("
            SELECT SUM(package) AS total_package
            FROM order_orderhistories 
            WHERE reference_id = '$table_referenceid' AND status != 0 AND package = 1
        ");
        $packagechngchk=false;
        if (!empty($totalpackagechkorder[0][0]['total_package'])) {
            
            $total_package = isset($totalpackagechkorder[0][0]['total_package']) 
                ? $totalpackagechkorder[0][0]['total_package'] 
                : 0;
                // 3. Non-package items and discount percentage logic
                $discount_percentage = 0;
                $nonpackagechkorder = $this->Order_orderhistory->query("
                    SELECT product_id, SUM(quantity) as order_quantity
                    FROM order_orderhistories 
                    WHERE reference_id = '$table_referenceid' AND status != 0 AND package = 0
                    GROUP BY product_id
                ");
                $discount_pro_array = []; // initialize
                foreach ($nonpackagechkorder as $row) {
                    $orderproduct_id = $row['order_orderhistories']['product_id'];
                    $orderproduct_quantity = $row[0]['order_quantity'];
                    
                    // 4. Find linked package quantity for this non-package item
                    $linkpackagechk = $this->Catalog_package->query("
                        SELECT SUM(link_quantity) AS link_qty,link_product_id
                        FROM catalog_package
                        WHERE link_product_id = '$orderproduct_id' AND status = 1
                        AND main_product_id IN (
                            SELECT product_id 
                            FROM order_orderhistories 
                            WHERE reference_id = '$table_referenceid' AND package = 1
                        )
                    ");
                    
                    $link_package_item_quantity = 0;
                    if (!empty($linkpackagechk[0][0]['link_qty'])) {
                        $link_package_item_quantity = $linkpackagechk[0][0]['link_qty'];
                    }
                    
                    // 5. Calculate discount
                    if ($orderproduct_quantity <= $link_package_item_quantity) {
                        $discount_percentage = 100;
                    } elseif ($link_package_item_quantity > 0) {
                        $discount_percentage = round(($link_package_item_quantity * 100) / $orderproduct_quantity, 2);
                    } else {
                        $discount_percentage = 0;
                    }
                    // print_r($discount_percentage);exit;
                
                    $orderdata = $this->ordercomputewithpackagediscount($table_referenceid, $cashierid,$orderproduct_id, $discount_percentage);
                    if($orderdata['status'])
                    {
                        $packagechngchk=true;
                    }
                }
            }

            //discount update in ordertax
            $orderss = $this->Order_orderhistory->query("SELECT sum(price) as price,sum(total_tax) as total_tax,sum(total_price) as total_price,sum(discount) as discount FROM `order_orderhistories` WHERE reference_id='$table_referenceid' and status!=0");
            if(!empty($orderss))
            {
                if($orderss[0][0]['total_price']<1){
                    $response =array(
                        'status'=> false,
                        'message'=> "There is no item to bill. Please Check..!",
                    );
                    return json_encode($response);
                }
                
                $todayDate = date("Y-m-d");
                $tdaytrx=$this->Order_transaction->query("SELECT COUNT(id) as tkn FROM `order_transactions` WHERE date(created)='$todayDate' and cashier_id='$cashierid' and status=2");
                $token=$tdaytrx['0']['0']['tkn']+1;
                $currenttime=date("H:i:s");
                $updated_discount=0;
                $updated_tax=0;
                $updated_final_amount=0;
                if($packagechngchk){
                    $orderstaxdatas = $this->Order_tax->query("SELECT ot.product_id, SUM((ot.price * ot.quantity) * (ot.discount_percentage / 100)) AS discounted_total, SUM(((ot.price * ot.quantity) * (ot.discount_percentage / 100)) * (IFNULL(ooh.tax_percent, 0) / 100)) AS total_tax, SUM(((ot.price * ot.quantity) * (ot.discount_percentage / 100)) * (1 + (IFNULL(ooh.tax_percent, 0) / 100))) AS final_amount FROM order_tax ot LEFT JOIN ( SELECT product_id, SUM(total_tax_percentage) AS tax_percent FROM order_orderhistories WHERE reference_id = '$table_referenceid' AND status = 1 GROUP BY product_id ) ooh ON ooh.product_id = ot.product_id WHERE ot.reference_id = '$table_referenceid' AND ot.package = 0 AND ot.status = 1");
                    if(!empty($orderstaxdatas))
                    {
                        $updated_discount=$orderstaxdatas[0][0]['discounted_total'];
                        $updated_tax=$orderstaxdatas[0][0]['total_tax'];
                        $updated_final_amount=$orderstaxdatas[0][0]['final_amount'];
                    }
                }
                $grand_total = $orderss[0][0]['total_price'] + $orderss[0][0]['total_tax'];
                $net_total = $grand_total - $orderss[0][0]['discount'] - $updated_final_amount;
                
                $finalamount = round(($orderss[0][0]['total_price']+$orderss[0][0]['total_tax'])-$orderss[0][0]['discount']-$updated_final_amount);        // Rounded to nearest integer
                $roundfinalamount = round(($orderss[0][0]['total_price']+$orderss[0][0]['total_tax'])-$orderss[0][0]['discount']-$updated_final_amount,2); // Rounded to 2 decimal places
                
                $round_amount = $finalamount - $roundfinalamount;
                
                $datas['Order_transaction']=array(
                    'reference_id'=>$table_referenceid,
                    'device_id'=>$device_id,
                    'cashier_id'=>$cashierid,
                    'store_id'=>$location_id,
                    'price'=>round($orderss[0][0]['total_price']-$updated_discount,2),
                    'total_tax'=>round($orderss[0][0]['total_tax']-$updated_tax,2),
                    'discount'=>round($orderss[0][0]['discount'],2),
                    'amount'=>$finalamount,
                    'round'=>round($round_amount,2),
                    'name'=>$name,
                    'phone'=>$phone,
                    'address'=>$address,
                    'tokenno'=>$token,
                    'table_number'=>$table_number,
                    'pax'=>$pax,
                    'waiter_id'=>$waiter_id,
                    'waiter_name'=>$waiter_name,
                    'is_takeaway' => $is_takeaway,
                    'createtime'=>$currenttime
                );
                if($this->Order_transaction->saveAll($datas['Order_transaction']))
                {
                    $this->Order_table->query("UPDATE order_tables SET status = 3 WHERE reference_id = '$table_referenceid'");
            
                    $response['status']= true;
                    $response['message']= "Bill Generated Successfully..!";
                }else{
                    $response['status']= false;
                    $response['message']= "Transaction Data not saved Error:103";
                }
            }
        
        return json_encode($response);
    }
    
    public function ordercomputewithpackagediscount($txnid=null,$user_id=null,$product_id=0,$discount=0)
    {
        $response['status']=false;
        $totalservicechg=0;
        $totalprice=0;
        $totaltax1=0;
        $totaltax2=0;
        $totaldiscount=0;
        $sc=0;
        $is_sc=0;
        if($is_sc==1){
            $sc=servicecharge;
        }
        $discq="(((Order_orderhistory.total_price)-(Order_orderhistory.discount))*$discount/100)";
        $priceq="((Order_orderhistory.total_price)-(Order_orderhistory.discount))";
        
        $this->Order_orderhistory->virtualFields = array('tdisc'=>"SUM($discq)",'tservicechg'=>"SUM(($priceq-$discq)*($sc/100))",'tprice'=>"SUM($priceq)",'total_tax'=>"SUM(($priceq+(($priceq-$discq)*($sc/100))-$discq)*((Order_orderhistory.total_tax_percentage)/100))");  
        $orderhistories=$this->Order_orderhistory->find('first',array('conditions'=>array('Order_orderhistory.reference_id'=>$txnid,'Order_orderhistory.product_id'=>$product_id,'status !=' =>0),'fields'=>array('product_id','tdisc','Order_orderhistory.reference_id','tprice','total_tax','tservicechg')));
        if(!empty($orderhistories['Order_orderhistory']['reference_id'])){
            $response['status']=true;
            $totalservicechg=round($orderhistories['Order_orderhistory']['tservicechg'],2);
            $totalprice=round($orderhistories['Order_orderhistory']['tprice'],2);
            $totaltax=round($orderhistories['Order_orderhistory']['total_tax'],2);
            $totaldiscount=round($orderhistories['Order_orderhistory']['tdisc'],2);
            
            //tax update
            $discq="(((Order_orderhistory.price)-(Order_orderhistory.discount))*$discount/100)";
            $priceq="((Order_orderhistory.price)-(Order_orderhistory.discount))";
            
            $taxes=[];
            
            $this->Order_orderhistory->virtualFields = array('tamount'=>"($priceq+(($priceq-$discq)*($sc/100))-$discq)");  
            $neworderhistories=$this->Order_orderhistory->find('all',array('conditions'=>array('Order_orderhistory.reference_id'=>$txnid,'Order_orderhistory.product_id'=>$product_id,'Order_orderhistory.cashier_id'=>$user_id,'status !=' =>0),'fields'=>array('Order_orderhistory.reference_id','tamount','product_id','price')));
            foreach($neworderhistories as $data){
                $reference_id=$data['Order_orderhistory']['reference_id'];
                $product_id=$data['Order_orderhistory']['product_id'];
                $tamount=$data['Order_orderhistory']['tamount'];
                $price=$data['Order_orderhistory']['price'];
                
                $taxitem=$this->Order_tax->find('all',array('conditions'=>array('Order_tax.reference_id'=>$txnid,'Order_tax.product_id'=>$product_id,'status'=>1)));
                foreach($taxitem as $item){
                    $id=$item['Order_tax']['id'];
                    $tax_id=$item['Order_tax']['tax_id'];
                    $tax_percentage=$item['Order_tax']['tax_percentage'];
                    $quantity=$item['Order_tax']['quantity'];
                    $taxamount=round($tamount*$quantity,2);
                    $taxvalue=round((($tamount*$quantity*$tax_percentage)/100),2);
                    $this->Order_tax->query("UPDATE order_tax SET taxable_price = '$taxamount',tax_value='$taxvalue',discount_percentage='$discount' WHERE id = '$id'");
                }
            }
            
            $response['totalservicechg']=$totalservicechg;
            $response['totalprice']=$totalprice;
            $response['totaltax']=$totaltax;
            $response['totaldiscount']=$totaldiscount;
        }
        // print_r($response);exit;
        return $response;
    }
    
    
    public function orderpaymentsave_table()
    {
        $response['status']= false;
        $response['message']= "fail";
        
        $cashierid = $_REQUEST['id'];
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id is Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }else{
            if (isset($_REQUEST['data'])) {
                $data = $_REQUEST['data'];
            } else {
                $response =array(
                    'status'=> false,
                    'message'=> "data not found",
                );
                return json_encode($response);
            }
            
            $data = json_decode($data, true);
            
            $reference_id=$data['reference_id'];
            $device_id=$data['device_id'];
            
            //payment save
            
            $transactions = $this->Order_transaction->find('first', array('conditions'=>array('Order_transaction.reference_id'=>$reference_id,'Order_transaction.status'=>1)));
            if(empty($transactions))
            {
                $response =array(
                    'status'=> false,
                    'message'=> "Transaction not found",
                );
                return json_encode($response);
            }else{
                $store_id=$transactions['Order_transaction']['store_id'];
                
                foreach($data['payment'] as $payment){
            
                    $datas['Order_payment']=array(
                        'reference_id'=>$reference_id,
                        'store_id'=>$store_id,
                        'device_id'=>$device_id,
                        'cashier_id'=>$cashierid,
                        'type'=>$payment['type'],
                        'type_value'=>$payment['type_value'],
                        'amount'=>$payment['amount'],
                        'remarks'=>$payment['remarks']
                    );
                    if($this->Order_payment->saveAll($datas['Order_payment']))
                    {
                        $finalpayment=0;
                        $finalamount=0;
                        $allpayments=$this->Order_payment->query("SELECT sum(amount) as pay_amount FROM `order_payments` WHERE reference_id='$reference_id'");
                        if($allpayments){
                            $finalpayment=$allpayments[0][0]['pay_amount'];
                        }
                        if($transactions){
                            $finalamount=$transactions['Order_transaction']['amount'];
                        }
                        $amount_diff=$finalamount-$finalpayment;
                        if($amount_diff<1){
                            
                            $this->Order_orderhistory->query("UPDATE order_orderhistories SET status = 2 WHERE reference_id = '$reference_id' and status = 1");
                            $this->Order_transaction->query("UPDATE order_transactions SET status = 2,payment_mode='$type_value' WHERE reference_id = '$reference_id'");
                            $this->Order_payment->query("UPDATE order_payments SET status = 2 WHERE reference_id = '$reference_id'");
                            $this->Order_tax->query("UPDATE order_tax SET status = 2 WHERE reference_id = '$reference_id' and status != 0");
                            
                            do {
                                $pin = 'TX' . $cashierid . date('Y') . uniqid();
                                // $pin = uniqid();
                            } while ($this->Order_table->find('first', array('fields' => 'Order_table.id', 'conditions' => array('Order_table.reference_id' => $pin))));
                            
                            $tablestatus = $this->Order_table->find('first', array('conditions'=>array('reference_id'=>$reference_id,'is_takeaway'=>1)));
                            if(!empty($tablestatus))
                            {   
                                $this->Order_table->query("DELETE FROM order_tables  WHERE reference_id = '$reference_id'");
                            }else{
                                $this->Order_table->query("UPDATE order_tables SET status = 1,reference_id='$pin',is_alert=0 WHERE reference_id = '$reference_id'");
                            }

                            
                            $stockupdate=$this->stock_update($reference_id);
                            if(!$stockupdate){
                                $response['status']= true;
                                $response['message']= "Payment Data Saved Successfully..! But stock not updated";
                                $response['full_payment']= true; 
                            }
                            $response['status']= true;
                            $response['message']= "Payment Data Saved Successfully..!";
                            $response['full_payment']= true;
                        }else{
                            $response['status']= true;
                            $response['message']= "Payment Data Saved Successfully..!";
                            $response['full_payment']= false;
                        }
                    }else{
                        $response['status']= false;
                        $response['message']= "Payment Data not saved Error:102";
                        $response['full_payment']= false;
                    }
                }
            }
        }
        return json_encode($response);
    }
    
    public function swap_table()
    {
        $response['status']= false;
        $response['message']= "fail";
        
        $cashierid = $_REQUEST['id'];
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id is Missing",
            );
            return json_encode($response);
        }
        $from_table = $_REQUEST['from_reference_id'];
        if($from_table==''){
            $response =array(
                'status'=> false,
                'message'=> "From Reference id is Missing",
            );
            return json_encode($response);
        }
        
        $to_table = $_REQUEST['to_reference_id'];
        if($from_table==''){
            $response =array(
                'status'=> false,
                'message'=> "To Reference id is Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $chktransaction=$this->Order_table->find('first',array('conditions'=>array('Order_table.status'=>2,'Order_table.reference_id'=>$from_table)));
        //print_r($chktransaction);exit;
        
        if(empty($chktransaction)){
            $response['message']= "Option not available for source table!";
            return json_encode($response);
        }
        
        $chktable=$this->Order_table->find('first',array('conditions'=>array('Order_table.status'=>1,'Order_table.reference_id'=>$to_table)));
        if(empty($chktable)){
            $response['message']= "Option not available for Destination table!";
            return json_encode($response);
        }
        
        do {
            // $pin = uniqid();
            $pin = 'TX' . $cashierid . date('Y') . uniqid();
        } while ($this->Order_table->find('first', array('fields' => 'Order_table.id', 'conditions' => array('Order_table.reference_id' => $pin))));
        $this->Order_table->query("UPDATE order_tables SET status = 1,reference_id='$pin' WHERE reference_id = '$from_table'");
        
        $this->Order_table->query("UPDATE order_tables SET status = 2,reference_id='$from_table' WHERE reference_id = '$to_table'");

        $response['status']= true;
        $response['message']= "Swap Successfully..!";

        return json_encode($response);
    }
    /*
    public function remove_item()
    {
        // $response['status']= false;
        // $response['message']= "fail";
        $response['status']= false;
        $response['message']= "fail";
        
        
        $cashierid = $_REQUEST['id'];
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id is Missing",
            );
            return json_encode($response);
        }
        
        $order_id = $_REQUEST['order_id'];
        if($order_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Order id is Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $chktransaction=$this->Order_orderhistory->find('first',array('conditions'=>array('Order_orderhistory.status'=>1,'Order_orderhistory.id'=>$order_id)));
        
        if(empty($chktransaction)){
            $response['message']= "Order Item not found";
            return json_encode($response);
        }
        $reference_id=$chktransaction['Order_orderhistory']['reference_id'];
        $product_id=$chktransaction['Order_orderhistory']['product_id'];
        $quantity=$chktransaction['Order_orderhistory']['quantity'];
        
        // $this->Order_orderhistory->query("UPDATE order_orderhistories SET status = 0 WHERE id = '$order_id'");
        // $this->Order_tax->query("UPDATE order_tax SET status = 0 WHERE reference_id = '$reference_id' AND orderhistory_id = '$order_id'");
        
        // Soft delete order history
        $this->Order_orderhistory->updateAll(
            ['Order_orderhistory.status' => 0],
            ['Order_orderhistory.id' => $order_id]
        );
    
        // Soft delete related taxes
        $this->Order_tax->updateAll(
            ['status' => 0],
            ['orderhistory_id' => $order_id]
        );

        $response['status']= true;
        $response['message']= "Item Removed Successfully..!";

        return json_encode($response);
    }
    
    public function quantity_increase()
    {
        $response['status']= false;
        $response['message']= "fail";
        
        $cashierid = $_REQUEST['id'];
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id is Missing",
            );
            return json_encode($response);
        }
        
        $order_id = $_REQUEST['order_id'];
        if($order_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Order id is Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $orderss = $this->Order_orderhistory->find('first', array('conditions'=>array('id'=>$order_id)));
        if(!empty($orderss))
        {
            $newquantity=$orderss['Order_orderhistory']['quantity']+1;
            $price_value=$newquantity*$orderss['Order_orderhistory']['price'];
            $total_tax_percentage=$orderss['Order_orderhistory']['total_tax_percentage'];
            $total_tax=round(((($price_value-$orderss['Order_orderhistory']['discount'])*$total_tax_percentage)/100),2);
            
            $total_price=round($price_value,2);
            
            $this->Order_orderhistory->query("UPDATE order_orderhistories SET quantity=$newquantity,total_price=$total_price,total_tax=$total_tax WHERE id = '$order_id'");
            
            $reference_id=$orderss['Order_orderhistory']['reference_id'];
            $product_id=$orderss['Order_orderhistory']['product_id'];
            $tamount=$total_price;
            $price=$orderss['Order_orderhistory']['price'];
            $taxitem=$this->Order_tax->find('all',array('conditions'=>array('Order_tax.orderhistory_id'=>$order_id,'Order_tax.reference_id'=>$reference_id,'Order_tax.product_id'=>$product_id)));
            foreach($taxitem as $item){
                $id=$item['Order_tax']['id'];
                $tax_percentage=$item['Order_tax']['tax_percentage'];
                $quantity=$item['Order_tax']['quantity']+1;
                $taxamount=round($price*$quantity,2);
                $taxvalue=round((($price*$quantity*$tax_percentage)/100),2);
                
                $this->Order_tax->query("UPDATE order_tax SET quantity=$quantity,taxable_price = '$taxamount',tax_value='$taxvalue' WHERE id = '$id'");
            }
            
            $response['status']= true;
            $response['message']= "Quantity Increased Successfully..!";

        
        }else{
            $response['status']= false;
            $response['message']= "Order item not found..!";

        }
        
        
        return json_encode($response);
    }
    
    public function quantity_decrease()
    {
        $response['status']= false;
        $response['message']= "fail";
        
        $cashierid = $_REQUEST['id'];
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id is Missing",
            );
            return json_encode($response);
        }
        
        $order_id = $_REQUEST['order_id'];
        if($order_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Order id is Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $orderss = $this->Order_orderhistory->find('first', array('conditions'=>array('id'=>$order_id,'quantity >'=>1)));
        if(!empty($orderss))
        {
            $newquantity=$orderss['Order_orderhistory']['quantity']-1;
            $price_value=$newquantity*$orderss['Order_orderhistory']['price'];
            $total_tax_percentage=$orderss['Order_orderhistory']['total_tax_percentage'];
            $total_tax=round(((($price_value-$orderss['Order_orderhistory']['discount'])*$total_tax_percentage)/100),2);
            
            $total_price=round($price_value,2);
            
            $this->Order_orderhistory->query("UPDATE order_orderhistories SET quantity=$newquantity,total_price=$total_price,total_tax=$total_tax WHERE id = '$order_id'");
            
            $reference_id=$orderss['Order_orderhistory']['reference_id'];
            $product_id=$orderss['Order_orderhistory']['product_id'];
            $tamount=$total_price;
            $price=$orderss['Order_orderhistory']['price'];
            $taxitem=$this->Order_tax->find('all',array('conditions'=>array('Order_tax.orderhistory_id'=>$order_id,'Order_tax.reference_id'=>$reference_id,'Order_tax.product_id'=>$product_id)));
            foreach($taxitem as $item){
                $id=$item['Order_tax']['id'];
                $tax_percentage=$item['Order_tax']['tax_percentage'];
                $quantity=$item['Order_tax']['quantity']-1;
                $taxamount=round($price*$quantity,2);
                $taxvalue=round((($price*$quantity*$tax_percentage)/100),2);
                
                $this->Order_tax->query("UPDATE order_tax SET quantity=$quantity,taxable_price = '$taxamount',tax_value='$taxvalue' WHERE id = '$id'");
            }
            
            
            $response['status']= true;
            $response['message']= "Quantity Decreased Successfully..!";

        
        }else{
            $response['status']= false;
            $response['message']= "Quantity must be greater then 1 or Order item not found..!";

        }
        
        
        return json_encode($response);
    }
    */
    public function remove_item()
    {
        // $response['status']= false;
        // $response['message']= "fail";
        $response['status']= false;
        $response['message']= "fail";
        
        
        $cashierid = $_REQUEST['id'];
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id is Missing",
            );
            return json_encode($response);
        }
        
        $order_id = $_REQUEST['order_id'];
        if($order_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Order id is Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $chktransaction=$this->Order_orderhistory->find('first',array('conditions'=>array('Order_orderhistory.status'=>1,'Order_orderhistory.id'=>$order_id)));
        
        if(empty($chktransaction)){
            $response['message']= "Order Item not found";
            return json_encode($response);
        }
        $reference_id=$chktransaction['Order_orderhistory']['reference_id'];
        $product_id=$chktransaction['Order_orderhistory']['product_id'];
        $quantity=$chktransaction['Order_orderhistory']['quantity'];
        
        // $this->Order_orderhistory->query("UPDATE order_orderhistories SET status = 0 WHERE id = '$order_id'");
        // $this->Order_tax->query("UPDATE order_tax SET status = 0 WHERE reference_id = '$reference_id' AND orderhistory_id = '$order_id'");
        
        // Soft delete order history
        $this->Order_orderhistory->updateAll(
            ['Order_orderhistory.status' => 0],
            ['Order_orderhistory.id' => $order_id]
        );
    
        // Soft delete related taxes
        $this->Order_tax->updateAll(
            ['status' => 0],
            ['orderhistory_id' => $order_id]
        );

        $this->Order_modifier->updateAll(
            ['status' => 0],
            ['orderhistory_id' => $order_id]
        );
        
        $response['status']= true;
        $response['message']= "Item Removed Successfully..!";

        return json_encode($response);
    }
    
    public function quantity_increase()
    {
        $response['status']= false;
        $response['message']= "fail";
        
        $cashierid = $_REQUEST['id'];
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id is Missing",
            );
            return json_encode($response);
        }
        
        $order_id = $_REQUEST['order_id'];
        if($order_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Order id is Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $orderss = $this->Order_orderhistory->find('first', array('conditions'=>array('id'=>$order_id)));
        if(!empty($orderss))
        {
            $newquantity=$orderss['Order_orderhistory']['quantity']+1;
            $price_value=$newquantity*$orderss['Order_orderhistory']['price'];
            $total_tax_percentage=$orderss['Order_orderhistory']['total_tax_percentage'];
            $total_tax=round(((($price_value-$orderss['Order_orderhistory']['discount'])*$total_tax_percentage)/100),2);
            
            $total_price=round($price_value,2);
            
            $this->Order_orderhistory->query("UPDATE order_orderhistories SET quantity=$newquantity,total_price=$total_price,total_tax=$total_tax WHERE id = '$order_id'");
            $this->Order_modifier->query("UPDATE order_modifier SET quantity=$newquantity WHERE orderhistory_id = '$order_id'");
            
            $reference_id=$orderss['Order_orderhistory']['reference_id'];
            $product_id=$orderss['Order_orderhistory']['product_id'];
            $tamount=$total_price;
            $price=$orderss['Order_orderhistory']['price'];
            $taxitem=$this->Order_tax->find('all',array('conditions'=>array('Order_tax.orderhistory_id'=>$order_id,'Order_tax.reference_id'=>$reference_id,'Order_tax.product_id'=>$product_id)));
            foreach($taxitem as $item){
                $id=$item['Order_tax']['id'];
                $tax_percentage=$item['Order_tax']['tax_percentage'];
                $quantity=$item['Order_tax']['quantity']+1;
                $taxamount=round($price*$quantity,2);
                $taxvalue=round((($price*$quantity*$tax_percentage)/100),2);
                
                $this->Order_tax->query("UPDATE order_tax SET quantity=$quantity,taxable_price = '$taxamount',tax_value='$taxvalue' WHERE id = '$id'");
            }
            
            
            $response['status']= true;
            $response['message']= "Quantity Increased Successfully..!";

        
        }else{
            $response['status']= false;
            $response['message']= "Order item not found..!";

        }
        
        
        return json_encode($response);
    }
    
    public function quantity_decrease()
    {
        $response['status']= false;
        $response['message']= "fail";
        
        $cashierid = $_REQUEST['id'];
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id is Missing",
            );
            return json_encode($response);
        }
        
        $order_id = $_REQUEST['order_id'];
        if($order_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Order id is Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $orderss = $this->Order_orderhistory->find('first', array('conditions'=>array('id'=>$order_id,'quantity >'=>1)));
        if(!empty($orderss))
        {
            $newquantity=$orderss['Order_orderhistory']['quantity']-1;
            $price_value=$newquantity*$orderss['Order_orderhistory']['price'];
            $total_tax_percentage=$orderss['Order_orderhistory']['total_tax_percentage'];
            $total_tax=round(((($price_value-$orderss['Order_orderhistory']['discount'])*$total_tax_percentage)/100),2);
            
            $total_price=round($price_value,2);
            
            $this->Order_orderhistory->query("UPDATE order_orderhistories SET quantity=$newquantity,total_price=$total_price,total_tax=$total_tax WHERE id = '$order_id'");
            $this->Order_modifier->query("UPDATE order_modifier SET quantity=$newquantity WHERE orderhistory_id = '$order_id'");
            
            $reference_id=$orderss['Order_orderhistory']['reference_id'];
            $product_id=$orderss['Order_orderhistory']['product_id'];
            $tamount=$total_price;
            $price=$orderss['Order_orderhistory']['price'];
            $taxitem=$this->Order_tax->find('all',array('conditions'=>array('Order_tax.orderhistory_id'=>$order_id,'Order_tax.reference_id'=>$reference_id,'Order_tax.product_id'=>$product_id)));
            foreach($taxitem as $item){
                $id=$item['Order_tax']['id'];
                $tax_percentage=$item['Order_tax']['tax_percentage'];
                $quantity=$item['Order_tax']['quantity']-1;
                $taxamount=round($price*$quantity,2);
                $taxvalue=round((($price*$quantity*$tax_percentage)/100),2);
                
                $this->Order_tax->query("UPDATE order_tax SET quantity=$quantity,taxable_price = '$taxamount',tax_value='$taxvalue' WHERE id = '$id'");
            }
            
            
            $response['status']= true;
            $response['message']= "Quantity Decreased Successfully..!";

        
        }else{
            $response['status']= false;
            $response['message']= "Quantity must be greater then 1 or Order item not found..!";

        }
        
        
        return json_encode($response);
    }
    public function data_report()
    {
        $cashierid = $_REQUEST['id'];
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "User Id Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $todayDate = date("Y-m-d");
$today = new DateTime();
$today->modify('-7 days');
$prevdate = $today->format('Y-m-d');

// Generate all dates between $prevdate and $todayDate
$dateRange = [];
$currentDate = new DateTime($prevdate);
$endDate = new DateTime($todayDate);
while ($currentDate <= $endDate) {
    $dateRange[] = $currentDate->format('Y-m-d');
    $currentDate->modify('+1 day');
}

// Initialize the array with all dates and default values
$transactionitems = [];
foreach ($dateRange as $date) {
    $transactionitems[$date] = [
        'total_price' => 0,
        'total_tax' => 0,
        'total_amount' => 0,
        'cash' => 0,
        'online' => 0,
        'card' => 0,
        'storecard' => 0,
        'transaction_date' => $date
    ];
}
$shiftstart=shiftstart;
$shiftend=shiftend;
$todayDate = new DateTime($todayDate);
$todayDate = $todayDate->modify('+1 day')->format('Y-m-d');
// Query to get transactions and payments
$transactions = $this->Order_transaction->query("
    SELECT t.txn_date, t.total_price, t.total_tax, t.total_amount, p.cash, p.online, p.card, p.storecard
    FROM (
        SELECT SUM(price) AS total_price, SUM(total_tax) AS total_tax, SUM(amount) AS total_amount, DATE(created) AS txn_date
        FROM order_transactions
        WHERE created BETWEEN '$prevdate $shiftstart' AND '$todayDate $shiftend'
        AND cashier_id = $cashierid
        AND status = 2
        GROUP BY DATE(created)
    ) t
    LEFT JOIN (
        SELECT SUM(IF(type = 1, amount, 0)) AS cash, SUM(IF(type = 2, amount, 0)) AS card, SUM(IF(type = 6, amount, 0)) AS online, SUM(IF(type = 8, amount, 0)) AS storecard, DATE(created) AS paydate
        FROM order_payments
        WHERE created BETWEEN '$prevdate $shiftstart' AND '$todayDate $shiftend'
        AND cashier_id = $cashierid
        GROUP BY DATE(created)
    ) p ON t.txn_date = p.paydate
");

// Populate the results into the array
if (!empty($transactions)) {
    foreach ($transactions as $transaction) {
        $txn_date = $transaction['t']['txn_date'];
        if (isset($transactionitems[$txn_date])) {
            $transactionitems[$txn_date] = [
                'total_price' => $transaction['t']['total_price'],
                'total_tax' => $transaction['t']['total_tax'],
                'total_amount' => $transaction['t']['total_amount'],
                'cash' => $transaction['p']['cash'],
                'online' => $transaction['p']['online'],
                'card' => $transaction['p']['card'],
                'storecard' => $transaction['p']['storecard'],
                'transaction_date' => $txn_date
            ];
        }
    }
}

// Convert back to an indexed array if necessary
$transactionitems = array_values($transactionitems);

        $response= array('status'=> true,
                'message'=> "success",
                'transactions'=>$transactionitems
            );
        return json_encode($response);
    }
    
    public function data_report_export()
    {
        $cashierid = $_REQUEST['id'];
        $sdate = $_REQUEST['sdate'];
        $edate = $_REQUEST['edate'];
        $type = $_REQUEST['type'];
        
        $response = array();
        // if($cashierid==''){
        //     $response =array(
        //         'status'=> false,
        //         'message'=> "User Id Missing",
        //     );
        //     return json_encode($response);
        // }
        
        // $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        // if(empty($users))
        // {
        //     $response =array(
        //         'status'=> false,
        //         'message'=> "User not found",
        //     );
        //     return json_encode($response);
        // }
        
        

        $response= array('status'=> true,
                'message'=> "success",
                'export'=>'https://phylopos.in/Theparkhotel/erp/app/webroot/uploads/reports/type1.csv'
            );
        return json_encode($response);
    }
    
    public function table_clear()
    {
        $cashierid = $_REQUEST['id'];
        $ref_id = $_REQUEST['reference_id'];
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "User Id Missing",
            );
            return json_encode($response);
        }
        
        if($ref_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Reference id Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $tables=$this->Order_table->find('first',array('conditions'=>array('Order_table.reference_id'=>$ref_id,'Order_table.status'=>2)));
//      print_r($tables);exit;;
        if(empty($tables))
        {   
            $response= array('status'=> false,
                'message'=> "Table not found"
            );
            return json_encode($response);
        }
        
        $checkref=$this->Order_orderhistory->find('first',array('conditions'=>array('Order_orderhistory.reference_id'=>$ref_id,'status !='=>0)));
        if(!empty($checkref))
        {   
            $response= array('status'=> false,
                'message'=> "Please clear the item first"
            );
            return json_encode($response);
        }
        
        $tablestatus = $this->Order_table->find('first', array('conditions'=>array('reference_id'=>$ref_id,'is_takeaway'=>1)));
        if(!empty($tablestatus))
        {   
            $this->Order_table->query("DELETE FROM order_tables  WHERE reference_id = '$ref_id'");
        }else{
            $this->Order_table->query("update order_tables set status=1 where reference_id='$ref_id'");
        }
        
        $response= array('status'=> true,
            'message'=> "Table Cleared"
        );
        return json_encode($response);
    }
    
    public function table_unbill()
    {
        $cashierid = $_REQUEST['id'];
        $ref_id = $_REQUEST['reference_id'];
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "User Id Missing",
            );
            return json_encode($response);
        }
        
        if($ref_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Reference id Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $txnchk = $this->Order_transaction->find('first', array('conditions'=>array('Order_transaction.reference_id'=>$ref_id)));
        if(!empty($txnchk))
        {
            $tableid=$txnchk['Order_transaction']['table_number'];
            
            $tables=$this->Order_table->find('first',array('conditions'=>array('Order_table.number'=>$tableid,'Order_table.reference_id'=>$ref_id)));
//          print_r($tables);exit;;
            
            $orderdata=$this->ordercompute($ref_id,$cashierid,0,0);
            
            $this->Order_transaction->id=$txnchk['Order_transaction']['id'];
            if($this->Order_transaction->delete()){
                if($tables){
                 //   print_r($tables);exit;
                    $this->Order_table->id=$tables['Order_table']['id'];
                    $this->Order_table->saveField('status','2');
                }
                $response= array('status'=> true,
                    'message'=> "Bill updated"
                );
                return json_encode($response);
            }else{
                $response= array('status'=> false,
                    'message'=> "Bill not updated"
                );
                return json_encode($response);  
            }
            
        }else{
            $response= array('status'=> false,
                'message'=> "No Transaction found"
            );
            return json_encode($response);
        }
        
        
    }
    
    public function table_billupdate_discount()
    {
        $cashierid = $_REQUEST['id'];
        $ref_id = $_REQUEST['reference_id'];
        $disc=$_REQUEST['discount'];
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "User Id Missing",
            );
            return json_encode($response);
        }
        
        if($ref_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Reference id Missing",
            );
            return json_encode($response);
        }
        
        if($disc==''){
            $response =array(
                'status'=> false,
                'message'=> "Discount Missing",
            );
            return json_encode($response);
        }
        if($disc>99){
            $response =array(
                'status'=> false,
                'message'=> "Discount is not more than 99%",
            );
            return json_encode($response);
        }
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        if($disc>=0){
            $checkdiscount=$this->Order_orderhistory->find('first',array('conditions'=>array('Order_orderhistory.discount > '=>0,'Order_orderhistory.status'=>2,'Order_orderhistory.reference_id'=>$ref_id)));
            if(!empty($checkdiscount)){
                $response['status']= false;
                $response['message']= "Discount can not merge with item level discount";
                return json_encode($response);     
            }
        }else{
            $response['status']= false;
            $response['message']= "please check discount value";
            return json_encode($response);  
        }
        
        $tables=$this->Order_table->find('first',array('conditions'=>array('Order_table.reference_id'=>$ref_id,'Order_table.status'=>3)));
        if(empty($tables)){
            $response['status']= false;
            $response['message']= "Table is not in billing state";
            return json_encode($response);
        }
        
        $txnchk = $this->Order_transaction->find('first', array('conditions'=>array('Order_transaction.reference_id'=>$ref_id, 'Order_transaction.cashier_id'=>$cashierid)));
        if(empty($txnchk))
        {
            $response= array('status'=> false,
                'message'=> "No Transaction found"
            );
            return json_encode($response);
        }
        if($txnchk['Order_transaction']['servicecharge']>0){
            $sc=1;
        }else{
            $sc=0;
        }
        
        $orderdata=$this->ordercompute($ref_id,$cashierid,$sc,$disc);
        
        if($orderdata['status'])
        {
            $totalservicechg=$orderdata['totalservicechg'];
            $totalprice=$orderdata['totalprice'];
            $totaltax=$orderdata['totaltax'];
            $totaldiscount=$orderdata['totaldiscount'];
            $totalamount=round((($totalprice+$totaltax+$totalservicechg)-$totaldiscount),2);
            
            $createtime = date('H:i:s');
            $this->Order_transaction->query("UPDATE `order_transactions` SET `price` = '$totalprice',`total_tax`='$totaltax',`servicecharge`='$totalservicechg',`discount`='$totaldiscount',`discount_type`='1',`discount_type_value`='$disc',`amount`='$totalamount',`createtime`='$createtime' WHERE `order_transactions`.`reference_id` = '$ref_id'");
            
            $response =array(
                'status'=> true,
                'message'=> "Saved",
            );
            return json_encode($response);
        }else{
            $response =array(
                'status'=> false,
                'message'=> "Not Saved",
            );
            return json_encode($response);
        }
    }
    
    public function table_billupdate_servicecharge()
    {
        $cashierid = $_REQUEST['id'];
        $ref_id = $_REQUEST['reference_id'];
        $sc=$_REQUEST['service_charge'];
        
        $disc=0;
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "User Id Missing",
            );
            return json_encode($response);
        }
        
        if($ref_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Reference id Missing",
            );
            return json_encode($response);
        }
        
        if($sc==''){
            $response =array(
                'status'=> false,
                'message'=> "Service Charge Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $tables=$this->Order_table->find('first',array('conditions'=>array('Order_table.reference_id'=>$ref_id,'Order_table.status'=>3)));
        if(empty($tables)){
            $response['status']= false;
            $response['message']= "Table is not in billing state";
            return json_encode($response);
        }
        
        $txnchk = $this->Order_transaction->find('first', array('conditions'=>array('Order_transaction.reference_id'=>$ref_id, 'Order_transaction.cashier_id'=>$cashierid)));
        if(empty($txnchk))
        {
            $response= array('status'=> false,
                'message'=> "No Transaction found"
            );
            return json_encode($response);
        }
        
        $orderdata=$this->ordercompute($ref_id,$cashierid,$sc,$disc);
        
        if($orderdata['status'])
        {
            $totalservicechg=$orderdata['totalservicechg'];
            $totalprice=$orderdata['totalprice'];
            $totaltax=$orderdata['totaltax'];
            $totaldiscount=$orderdata['totaldiscount'];
            $totalamount=round((($totalprice+$totaltax+$totalservicechg)-$totaldiscount),2);
            
            $createtime = date('H:i:s');
            $this->Order_transaction->query("UPDATE `order_transactions` SET `price` = '$totalprice',`total_tax`='$totaltax',`servicecharge`='$totalservicechg',`discount`='$totaldiscount',`discount_type`='1',`discount_type_value`='$disc',`amount`='$totalamount',`createtime`='$createtime' WHERE `order_transactions`.`reference_id` = '$ref_id'");
            
            $response =array(
                'status'=> true,
                'message'=> "Saved",
            );
            return json_encode($response);
        }else{
            $response =array(
                'status'=> false,
                'message'=> "Not Saved",
            );
            return json_encode($response);
        }
    }
    
    public function table_billupdate_coupon()
    {
        $cashierid = $_REQUEST['id'];
        $ref_id = $_REQUEST['reference_id'];
        $coupon=$_REQUEST['coupon'];
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "User Id Missing",
            );
            return json_encode($response);
        }
        
        if($ref_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Reference id Missing",
            );
            return json_encode($response);
        }
        
        if($coupon==''){
            $response =array(
                'status'=> false,
                'message'=> "Coupon Code Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $todayDate = date("Y-m-d");
        $coup = $this->Coupon->find('first', array('conditions'=>array('Coupon.code'=>$coupon,'Coupon.expiry_date >='=>$todayDate,'Coupon.status'=>1)));
        if(empty($coup))
        {
            $response =array(
                'status'=> false,
                'message'=> "Coupon not found Or Coupon Expired",
            );
            return json_encode($response);
        }
        $coup_value=$coup['Coupon']['value'];
        
        $tables=$this->Order_table->find('first',array('conditions'=>array('Order_table.reference_id'=>$ref_id,'Order_table.status'=>3)));
        if(empty($tables)){
            $response['status']= false;
            $response['message']= "Table is not in billing state";
            return json_encode($response);
        }
        
        $txnchk = $this->Order_transaction->find('first', array('conditions'=>array('Order_transaction.reference_id'=>$ref_id, 'Order_transaction.cashier_id'=>$cashierid)));
        if(empty($txnchk))
        {
            $response= array('status'=> false,
                'message'=> "No Transaction found"
            );
            return json_encode($response);
        }
        if($txnchk['Order_transaction']['servicecharge']>0){
            $sc=1;
        }else{
            $sc=0;
        }
        
        $disc=$coup_value;
        
        $orderdata=$this->ordercompute($ref_id,$cashierid,$sc,$disc);
//      print_r($ref_id.'<br>'.$cashierid.'<br>'.$sc.'<br>'.$disc);exit;
        if($orderdata['status'])
        {
            $totalservicechg=$orderdata['totalservicechg'];
            $totalprice=$orderdata['totalprice'];
            $totaltax=$orderdata['totaltax'];
            $totaldiscount=$orderdata['totaldiscount'];
            $totalamount=round((($totalprice+$totaltax+$totalservicechg)-$totaldiscount),2);
            
            $createtime = date('H:i:s');
            $this->Order_transaction->query("UPDATE `order_transactions` SET `price` = '$totalprice',`total_tax`='$totaltax',`servicecharge`='$totalservicechg',`discount`='$totaldiscount',`discount_type`='0',`discount_type_value`='$coupon',`amount`='$totalamount',`createtime`='$createtime' WHERE `order_transactions`.`reference_id` = '$ref_id'");
            
            $response =array(
                'status'=> true,
                'message'=> "Saved",
            );
            return json_encode($response);
        }else{
            $response =array(
                'status'=> false,
                'message'=> "Not Saved",
            );
            return json_encode($response);
        }
    }
        
    public function table_bill_coupon_removed()
    {
        $cashierid = $_REQUEST['id'];
        $ref_id = $_REQUEST['reference_id'];
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "User Id Missing",
            );
            return json_encode($response);
        }
        
        if($ref_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Reference id Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $todayDate = date("Y-m-d");
        $coup_value=0;
        
        $tables=$this->Order_table->find('first',array('conditions'=>array('Order_table.reference_id'=>$ref_id,'Order_table.status'=>3)));
        if(empty($tables)){
            $response['status']= false;
            $response['message']= "Table is not in billing state";
            return json_encode($response);
        }
        
        $txnchk = $this->Order_transaction->find('first', array('conditions'=>array('Order_transaction.reference_id'=>$ref_id, 'Order_transaction.cashier_id'=>$cashierid)));
        if(empty($txnchk))
        {
            $response= array('status'=> false,
                'message'=> "No Transaction found"
            );
            return json_encode($response);
        }
        if($txnchk['Order_transaction']['servicecharge']>0){
            $sc=1;
        }else{
            $sc=0;
        }
        
        $disc=$coup_value;
        
        $orderdata=$this->ordercompute($ref_id,$cashierid,$sc,$disc);
        
        if($orderdata['status'])
        {
            $totalservicechg=$orderdata['totalservicechg'];
            $totalprice=$orderdata['totalprice'];
            $totaltax=$orderdata['totaltax'];
            $totaldiscount=$orderdata['totaldiscount'];
            $totalamount=round((($totalprice+$totaltax+$totalservicechg)-$totaldiscount),2);
            
            $createtime = date('H:i:s');
            $this->Order_transaction->query("UPDATE `order_transactions` SET `price` = '$totalprice',`total_tax`='$totaltax',`servicecharge`='$totalservicechg',`discount`='$totaldiscount',`amount`='$totalamount',`createtime`='$createtime' WHERE `order_transactions`.`reference_id` = '$ref_id'");
            
            $response =array(
                'status'=> true,
                'message'=> "Removed",
            );
            return json_encode($response);
        }else{
            $response =array(
                'status'=> false,
                'message'=> "Not Removed",
            );
            return json_encode($response);
        }
    }
    
    public function ordercompute($txnid=null,$user_id=null,$is_sc=1,$discount=0){
        $response['status']=false;
        $totalservicechg=0;
        $totalprice=0;
        $totaltax1=0;
        $totaltax2=0;
        $totaldiscount=0;
        $sc=0;
        if($is_sc==1){
            $sc=servicecharge;
        }
        $discq="(((Order_orderhistory.total_price)-(Order_orderhistory.discount))*$discount/100)";
        $priceq="((Order_orderhistory.total_price)-(Order_orderhistory.discount))";
    
        $this->Order_orderhistory->virtualFields = array('tdisc'=>"SUM($discq)",'tservicechg'=>"SUM(($priceq-$discq)*($sc/100))",'tprice'=>"SUM($priceq)",'total_tax'=>"SUM(($priceq+(($priceq-$discq)*($sc/100))-$discq)*((Order_orderhistory.total_tax_percentage)/100))");  
        
        $orderhistories=$this->Order_orderhistory->find('first',array('conditions'=>array('Order_orderhistory.reference_id'=>$txnid,'status !=' =>0),'fields'=>array('tdisc','Order_orderhistory.reference_id','tprice','total_tax','tservicechg')));
    //  print_r($orderhistories);exit;
        
        if(!empty($orderhistories['Order_orderhistory']['reference_id'])){
            $response['status']=true;
            $totalservicechg=round($orderhistories['Order_orderhistory']['tservicechg'],2);
            $totalprice=round($orderhistories['Order_orderhistory']['tprice'],2);
            $totaltax=round($orderhistories['Order_orderhistory']['total_tax'],2);
            $totaldiscount=round($orderhistories['Order_orderhistory']['tdisc'],2);
            
            //tax update
            $discq="(((Order_orderhistory.price)-(Order_orderhistory.discount))*$discount/100)";
            $priceq="((Order_orderhistory.price)-(Order_orderhistory.discount))";
            
            $this->Order_orderhistory->virtualFields = array('tamount'=>"($priceq+(($priceq-$discq)*($sc/100))-$discq)");  
            $neworderhistories=$this->Order_orderhistory->find('all',array('conditions'=>array('Order_orderhistory.reference_id'=>$txnid),'fields'=>array('Order_orderhistory.reference_id','tamount','product_id','price')));
            foreach($neworderhistories as $data){
                $reference_id=$data['Order_orderhistory']['reference_id'];
                $product_id=$data['Order_orderhistory']['product_id'];
                $tamount=$data['Order_orderhistory']['tamount'];
                $price=$data['Order_orderhistory']['price'];
                
                $taxitem=$this->Order_tax->find('all',array('conditions'=>array('Order_tax.reference_id'=>$txnid,'Order_tax.product_id'=>$product_id)));
                foreach($taxitem as $item){
                    $id=$item['Order_tax']['id'];
                    $tax_percentage=$item['Order_tax']['tax_percentage'];
                    $quantity=$item['Order_tax']['quantity'];
                    $taxamount=round($tamount*$quantity,2);
                    $taxvalue=round((($tamount*$quantity*$tax_percentage)/100),2);
                    $this->Order_tax->query("UPDATE order_tax SET taxable_price = '$taxamount',tax_value='$taxvalue',discount_percentage='$discount' WHERE id = '$id'");
                }
            }
            
            $response['totalservicechg']=$totalservicechg;
            $response['totalprice']=$totalprice;
            $response['totaltax']=$totaltax;
            $response['totaldiscount']=$totaldiscount;
        }
        // print_r($response);exit;
        return $response;
    }

    public function dsr_report_print()
    {
        $cashier_id = $_REQUEST['id'];
        $startdate = $_REQUEST['sdate'];
        $enddate = $_REQUEST['edate'];
        
        $response = array();
        
        if($cashier_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id Missing",
            );
            return json_encode($response);
        }
        
        if($startdate==''){
            $response =array(
                'status'=> false,
                'message'=> "Start date Missing",
            );
            return json_encode($response);
        }
        
        if($enddate==''){
            $response =array(
                'status'=> false,
                'message'=> "End date Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashier_id,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $cashiernames=$this->User->find('first',array('conditions'=>array('User.id'=>$cashier_id)));
        $cashiername=$cashiernames['User']['name'];
        $shiftstart=shiftstart;
        $shiftend=shiftend;

        $enddate = new DateTime($enddate);
        $enddate = $enddate->modify('+1 day')->format('Y-m-d');
        $payments = $this->Order_payment->query("SELECT SUM(amount) as total_amount,SUM(IF(type=1,amount,0)) AS cash,SUM(IF(type=6,amount,0)) AS upi,SUM(IF(type=2,amount,0)) AS card,SUM(IF(type=9,amount,0)) AS online,SUM(IF(type=7,amount,0)) AS no_charge_with_tax,SUM(IF(type=7,round(amount-(SELECT sum(total_tax) from order_transactions WHERE reference_id=order_payments.reference_id),2),0)) AS  no_charge,SUM(IF(type=8,amount,0)) AS storecard FROM `order_payments` where status=2 and created BETWEEN '$startdate $shiftstart' and '$enddate $shiftend' and cashier_id=$cashier_id");
        $transactions = $this->Order_transaction->query("SELECT COUNT(id) as total_count,SUM(total_tax) AS total_tax,SUM(servicecharge) AS servicecharge,SUM(discount) AS discount,SUM(delivery_charge) AS delivery_charge,SUM(packing_charge) AS packing_charge,SUM(amount) AS amount,SUM(price) AS price,SUM(round) AS round FROM `order_transactions` where  created BETWEEN '$startdate $shiftstart' and '$enddate $shiftend' and cashier_id=$cashier_id and status=2 and reference_id NOT IN (SELECT reference_id from order_payments WHERE type=7 and status=2)");
        $transactionsubtotal = $this->Order_transaction->query("SELECT SUM(price) AS price ,SUM(discount) AS discount FROM `order_transactions` where  created BETWEEN '$startdate $shiftstart' and '$enddate $shiftend' and status=2 and cashier_id=$cashier_id");
    	$taxes = $this->Order_tax->query("SELECT tax_id,tax_name,tax_percentage,sum(tax_value) as tax_value FROM `order_tax` WHERE  created BETWEEN '$startdate $shiftstart' and '$enddate $shiftend' and status=2  and reference_id IN (SELECT reference_id FROM `order_orderhistories` WHERE cashier_id=$cashier_id  and reference_id NOT IN (SELECT reference_id from order_payments WHERE type=7 and status=2))  GROUP by tax_id");
        // $taxablepricess = $this->Order_tax->query("SELECT DISTINCT(product_id), taxable_price FROM order_tax WHERE  created BETWEEN '$startdate $shiftstart' and '$enddate $shiftend'  and status=2  and reference_id IN (SELECT reference_id FROM `order_orderhistories` WHERE cashier_id=$cashier_id)");
        // $taxablepricess = $this->Order_tax->query("SELECT DISTINCT taxable_price AS taxable_price FROM ( SELECT SUM(taxable_price) AS taxable_price FROM order_tax WHERE created BETWEEN  '$startdate $shiftstart' and '$enddate $shiftend' AND status = 2  and reference_id IN (SELECT reference_id FROM `order_orderhistories` WHERE cashier_id=$cashier_id) GROUP BY tax_id ) AS order_tax");   
        $taxablepricess = $this->Order_tax->query("SELECT DISTINCT taxable_price AS taxable_price FROM ( SELECT SUM(taxable_price) AS taxable_price FROM order_tax WHERE created BETWEEN  '$startdate $shiftstart' and '$enddate $shiftend' AND status = 2 and tax_percentage!=0  and reference_id IN (SELECT reference_id FROM `order_orderhistories` WHERE cashier_id=$cashier_id and reference_id NOT IN (SELECT reference_id from order_payments WHERE type=7 and status=2)) GROUP BY tax_id ) AS order_tax");   
        // print_r($taxablepricess);exit;
        $sales = $this->Order_tax->query("SELECT kds,kds_name,value,tax_percentage from (SELECT SUM(tax_percentage) as tax_percentage,kds,kds_name ,round(taxable_price+SUM(tax_value),2) as value FROM (SELECT tax_percentage,tax_id,kds,(select name from pos_printers where kds=order_tax.kds) as kds_name,round(SUM(taxable_price),2) as taxable_price,sum(tax_value) as tax_value FROM `order_tax` WHERE created BETWEEN '$startdate $shiftstart' and '$enddate $shiftend' and status=2  and reference_id IN (SELECT reference_id FROM `order_orderhistories` WHERE cashier_id=$cashier_id  and reference_id NOT IN (SELECT reference_id from order_payments WHERE type=7 and status=2)) GROUP by kds,tax_id) as sub GROUP by kds,tax_value) as final GROUP by kds,tax_percentage");
        
        $taxable_price=0;
        foreach($taxablepricess as $taxableprices){
            $taxable_price=round($taxable_price+$taxableprices['order_tax']['taxable_price'],2);
        }
        $key = array();
        $value = array();
        
        $key[] = "Payment Data";
        $value[] = "------";
        $heading[] = true;
        $key[] = "Cashier";
        $value[] = $cashiername;
        $key[] = "Total Collection";
        $value[] = round($payments[0][0]['total_amount']-$payments[0][0]['no_charge_with_tax'],2);
        $key[] = "Cash";
        $value[] = round($payments[0][0]['cash'],2);
        $key[] = "Card";
        $value[] = round($payments[0][0]['card'],2);
        $key[] = "UPI";
        $value[] = round($payments[0][0]['upi'],2);
        $key[] = "Online";
        $value[] = round($payments[0][0]['online'],2);
        $key[] = "Storecard";
        $value[] = round($payments[0][0]['storecard'],2);
        $key[] = "No Charge";
        $value[] = round($payments[0][0]['no_charge'],2);
        
        $key[] = "Total Data";
        $value[] = "------";
        $key[] = "Subtotal";
        $value[] = round($transactionsubtotal[0][0]['price'],2);
        $key[] = "Discount";
        $value[] = round($transactionsubtotal[0][0]['discount'],2);
        $key[] = "No Charge";
        $value[] = round($payments[0][0]['no_charge'],2);
        $key[] = "Taxable Amount";
        $value[] = round($taxable_price,2);
        $key[] = "Service Charge";
        $value[] = round($transactions[0][0]['servicecharge'],2);
        // $key[] = "Delivery Charge";
        // $value[] = round($transactions[0][0]['delivery_charge'],2);
        // $key[] = "Packing charge";
        // $value[] = round($transactions[0][0]['packing_charge'],2);
        $key[] = "Total Tax";
        $value[] = round($transactions[0][0]['total_tax'],2);
        $key[] = "Bill Count";
        $value[] = round($transactions[0][0]['total_count'],2);
        $key[] = "Net Amount";
        $value[] = round($transactions[0][0]['amount'],2);
        
        $key[] = "Taxes";
        $value[] = "------";
        $heading[] = true;
        
        foreach($taxes as $tax){
            $key[] = $tax['order_tax']['tax_name'].'('.$tax['order_tax']['tax_percentage'].'%)';
            $value[] = "" .round($tax[0]['tax_value'],2);
            $heading[] = false;
        }
        
        $key[] = "Sales Aggregation";
        $value[] = "------";
        $heading[] = true;
        
        foreach($sales as $sale){
            $key[] =$sale['final']['kds_name'].'('.$sale['final']['tax_percentage'].'%)';
            $value[] = round($sale['final']['value'],2);
            $heading[] = false;
        }
        
        $newData = array();

        $newData[] = array(
            "key" => "Payment Data",
            "value" => "------",
            "heading" => true
        );
        
       // Add the rest of the elements dynamically
        for ($i = 1; $i < count($key); $i++) {
            $newData[] = array(
                "key" => $key[$i],
                "value" => (string)$value[$i],
                "heading" => $key[$i] === "Taxes" || $key[$i] === "Total Data"  
            );
        }
        
        $response = array(
            'status' => true,
            'message' => "success",
            'data' => $newData
        );
        
        return json_encode($response, JSON_PRETTY_PRINT);
    }
    
    public function wallet_report_print()
    {
        $cashierid = $_REQUEST['id'];
        $sdate = $_REQUEST['sdate'];
        $edate = $_REQUEST['edate'];
        
        $response = array();
        
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id Missing",
            );
            return json_encode($response);
        }
        
        if($sdate==''){
            $response =array(
                'status'=> false,
                'message'=> "Start date Missing",
            );
            return json_encode($response);
        }
        
        if($edate==''){
            $response =array(
                'status'=> false,
                'message'=> "End date Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $cashiernames=$this->User->find('first',array('conditions'=>array('User.id'=>$cashierid)));
        $cashiername=$cashiernames['User']['name'];
        $shiftstart=shiftstart;
        $shiftend=shiftend;
        $edate = new DateTime($edate);
        $edate = $edate->modify('+1 day')->format('Y-m-d');

        $card = $this->Card->query("SELECT SUM(IF(status IN (2,1),1,0)) AS activecard, SUM(IF(status=0,1,0)) AS inactivecard FROM cards WHERE created between '$sdate $shiftstart' and '$edate $shiftend'");
        $activecards=$card[0][0]['activecard'];
        $inactivecards=$card[0][0]['inactivecard'];
        
        $cardtracking = $this->Cardtracking->query("SELECT SUM(IF(type=1 and purpose='add',amount,0)) AS totadd, SUM(IF(type=2 and purpose='withdrawal',amount,0)) AS totused, SUM(IF(type=3,amount,0)) AS totsec, SUM(IF(type=4,amount,0)) AS totref,COUNT(DISTINCT(customerphone)) as customers FROM cardtracking WHERE created between '$sdate $shiftstart' and '$edate $shiftend'");
        $totaladded=$cardtracking[0][0]['totadd'];
        $totalused=$cardtracking[0][0]['totused'];
        $totalsecurity=$cardtracking[0][0]['totsec'];
        $totalrefund=$cardtracking[0][0]['totref'];
        
        $key = array();
        $value = array();
        
        $key[] = "Card Data";
        $value[] = "------";
        $key[] = "Active Cards";
        $value[] = round($activecards,2);
        $key[] = "Inactive Cards";
        $value[] = round($inactivecards,2);
        
        $key[] = "Wallet Data";
        $value[] = "------";
        $key[] = "Total Balance Added";
        $value[] = round($totaladded,2);
        $key[] = "Total Used Amount";
        $value[] = round($totalused,2);
        $key[] = "Total Refunded Amount";
        $value[] = round($totalrefund,2);
        $key[] = "Total Security Amount";
        $value[] = round($totalsecurity,2);
        $key[] = "Net Balance";
        $value[] = round(($totaladded-$totalused),2);
        
        $newData = array();

        $newData[] = array(
            "key" => "Card Data",
            "value" => "------",
            "heading" => true
        );
        
       // Add the rest of the elements dynamically
        for ($i = 1; $i < count($key); $i++) {
            $newData[] = array(
                "key" => $key[$i],
                "value" => (string)$value[$i],
                "heading" => $key[$i] === "Wallet Data"
            );
        }
        
        $response = array(
            'status' => true,
            'message' => "success",
            'data' => $newData
        );
        
        return json_encode($response, JSON_PRETTY_PRINT);
    }
    
    public function item_sale_list()
    {
        $cashierid = $_REQUEST['id'];
        $sdate = $_REQUEST['sdate'];
        $edate = $_REQUEST['edate'];
        
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "User Id Missing",
            );
            return json_encode($response);
        }
        
        if($sdate==''){
            $response =array(
                'status'=> false,
                'message'=> "Start date Missing",
            );
            return json_encode($response);
        }
        
        if($edate==''){
            $response =array(
                'status'=> false,
                'message'=> "End date Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        $shiftstart=shiftstart;
        $shiftend=shiftend;
        $edate = new DateTime($edate);
        $edate = $edate->modify('+1 day')->format('Y-m-d');

        $orderhistories = $this->Order_orderhistory->query("SELECT product_id,product_name,category_name,SUM(quantity) as totalquantity,price FROM `order_orderhistories` WHERE status=2 and created between '$sdate $shiftstart' and '$edate $shiftend' and cashier_id=$cashierid GROUP BY product_id");
        foreach ($orderhistories as $orderhistory) {
            $items[] = [
                'product_id' => $orderhistory['order_orderhistories']['product_id'],
                'product_name' => $orderhistory['order_orderhistories']['product_name'],
                'category_name' => $orderhistory['order_orderhistories']['category_name'],
                'quantity' => $orderhistory[0]['totalquantity'],
                'price' => $orderhistory['order_orderhistories']['price']
            ];
        }

        $response= array('status'=> true,
                'message'=> "success",
                'data'=>$items
            );
        return json_encode($response);
    }
    
    public function item_sale_report()
    {
        $cashierid = $_REQUEST['id'];
        $sdate = $_REQUEST['sdate'];
        $edate = $_REQUEST['edate'];
        
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "User Id Missing",
            );
            return json_encode($response);
        }
        
        if($sdate==''){
            $response =array(
                'status'=> false,
                'message'=> "Start date Missing",
            );
            return json_encode($response);
        }
        
        if($edate==''){
            $response =array(
                'status'=> false,
                'message'=> "End date Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $key = array();
        $value = array();
        $shiftstart=shiftstart;
        $shiftend=shiftend;

        $edate = new DateTime($edate);
        $edate = $edate->modify('+1 day')->format('Y-m-d');
        
        $printers = $this->Pos_printer->query("SELECT name,kds FROM `pos_printers` WHERE status=1");
        foreach ($printers as $printer) {
            
            $key[] = $printer[pos_printers]['name'].' items';
            $value[] = '';
            
            $kds=$printer[pos_printers]['kds'];
            
            $orderhistories = $this->Order_orderhistory->query("SELECT product_id,product_name,category_name,SUM(quantity) as totalquantity,price,total_price FROM `order_orderhistories` WHERE status=2 and created between '$sdate $shiftstart' and '$edate $shiftend' and cashier_id=$cashierid  and kds=$kds GROUP BY product_id");
            foreach ($orderhistories as $orderhistory) {
                $key[] = $orderhistory[0]['totalquantity'].' * '.$orderhistory['order_orderhistories']['product_name'];
                $value[] = $orderhistory[order_orderhistories]['total_price'];
            }
            $newData = array();
            for ($i = 0; $i < count($key); $i++) {
                
                $newData[] = array(
                    "key" => $key[$i],
                    "value" => (string)$value[$i]
                );
            }
        
            
        }    
        $response = array(
            'status' => true,
            'message' => "success",
            'data' => $newData
        );
        
        return json_encode($response, JSON_PRETTY_PRINT);
    }
    
    public function card_validity_options()
    {
        $cashierid = $_REQUEST['id'];
    
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "User Id Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $todayDate = date("Y-m-d");
        $items[] = [
            'name'=>'today',
            'value'=>$todayDate
        ];
        $items[] = [
            'name'=>'unlimited',
            'value'=>'2030-12-31'
        ];
        $items[] = [
            'name'=>'custom',
            'value'=>'custom'
        ];
        
        $response= array('status'=> true,
                'message'=> "success",
                'data'=>$items
            );
        return json_encode($response);
    }
    
    public function card_payment_options()
    {
        $cashierid = $_REQUEST['id'];
    
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "User Id Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $items[] = [
            'name'=>'cash'
        ];
        $items[] = [
            'name'=>'card'
        ];
        $items[] = [
            'name'=>'online'
        ];
        
        $response= array('status'=> true,
                'message'=> "success",
                'data'=>$items
            );
        return json_encode($response);
    }
    
    public function quick_billupdate_discount()
    {
        $cashierid = $_REQUEST['id'];
        $ref_id = $_REQUEST['reference_id'];
        $disc=$_REQUEST['discount'];
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "User Id Missing",
            );
            return json_encode($response);
        }
        
        if($ref_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Reference id Missing",
            );
            return json_encode($response);
        }
        
        if($disc==''){
            $response =array(
                'status'=> false,
                'message'=> "Discount Missing",
            );
            return json_encode($response);
        }
        
        if($disc>99){
            $response =array(
                'status'=> false,
                'message'=> "Discount is not more than 99%",
            );
            return json_encode($response);
        }
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        if($disc>=0){
            $checkdiscount=$this->Order_orderhistory->find('first',array('conditions'=>array('Order_orderhistory.discount > '=>0,'Order_orderhistory.cashier_id'=>$cashierid,'Order_orderhistory.status'=>2,'Order_orderhistory.reference_id'=>$ref_id)));
            if(!empty($checkdiscount)){
                $response['status']= false;
                $response['message']= "Discount can not merge with item level discount";
                return json_encode($response);     
            }
        }else{
            $response['status']= false;
            $response['message']= "please check discount value";
            return json_encode($response);  
        }
        
        $txnchk = $this->Order_transaction->find('first', array('conditions'=>array('Order_transaction.reference_id'=>$ref_id, 'Order_transaction.cashier_id'=>$cashierid)));
        if(empty($txnchk))
        {
            $response= array('status'=> false,
                'message'=> "No Transaction found"
            );
            return json_encode($response);
        }
        if($txnchk['Order_transaction']['servicecharge']>0){
            $sc=1;
        }else{
            $sc=0;
        }
        
        $orderdata=$this->ordercompute($ref_id,$cashierid,$sc,$disc);
        
        if($orderdata['status'])
        {
            $totalservicechg=$orderdata['totalservicechg'];
            $totalprice=$orderdata['totalprice'];
            $totaltax=$orderdata['totaltax'];
            $totaldiscount=$orderdata['totaldiscount'];
            $totalamount=round((($totalprice+$totaltax+$totalservicechg)-$totaldiscount),2);
            
            $createtime = date('H:i:s');
            $this->Order_transaction->query("UPDATE `order_transactions` SET `price` = '$totalprice',`total_tax`='$totaltax',`servicecharge`='$totalservicechg',`discount`='$totaldiscount',`discount_type`='1',`discount_type_value`='$disc',`amount`='$totalamount',`createtime`='$createtime' WHERE `order_transactions`.`reference_id` = '$ref_id'");
            
            $response =array(
                'status'=> true,
                'message'=> "Saved",
            );
            return json_encode($response);
        }else{
            $response =array(
                'status'=> false,
                'message'=> "Not Saved",
            );
            return json_encode($response);
        }
    }
    
    public function quick_billupdate_servicecharge()
    {
        $cashierid = $_REQUEST['id'];
        $ref_id = $_REQUEST['reference_id'];
        $sc=$_REQUEST['service_charge'];
        
        $disc=0;
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "User Id Missing",
            );
            return json_encode($response);
        }
        
        if($ref_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Reference id Missing",
            );
            return json_encode($response);
        }
        
        if($sc==''){
            $response =array(
                'status'=> false,
                'message'=> "Service Charge Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $txnchk = $this->Order_transaction->find('first', array('conditions'=>array('Order_transaction.reference_id'=>$ref_id, 'Order_transaction.cashier_id'=>$cashierid)));
        if(empty($txnchk))
        {
            $response= array('status'=> false,
                'message'=> "No Transaction found"
            );
            return json_encode($response);
        }
        
        $orderdata=$this->ordercompute($ref_id,$cashierid,$sc,$disc);
        
        if($orderdata['status'])
        {
            $totalservicechg=$orderdata['totalservicechg'];
            $totalprice=$orderdata['totalprice'];
            $totaltax=$orderdata['totaltax'];
            $totaldiscount=$orderdata['totaldiscount'];
            $totalamount=round((($totalprice+$totaltax+$totalservicechg)-$totaldiscount),2);
            
            $createtime = date('H:i:s');
            $this->Order_transaction->query("UPDATE `order_transactions` SET `price` = '$totalprice',`total_tax`='$totaltax',`servicecharge`='$totalservicechg',`discount`='$totaldiscount',`discount_type`='1',`discount_type_value`='$disc',`amount`='$totalamount',`createtime`='$createtime' WHERE `order_transactions`.`reference_id` = '$ref_id'");
            
            $response =array(
                'status'=> true,
                'message'=> "Saved",
            );
            return json_encode($response);
        }else{
            $response =array(
                'status'=> false,
                'message'=> "Not Saved",
            );
            return json_encode($response);
        }
    }
    
    public function quick_billupdate_coupon()
    {
        $cashierid = $_REQUEST['id'];
        $ref_id = $_REQUEST['reference_id'];
        $coupon=$_REQUEST['coupon'];
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "User Id Missing",
            );
            return json_encode($response);
        }
        
        if($ref_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Reference id Missing",
            );
            return json_encode($response);
        }
        
        if($coupon==''){
            $response =array(
                'status'=> false,
                'message'=> "Coupon Code Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $todayDate = date("Y-m-d");
        $coup = $this->Coupon->find('first', array('conditions'=>array('Coupon.code'=>$coupon,'Coupon.expiry_date >='=>$todayDate,'Coupon.status'=>1)));
        if(empty($coup))
        {
            $response =array(
                'status'=> false,
                'message'=> "Coupon not found Or Coupon Expired",
            );
            return json_encode($response);
        }
        $coup_value=$coup['Coupon']['value'];
        
        $txnchk = $this->Order_transaction->find('first', array('conditions'=>array('Order_transaction.reference_id'=>$ref_id, 'Order_transaction.cashier_id'=>$cashierid)));
        if(empty($txnchk))
        {
            $response= array('status'=> false,
                'message'=> "No Transaction found"
            );
            return json_encode($response);
        }
        if($txnchk['Order_transaction']['servicecharge']>0){
            $sc=1;
        }else{
            $sc=0;
        }
        
        $disc=$coup_value;
        
        $orderdata=$this->ordercompute($ref_id,$cashierid,$sc,$disc);
//      print_r($ref_id.'<br>'.$cashierid.'<br>'.$sc.'<br>'.$disc);exit;
        if($orderdata['status'])
        {
            $totalservicechg=$orderdata['totalservicechg'];
            $totalprice=$orderdata['totalprice'];
            $totaltax=$orderdata['totaltax'];
            $totaldiscount=$orderdata['totaldiscount'];
            $totalamount=round((($totalprice+$totaltax+$totalservicechg)-$totaldiscount),2);
            
            $createtime = date('H:i:s');
            $this->Order_transaction->query("UPDATE `order_transactions` SET `price` = '$totalprice',`total_tax`='$totaltax',`servicecharge`='$totalservicechg',`discount`='$totaldiscount',`discount_type`='0',`discount_type_value`='$coupon',`amount`='$totalamount',`createtime`='$createtime' WHERE `order_transactions`.`reference_id` = '$ref_id'");
            
            $response =array(
                'status'=> true,
                'message'=> "Saved",
            );
            return json_encode($response);
        }else{
            $response =array(
                'status'=> false,
                'message'=> "Not Saved",
            );
            return json_encode($response);
        }
    }
    
    //validity crons
    public function cron_disable_cards()
    {
        // Current date and time
        $today= date('Y-m-d H:i:s');
        
        $cards = $this->Card->query("SELECT * FROM `cards` WHERE status=2");
        foreach($cards as $card) {
            $cardnumber = $card['cards']['cardnumber'];
            $cardtracks = $this->Cardtracking->query("SELECT newbalance FROM `cardtracking` WHERE cardnumber='$cardnumber' order by id desc limit 1");
            if($cardtracks[0]['cardtracking']['newbalance']){
                
                do {
                    $txnid = '';
                    for ($i = 0; $i < 10; $i++) {
                        $txnid .= rand(0, 9);
                    }
                    $existingOTP = $this->Cardtracking->find('first', array(
                        'conditions' => array(
                            'txnid' => $txnid
                        )
                    ));
                } while ($existingOTP); // Continue generating OTP until it doesn't exist
                
                $data['Cardtracking']=array(
                    'cardnumber'=>$cardnumber,
                    'txnid'=>$txnid,
                    'purpose'=>'transfertoTheParkWallet',
                    'oldbalance'=>$cardtracks[0]['cardtracking']['newbalance'],
                    'amount'=>$cardtracks[0]['cardtracking']['newbalance'],
                    'newbalance'=>0,
                    'type'=>5,
                    'payment_mode'=>'transfertoTheParkWallet'
                );
              
                if($this->Cardtracking->saveAll($data['Cardtracking']))
                {
                    $this->Card->query("UPDATE cards SET cardbalance = 0,status=1,name='',mobile=0,email='',valid_to=NULL WHERE cardnumber = '$cardnumber'");
                }else{
                    echo "Not Saved";
                }
            }else{
                $this->Card->query("UPDATE cards SET cardbalance = 0,status=1,name='',mobile=0,email='',valid_to=NULL WHERE cardnumber = '$cardnumber'");
            }
        }
    }
    
    public function payment_storecard()
    {
        $cashierid = $_REQUEST['id'];
        $cardno=preg_replace('/\D/', '', $_REQUEST['cardno']);
        $amount = $_REQUEST['amount'];
        $otp = $_REQUEST['otp'];
        $mode = $_REQUEST['mode'];
        $reference_id = $_REQUEST['reference_id'];
        $device_id = $_REQUEST['device_id'];
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id Missing",
            );
            return json_encode($response);
        }
        if($cardno==''){
            $response =array(
                'status'=> false,
                'message'=> "Card no Missing",
            );
            return json_encode($response);
        }
        if($amount==''){
            $response =array(
                'status'=> false,
                'message'=> "Amount Missing",
            );
            return json_encode($response);
        }
        if($mode==''){
            $response =array(
                'status'=> false,
                'message'=> "payment mode Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found or User Deactivated",
            );
            return json_encode($response);
        }else{
            $cashiername=$users['User']['name'];
        }
        
        $transactions = $this->Order_transaction->find('first', array('conditions'=>array('Order_transaction.reference_id'=>$reference_id,'Order_transaction.status'=>1)));
        if(empty($transactions))
        {
            $response =array(
                'status'=> false,
                'message'=> "Transaction not found",
            );
            return json_encode($response);
        }
        
        $card = $this->Card->find('first', array('conditions'=>array('Card.cardnumber'=>$cardno,'Card.status'=>2)));
        if(empty($card))
        {
            $response =array(
                'status'=> false,
                'message'=> "Card not found or Card Deactivated",
            );
            return json_encode($response);
        }else{
            $pinreq=$card['Card']['pin_required'];
            if($pinreq){
                if($otp==''){
                    $response =array(
                        'status'=> false,
                        'message'=> "PIN Missing",
                    );
                    return json_encode($response);
                }
                $card = $this->Card->find('first', array('conditions'=>array('Card.cardnumber'=>$cardno,'Card.pin'=>$otp,'Card.status'=>2)));
                if(empty($card))
                {
                    $response =array(
                        'status'=> false,
                        'message'=> "Wrong PIN ",
                    );
                    return json_encode($response);
                }
            }
            $card = $this->Card->find('first', array('conditions'=>array('Card.cardnumber'=>$cardno,'Card.cardbalance >= '=>$amount)));
            if(empty($card))
            {
                $response =array(
                    'status'=> false,
                    'message'=> "Withdrawal Amount not exist in card ",
                );
                return json_encode($response);
            }
            
            $today = date("Y-m-d H:i:s");
            $currentDate = new DateTime($today);
            $newdate = $currentDate->modify('-2 minute')->format('Y-m-d H:i:s');

            $cardtrackingchk = $this->Cardtracking->query("SELECT * FROM cardtracking where cardnumber='$cardno' and amount='$amount' and created between '$newdate' and '$today' and type=2");
            if(!empty($cardtrackingchk))
            {
                $response =array(
                    'status'=> false,
                    'message'=> "Withdraw blocked for 2 minutes",
                );
                return json_encode($response);
            }
            
            $name=$card['Card']['name'];
            $mobile=$card['Card']['mobile'];
            $oldbal=$card['Card']['cardbalance'];
            $newbal=$oldbal-$amount;
            
            do {
                $txnid = '';
                for ($i = 0; $i < 10; $i++) {
                    $txnid .= rand(0, 9);
                }
                $existingOTP = $this->Cardtracking->find('first', array(
                    'conditions' => array(
                        'txnid' => $txnid
                    )
                ));
            } while ($existingOTP); // Continue generating OTP until it doesn't exist
            
            $data['Cardtracking']=array(
                'cardnumber'=>$cardno,
                'cashierID'=>$cashierid,
                'txnid'=>$txnid,
                'reference_id'=>$reference_id,
                'cashierName'=>$cashiername,
                'customername'=>$name,
                'customerphone'=>$mobile,
                'purpose'=>'withdrawal',
                'oldbalance'=>$oldbal,
                'amount'=>$amount,
                'newbalance'=>$newbal,
                'type'=>2,
                'payment_mode'=>$mode
            );
          
            if($this->Cardtracking->saveAll($data['Cardtracking']))
            {
                $this->Card->query("UPDATE cards SET cardbalance = $newbal WHERE cardnumber = '$cardno'");
            
                //payment save
            
                $datas['Order_payment']=array(
                    'reference_id'=>$reference_id,
                    'device_id'=>$device_id,
                    'cashier_id'=>$cashierid,
                    'type'=>8,
                    'type_value'=>'StoreCard',
                    'amount'=>$amount,
                    'remarks'=>$cardno
                );
                if($this->Order_payment->saveAll($datas['Order_payment']))
                {
                    $finalpayment=0;
                    $finalamount=0;
                    $allpayments=$this->Order_payment->query("SELECT sum(amount) as pay_amount FROM `order_payments` WHERE reference_id='$reference_id'");
                    if($allpayments){
                        $finalpayment=$allpayments[0][0]['pay_amount'];
                    }
                    if($transactions){
                        $finalamount=$transactions['Order_transaction']['amount'];
                    }
                    $amount_diff=$finalamount-$finalpayment;
                    if($amount_diff<1){
                        
                        $this->Order_orderhistory->query("UPDATE order_orderhistories SET status = 2 WHERE reference_id = '$reference_id' and status = 1");
                        $this->Order_transaction->query("UPDATE order_transactions SET status = 2,payment_mode='StoreCard' WHERE reference_id = '$reference_id'");
                        $this->Order_payment->query("UPDATE order_payments SET status = 2 WHERE reference_id = '$reference_id'");
                        $this->Order_tax->query("UPDATE order_tax SET status = 2 WHERE reference_id = '$reference_id' and status != 0");
                        
                        $stockupdate=$this->stock_update($reference_id);
                        if(!$stockupdate){
                            $response['status']= true;
                            $response['message']= "Payment Data Saved Successfully..! But stock not updated";
                            $response['full_payment']= true; 
                        }
                        $response['status']= true;
                        $response['message']= "Payment Data Saved Successfully..!";
                        $response['full_payment']= true;
                        
                    }else{
                        $response['status']= true;
                        $response['message']= "Payment Data Saved Successfully..!";
                        $response['full_payment']= false;
                    }            
                }else{
                    $response['status']= false;
                    $response['message']= "Payment Data not saved Error:102";
                    $response['full_payment']= false;
                }
            }else{
                $response =array(
                    'status'=> false,
                    'message'=> "failed",
                );
            }
        }
        return json_encode($response);
    }
    
    public function payment_storecard_table()
    {
        $cashierid = $_REQUEST['id'];
        $cardno=preg_replace('/\D/', '', $_REQUEST['cardno']);
        $amount = $_REQUEST['amount'];
        $otp = $_REQUEST['otp'];
        $mode = $_REQUEST['mode'];
        $reference_id = $_REQUEST['reference_id'];
        $device_id = $_REQUEST['device_id'];
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id Missing",
            );
            return json_encode($response);
        }
        if($cardno==''){
            $response =array(
                'status'=> false,
                'message'=> "Card no Missing",
            );
            return json_encode($response);
        }
        if($amount==''){
            $response =array(
                'status'=> false,
                'message'=> "Amount Missing",
            );
            return json_encode($response);
        }
        if($mode==''){
            $response =array(
                'status'=> false,
                'message'=> "payment mode Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found or User Deactivated",
            );
            return json_encode($response);
        }else{
            $cashiername=$users['User']['name'];
        }
        
        $transactions = $this->Order_transaction->find('first', array('conditions'=>array('Order_transaction.reference_id'=>$reference_id,'Order_transaction.status'=>1)));
        if(empty($transactions))
        {
            $response =array(
                'status'=> false,
                'message'=> "Transaction not found",
            );
            return json_encode($response);
        }
        
        $card = $this->Card->find('first', array('conditions'=>array('Card.cardnumber'=>$cardno,'Card.status'=>2)));
        if(empty($card))
        {
            $response =array(
                'status'=> false,
                'message'=> "Card not found or Card Deactivated",
            );
            return json_encode($response);
        }else{
            $pinreq=$card['Card']['pin_required'];
            if($pinreq){
                if($otp==''){
                    $response =array(
                        'status'=> false,
                        'message'=> "PIN Missing",
                    );
                    return json_encode($response);
                }
                $card = $this->Card->find('first', array('conditions'=>array('Card.cardnumber'=>$cardno,'Card.pin'=>$otp,'Card.status'=>2)));
                if(empty($card))
                {
                    $response =array(
                        'status'=> false,
                        'message'=> "Wrong PIN ",
                    );
                    return json_encode($response);
                }
            }
            $card = $this->Card->find('first', array('conditions'=>array('Card.cardnumber'=>$cardno,'Card.cardbalance >= '=>$amount)));
            if(empty($card))
            {
                $response =array(
                    'status'=> false,
                    'message'=> "Withdrawal Amount not exist in card ",
                );
                return json_encode($response);
            }
            
            $today = date("Y-m-d H:i:s");
            $currentDate = new DateTime($today);
            $newdate = $currentDate->modify('-2 minute')->format('Y-m-d H:i:s');

            $cardtrackingchk = $this->Cardtracking->query("SELECT * FROM cardtracking where cardnumber='$cardno' and amount='$amount' and created between '$newdate' and '$today' and type=2");
            if(!empty($cardtrackingchk))
            {
                $response =array(
                    'status'=> false,
                    'message'=> "Withdraw blocked for 2 minutes",
                );
                return json_encode($response);
            }
            
            $name=$card['Card']['name'];
            $mobile=$card['Card']['mobile'];
            $oldbal=$card['Card']['cardbalance'];
            $newbal=$oldbal-$amount;
            
            do {
                $txnid = '';
                for ($i = 0; $i < 10; $i++) {
                    $txnid .= rand(0, 9);
                }
                $existingOTP = $this->Cardtracking->find('first', array(
                    'conditions' => array(
                        'txnid' => $txnid
                    )
                ));
            } while ($existingOTP); // Continue generating OTP until it doesn't exist
            
            $data['Cardtracking']=array(
                'cardnumber'=>$cardno,
                'cashierID'=>$cashierid,
                'txnid'=>$txnid,
                'reference_id'=>$reference_id,
                'cashierName'=>$cashiername,
                'customername'=>$name,
                'customerphone'=>$mobile,
                'purpose'=>'withdrawal',
                'oldbalance'=>$oldbal,
                'amount'=>$amount,
                'newbalance'=>$newbal,
                'type'=>2,
                'payment_mode'=>$mode
            );
          
            if($this->Cardtracking->saveAll($data['Cardtracking']))
            {
                $this->Card->query("UPDATE cards SET cardbalance = $newbal WHERE cardnumber = '$cardno'");
            
                //payment save
            
                $datas['Order_payment']=array(
                    'reference_id'=>$reference_id,
                    'device_id'=>$device_id,
                    'cashier_id'=>$cashierid,
                    'type'=>8,
                    'type_value'=>'StoreCard',
                    'amount'=>$amount,
                    'remarks'=>$cardno
                );
                if($this->Order_payment->saveAll($datas['Order_payment']))
                {
                    $finalpayment=0;
                    $finalamount=0;
                    $allpayments=$this->Order_payment->query("SELECT sum(amount) as pay_amount FROM `order_payments` WHERE reference_id='$reference_id'");
                    if($allpayments){
                        $finalpayment=$allpayments[0][0]['pay_amount'];
                    }
                    if($transactions){
                        $finalamount=$transactions['Order_transaction']['amount'];
                    }
                    $amount_diff=$finalamount-$finalpayment;
                    if($amount_diff<1){
                           
                        $this->Order_orderhistory->query("UPDATE order_orderhistories SET status = 2 WHERE reference_id = '$reference_id' and status = 1");
                        $this->Order_transaction->query("UPDATE order_transactions SET status = 2,payment_mode='StoreCard' WHERE reference_id = '$reference_id'");
                        $this->Order_payment->query("UPDATE order_payments SET status = 2 WHERE reference_id = '$reference_id'");
                        $this->Order_tax->query("UPDATE order_tax SET status = 2 WHERE reference_id = '$reference_id' and status != 0");
                        
                        do {
                            $pin = 'TX' . $cashierid . date('Y') . uniqid();
                            // $pin = uniqid();
                        } while ($this->Order_table->find('first', array('fields' => 'Order_table.id', 'conditions' => array('Order_table.reference_id' => $pin))));
                        
                        $tablestatus = $this->Order_table->find('first', array('conditions'=>array('reference_id'=>$reference_id,'is_takeaway'=>1)));
                        if(!empty($tablestatus))
                        {   
                            $this->Order_table->query("DELETE FROM order_tables  WHERE reference_id = '$reference_id'");
                        }else{
                            $this->Order_table->query("UPDATE order_tables SET status = 1,reference_id='$pin' WHERE reference_id = '$reference_id'");
                        }
                        
                        $stockupdate=$this->stock_update($reference_id);
                        if(!$stockupdate){
                            $response['status']= true;
                            $response['message']= "Payment Data Saved Successfully..! But stock not updated";
                            $response['full_payment']= true; 
                        }
                        $response['status']= true;
                        $response['message']= "Payment Data Saved Successfully..!";
                        $response['full_payment']= true;
                        
                    }else{
                        $response['status']= true;
                        $response['message']= "Payment Data Saved Successfully..!";
                        $response['full_payment']= false;
                    }            
                }else{
                    $response['status']= false;
                    $response['message']= "Payment Data not saved Error:102";
                    $response['full_payment']= false;
                }
            }else{
                $response =array(
                    'status'=> false,
                    'message'=> "failed",
                );
            }
        }
        return json_encode($response);
    }
    
    //booking cron
    public function cron_booking_alarm()
    {
        // Current date and time
        $today= date('Y-m-d H:i:s');
        // $today = '2024-07-29 11:00:00';
        $addDatetime = new DateTime($today);
        $addDatetime->modify("+30 minutes");
        $checkTime = $addDatetime->format('Y-m-d H:i:s');
        
        
        $upcomingBookings =  $this->Online_booking->query("SELECT * FROM `online_bookings` WHERE booking_time between '$today' and '$checkTime' AND status=1 LIMIT 10");
        foreach($upcomingBookings as $upcomingBooking) {
            $tableNumber = $upcomingBooking['online_bookings']['table_number'];
            $tableCheck = $this->Order_table->query("SELECT * FROM `order_tables` WHERE number='$tableNumber' AND status!=1");
            if($tableCheck) {
                $this->Order_table->query("UPDATE order_tables SET is_alert = '1' WHERE number = '$tableNumber'");
            }else{
                $this->Order_table->query("UPDATE order_tables SET is_alert = '0' WHERE number = '$tableNumber'");
            }
        }
        
        $addtime = new DateTime($today);
        $addtime->modify("-5 minutes");
        $check_time = $addtime->format('Y-m-d H:i:s');
        $Bookingupdates = $this->Online_booking->query("SELECT * FROM `online_bookings` WHERE booking_time between '$check_time' and '$today' AND status=1");
        foreach($Bookingupdates as $Bookingupdate) {
            $tableNumber = $Bookingupdate['online_bookings']['table_number'];
            $id = $Bookingupdate['online_bookings']['id'];
            $payment_type = $Bookingupdate['online_bookings']['payment_type'];
            if($payment_type==2){
                $pay_option = $Bookingupdate['online_bookings']['pay_option'];
                $pay_option_value = $Bookingupdate['online_bookings']['pay_option_value'];
            }else{
                $pay_option=1;
                $pay_option_value='postpaid';
            }
            
            $tableCheck = $this->Order_table->query("SELECT * FROM `order_tables` WHERE number='$tableNumber' AND status=1");
            if($tableCheck) {
                $datas['Order_payment']=array(
                    'reference_id'=>$tableCheck[0]['order_tables']['reference_id'],
                    'cashier_id'=>$Bookingupdate['online_bookings']['user_id'],
                    'type'=>$pay_option,
                    'type_value'=>$pay_option_value,
                    'amount'=>$Bookingupdate['online_bookings']['cover_charge'],
                    'remarks'=>$Bookingupdate['online_bookings']['remarks'],
                    'status'=>2
                );
                if($this->Order_payment->saveAll($datas['Order_payment']))
                {
                    $this->Order_table->query("UPDATE order_tables SET status = '2',modified='$today' WHERE number = '$tableNumber'");
                    $this->Online_booking->query("UPDATE online_bookings SET status = '3',modified='$today' WHERE id = '$id'");
                }
            }
        }
        
    }
    
    //stock update from POS
    public function stock_update($txnid=null){
        $response['status']=false;
        
        $orderhistories=$this->Order_orderhistory->find('all',array('conditions'=>array('Order_orderhistory.reference_id'=>$txnid,'status' =>2)));
        foreach($orderhistories as $data){
            $product_id=$data['Order_orderhistory']['product_id'];
            $product_quantity=$data['Order_orderhistory']['quantity'];
            $cashier_id=$data['Order_orderhistory']['cashier_id'];
            
            $store=$this->User->find('first',array('conditions'=>array('User.id'=>$cashier_id,'status' =>1)));
            $store_id=$store['User']['location_id'];
            
            //product linking with semifinished 
            // $semifinished_products=$this->Inventory_product_semifinished_linking->find('all',array('conditions'=>array('product_id'=>$product_id,'status' =>1)));
            $semifinished_products=$this->Inventory_linking->find('all',array('conditions'=>array('parent_type'=>'Product','parent_id'=>$product_id,'component_type'=>'Semifinished','status' =>1)));
            foreach($semifinished_products as $semifinished_product){
                $semifinished_id=$semifinished_product['Inventory_linking']['component_id'];
                $semiquantity=$semifinished_product['Inventory_linking']['quantity']*$product_quantity;
                
                $semidetails=$this->Inventory_semifinished->find('first',array('conditions'=>array('id'=>$semifinished_id)));
                $semiprice=$semidetails['Inventory_semifinished']['price'];
                
                   
                    $ledgerprevdetails = $this->Stock_ledger->find('first', [
                        'conditions' => ['sku_id' => $semifinished_product['Inventory_linking']['component_id'],'store_id' =>$store_id,'type'=>'OUTLET','item_type'=>'semifinished' ],
                        'fields' => ['actual_balance'],
                        'order' => ['id DESC'],
                        'recursive' => -1
                    ]);
                    
                    $ledger_prev_quantity = !empty($ledgerprevdetails['Stock_ledger']['actual_balance']) 
                        ? $ledgerprevdetails['Stock_ledger']['actual_balance'] 
                        : 0;
                    
                    $newQuantity = $ledger_prev_quantity-$semiquantity;
                    
                    $ledgerData['Stock_ledger'] = [
                            'store_id'        => $store_id,
                            'sku_id'          => $semifinished_product['Inventory_linking']['component_id'],
                            'sku_name'        => $semifinished_product['Inventory_linking']['component_name'],
                            'sku_price'       => $semiprice,
                            'unit_id'         => $semifinished_product['Inventory_linking']['component_unit'],
                            'unit_name'       => $semifinished_product['Inventory_linking']['component_unit_name'],
                            'record_id'       => $txnid,
                            'record_type'     => 'stockout',
                            'quantity'        => $semiquantity,
                            'balance_stock'   => $newQuantity,
                            'actual_balance'  => $newQuantity,
                            'quantity_type'   => 'debit',
                            'type'            => 'OUTLET',
                            'item_type'       => 'semifinished',
                            'created'         => date('Y-m-d H:i:s')
                    ];
    				if(!$this->Stock_ledger->saveAll($ledgerData['Stock_ledger'])){
                        $check=false;
                    }
                    
                    
                    //semifinished linking with sku
                    $sku_products=$this->Inventory_linking->find('all',array('conditions'=>array('parent_type'=>'Semifinished','parent_id'=>$semifinished_id,'component_type'=>'Sku','status' =>1)));
                    foreach($sku_products as $sku_product){
                        $sku_id=$sku_product['Inventory_linking']['component_id'];
                        $skuquantity=$sku_product['Inventory_linking']['quantity']*$semiquantity;
                        
                        $skudetails=$this->Inventory_sku->find('first',array('conditions'=>array('id'=>$sku_id)));
                        $skuprice=$skudetails['Inventory_sku']['price'];
                        
                        
                            $ledgerprevdetails = $this->Stock_ledger->find('first', [
                                'conditions' => ['sku_id' => $sku_product['Inventory_linking']['component_id'],'store_id' =>$store_id ,'type' =>'OUTLET','item_type'=>'SKU' ],
                                'fields' => ['actual_balance'],
                                'order' => ['id DESC'],
                                'recursive' => -1
                            ]);
                            
                            $ledger_prev_quantity = !empty($ledgerprevdetails['Stock_ledger']['actual_balance']) 
                                ? $ledgerprevdetails['Stock_ledger']['actual_balance'] 
                                : 0;
                            
                            $newQuantity = $ledger_prev_quantity-$skuquantity;
                            
                            $ledgerData['Stock_ledger'] = [
                                    'store_id'        => $store_id,
                                    'sku_id'          => $sku_product['Inventory_linking']['component_id'],
                                    'sku_name'        => $sku_product['Inventory_linking']['component_name'],
                                    'sku_price'       => $skuprice,
                                    'unit_id'         => $sku_product['Inventory_linking']['component_unit'],
                                    'unit_name'       => $sku_product['Inventory_linking']['component_unit_name'],
                                    'record_id'       => $txnid,
                                    'record_type'     => 'stockout',
                                    'quantity'        => $skuquantity,
                                    'balance_stock'   => $newQuantity,
                                    'actual_balance'  => $newQuantity,
                                    'quantity_type'   => 'debit',
                                    'type'            => 'OUTLET',
                                    'item_type'       => 'SKU',
                                    'created'         => date('Y-m-d H:i:s')
                            ];
            				if(!$this->Stock_ledger->saveAll($ledgerData['Stock_ledger'])){
                                $check=false;
                            }
                            $check=true;
                        
                    }
                    
                    
                    //semifinished linking with semifinished
                    $linked_semi_products=$this->Inventory_linking->find('all',array('conditions'=>array('parent_type'=>'Semifinished','parent_id'=>$semifinished_id,'component_type'=>'Semifinished','status' =>1)));
                    foreach($linked_semi_products as $linked_semi_product){
                        $linked_semi_id=$linked_semi_product['Inventory_linking']['component_id'];
                        $linked_semi_quantity=$linked_semi_product['Inventory_linking']['quantity']*$semiquantity;
                        
                        $linkedsemidetails=$this->Inventory_semifinished->find('first',array('conditions'=>array('id'=>$linked_semi_id)));
                        $linkedsemiprice=$linkedsemidetails['Inventory_semifinished']['price'];
                        
                            $ledgerprevdetails = $this->Stock_ledger->find('first', [
                                'conditions' => ['sku_id' => $linked_semi_id,'store_id' =>$store_id ,'type' =>'OUTLET','item_type'=>'Semifinished' ],
                                'fields' => ['actual_balance'],
                                'order' => ['id DESC'],
                                'recursive' => -1
                            ]);
                            
                            $ledger_prev_quantity = !empty($ledgerprevdetails['Stock_ledger']['actual_balance']) 
                                ? $ledgerprevdetails['Stock_ledger']['actual_balance'] 
                                : 0;
                            
                            $newQuantity = $ledger_prev_quantity-$skuquantity;
                            
                            $ledgerData['Stock_ledger'] = [
                                    'store_id'        => $store_id,
                                    'sku_id'          => $linked_semi_id,
                                    'sku_name'        => $linkedsemidetails['Inventory_semifinished']['name'],
                                    'sku_price'       => $linkedsemiprice,
                                    'unit_id'         => $linkedsemidetails['Inventory_semifinished']['unit'],
                                    'unit_name'       => $linkedsemidetails['Inventory_semifinished']['unit_name'],
                                    'record_id'       => $txnid,
                                    'record_type'     => 'stockout',
                                    'quantity'        => $linked_semi_quantity,
                                    'balance_stock'   => $newQuantity,
                                    'actual_balance'  => $newQuantity,
                                    'quantity_type'   => 'debit',
                                    'type'            => 'OUTLET',
                                    'item_type'       => 'Semifinished',
                                    'created'         => date('Y-m-d H:i:s')
                            ];
            				if(!$this->Stock_ledger->saveAll($ledgerData['Stock_ledger'])){
                                $check=false;
                            }
                            $check=true;
                        
                    }
                    
            }
            
            //product linking with direct sku 
            $sku_direct_products=$this->Inventory_linking->find('all',array('conditions'=>array('parent_type'=>'Product','parent_id'=>$product_id,'component_type'=>'Sku','status' =>1)));
            foreach($sku_direct_products as $sku_direct_product){
                $sku_id=$sku_direct_product['Inventory_linking']['component_id'];
                //sku previous stock
                $skudirectquantity=$sku_direct_product['Inventory_linking']['quantity']*$product_quantity;
                $skudetails=$this->Inventory_sku->find('first',array('conditions'=>array('id'=>$sku_id)));
                $skuprice=$skudetails['Inventory_sku']['price'];
                
                    
                    $ledgerprevdetails = $this->Stock_ledger->find('first', [
                        'conditions' => ['sku_id' => $sku_id,'store_id' =>$store_id ,'type' =>'OUTLET','item_type'=>'SKU' ],
                        'fields' => ['actual_balance'],
                        'order' => ['id DESC'],
                        'recursive' => -1
                    ]);
                    
                    $ledger_prev_quantity = !empty($ledgerprevdetails['Stock_ledger']['actual_balance']) 
                        ? $ledgerprevdetails['Stock_ledger']['actual_balance'] 
                        : 0;
                    
                    $newQuantity = $ledger_prev_quantity-$skudirectquantity;
                    
                    $ledgerData['Stock_ledger'] = [
                            'store_id'        => $store_id,
                            'sku_id'          => $sku_direct_product['Inventory_linking']['component_id'],
                            'sku_name'        => $sku_direct_product['Inventory_linking']['component_name'],
                            'sku_price'       => $skuprice,
                            'unit_id'         => $sku_direct_product['Inventory_linking']['component_unit'],
                            'unit_name'       => $sku_direct_product['Inventory_linking']['component_unit_name'],
                            'record_id'       => $txnid,
                            'record_type'     => 'stockout',
                            'quantity'        => $skudirectquantity,
                            'balance_stock'   => $newQuantity,
                            'actual_balance'  => $newQuantity,
                            'quantity_type'   => 'debit',
                            'type'            => 'OUTLET',
                            'item_type'       => 'SKU',
                            'created'         => date('Y-m-d H:i:s')
                    ];
    				if(!$this->Stock_ledger->saveAll($ledgerData['Stock_ledger'])){
                        $check=false;
                    }
                    $check=true;
                
            }
            
            //modifier linking with products 
            $ordermodifiers=$this->Order_modifier->find('all',array('conditions'=>array('reference_id'=>$txnid,'product_id'=>$product_id,'status' =>1)));
            foreach($ordermodifiers as $modifier){
                $modifier_id=$modifier['Order_modifier']['modifier_id'];
                $quantity=$modifier['Order_modifier']['quantity'];
                
                //modifier linking with semifinished 
                $semifinished_products=$this->Inventory_linking->find('all',array('conditions'=>array('parent_type'=>'Modifier','parent_id'=>$modifier_id,'component_type'=>'Semifinished','status' =>1)));
                foreach($semifinished_products as $semifinished_product){
                    $semifinished_id=$semifinished_product['Inventory_linking']['component_id'];
                    $semiquantity=$semifinished_product['Inventory_linking']['quantity']*$quantity;
                    
                    $semidetails=$this->Inventory_semifinished->find('first',array('conditions'=>array('id'=>$semifinished_id)));
                    $semiprice=$semidetails['Inventory_semifinished']['price'];
                    
                        $ledgerprevdetails = $this->Stock_ledger->find('first', [
                            'conditions' => ['sku_id' => $semifinished_id,'store_id' =>$store_id,'type'=>'OUTLET','item_type'=>'semifinished' ],
                            'fields' => ['actual_balance'],
                            'order' => ['id DESC'],
                            'recursive' => -1
                        ]);
                        
                        $ledger_prev_quantity = !empty($ledgerprevdetails['Stock_ledger']['actual_balance']) 
                            ? $ledgerprevdetails['Stock_ledger']['actual_balance'] 
                            : 0;
                        
                        $newQuantity = $ledger_prev_quantity-$semiquantity;
                        
                        $ledgerData['Stock_ledger'] = [
                                'store_id'        => $store_id,
                                'sku_id'          => $semifinished_id,
                                'sku_name'        => $semifinished_product['Inventory_linking']['component_name'],
                                'sku_price'       => $semiprice,
                                'unit_id'         => $semifinished_product['Inventory_linking']['component_unit'],
                                'unit_name'       => $semifinished_product['Inventory_linking']['component_unit_name'],
                                'record_id'       => $txnid,
                                'record_type'     => 'stockout_modifier',
                                'quantity'        => $semiquantity,
                                'balance_stock'   => $newQuantity,
                                'actual_balance'  => $newQuantity,
                                'quantity_type'   => 'debit',
                                'type'            => 'OUTLET',
                                'item_type'       => 'semifinished',
                                'created'         => date('Y-m-d H:i:s')
                        ];
        				if(!$this->Stock_ledger->saveAll($ledgerData['Stock_ledger'])){
                            $check=false;
                        }
                        
                        //semifinished linking with sku
                        $sku_products=$this->Inventory_linking->find('all',array('conditions'=>array('parent_type'=>'Semifinished','parent_id'=>$semifinished_id,'component_type'=>'Sku','status' =>1)));
                        foreach($sku_products as $sku_product){
                            $sku_id=$sku_product['Inventory_linking']['component_id'];
                            $skuquantity=$sku_product['Inventory_linking']['quantity']*$semiquantity;
                            
                            $skudetails=$this->Inventory_sku->find('first',array('conditions'=>array('id'=>$sku_id)));
                            $skuprice=$skudetails['Inventory_sku']['price'];
                            
                                $ledgerprevdetails = $this->Stock_ledger->find('first', [
                                    'conditions' => ['sku_id' => $sku_id,'store_id' =>$store_id ,'type' =>'OUTLET','item_type'=>'SKU' ],
                                    'fields' => ['actual_balance'],
                                    'order' => ['id DESC'],
                                    'recursive' => -1
                                ]);
                                
                                $ledger_prev_quantity = !empty($ledgerprevdetails['Stock_ledger']['actual_balance']) 
                                    ? $ledgerprevdetails['Stock_ledger']['actual_balance'] 
                                    : 0;
                                
                                $newQuantity = $ledger_prev_quantity-$skuquantity;
                                
                                $ledgerData['Stock_ledger'] = [
                                        'store_id'        => $store_id,
                                        'sku_id'          => $sku_id,
                                        'sku_name'        => $sku_product['Inventory_linking']['component_name'],
                                        'sku_price'       => $skuprice,
                                        'unit_id'         => $sku_product['Inventory_linking']['component_unit'],
                                        'unit_name'       => $sku_product['Inventory_linking']['component_unit_name'],
                                        'record_id'       => $txnid,
                                        'record_type'     => 'stockout_modifier',
                                        'quantity'        => $skuquantity,
                                        'balance_stock'   => $newQuantity,
                                        'actual_balance'  => $newQuantity,
                                        'quantity_type'   => 'debit',
                                        'type'            => 'OUTLET',
                                        'item_type'       => 'SKU',
                                        'created'         => date('Y-m-d H:i:s')
                                ];
                				if(!$this->Stock_ledger->saveAll($ledgerData['Stock_ledger'])){
                                    $check=false;
                                }
                                $check=true;
                            
                        }
                    
                }
                
                //modifier linking with direct sku 
                $sku_direct_products=$this->Inventory_linking->find('all',array('conditions'=>array('parent_type'=>'Modifier','parent_id'=>$modifier_id,'component_type'=>'Sku','status' =>1)));
                foreach($sku_direct_products as $sku_direct_product){
                    $sku_id=$sku_direct_product['Inventory_linking']['component_id'];
                    //sku previous stock
                    $skudirectquantity=$sku_direct_product['Inventory_linking']['quantity']*$quantity;
                    $skudetails=$this->Inventory_sku->find('first',array('conditions'=>array('id'=>$sku_id)));
                    $skuprice=$skudetails['Inventory_sku']['price'];
                    
                        
                        $ledgerprevdetails = $this->Stock_ledger->find('first', [
                            'conditions' => ['sku_id' => $sku_id,'store_id' =>$store_id ,'type' =>'OUTLET' ,'item_type'=>'SKU'],
                            'fields' => ['actual_balance'],
                            'order' => ['id DESC'],
                            'recursive' => -1
                        ]);
                        
                        $ledger_prev_quantity = !empty($ledgerprevdetails['Stock_ledger']['actual_balance']) 
                            ? $ledgerprevdetails['Stock_ledger']['actual_balance'] 
                            : 0;
                        
                        $newQuantity = $ledger_prev_quantity-$skudirectquantity;
                        
                        $ledgerData['Stock_ledger'] = [
                                'store_id'        => $store_id,
                                'sku_id'          => $sku_direct_product['Inventory_linking']['component_id'],
                                'sku_name'        => $sku_direct_product['Inventory_linking']['component_name'],
                                'sku_price'       => $skuprice,
                                'unit_id'         => $sku_direct_product['Inventory_linking']['component_unit'],
                                'unit_name'       => $sku_direct_product['Inventory_linking']['component_unit_name'],
                                'record_id'       => $txnid,
                                'record_type'     => 'stockout_modifier',
                                'quantity'        => $skudirectquantity,
                                'balance_stock'   => $newQuantity,
                                'actual_balance'  => $newQuantity,
                                'quantity_type'   => 'debit',
                                'type'            => 'OUTLET',
                                'item_type'       => 'SKU',
                                'created'         => date('Y-m-d H:i:s')
                        ];
        				if(!$this->Stock_ledger->saveAll($ledgerData['Stock_ledger'])){
                            $check=false;
                        }
                        $check=true;
                
                }
                
            }
        }
        if($check){
            $response['status']=true;
        }
        return $response;
    }
    
    public function waiter_list()
    {
        $cashierid = $_REQUEST['id'];
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $waiters = $this->Order_waiter->find('all', array('conditions'=>array('status'=>1)));
    
        if(empty($waiters))
        {
            $response =array(
                'status'=> false,
                'message'=> "Waiters Not found",
            );
            return json_encode($response);
        }else{
            foreach($waiters as $waiter){
                
                $item[]=array(
                    'id' => $waiter['Order_waiter']['id'],
                    'name' =>  $waiter['Order_waiter']['name'],
                    'phone' =>  $waiter['Order_waiter']['phone'],
                    'pin_number' =>  $waiter['Order_waiter']['pin_number'],
                    'is_pin_required' =>  $waiter['Order_waiter']['is_pin_required'],
                    'status' =>  $waiter['Order_waiter']['status'],
                );
            }
            $response= array('status'=> true,
                'message'=> "success",
                'waiters'=>$item
            );
        }
        return json_encode($response);
    }
    
    public function assign_waiter()
    {
        $response = array();
        $cashierid = $_REQUEST['id'];
        $reference_id = $_REQUEST['table_reference_id'];
        $waiter_id = $_REQUEST['waiter_id'];
        
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id Missing",
            );
            return json_encode($response);
        }
        if($reference_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Reference Id Missing",
            );
            return json_encode($response);
        }
        if($waiter_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Waiter Id Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $waiters = $this->Order_waiter->find('first', array('conditions'=>array('id'=>$waiter_id,'status'=>1)));
        if(empty($waiters))
        {
            $response =array(
                'status'=> false,
                'message'=> "Waiter Not found",
            );
            return json_encode($response);
        }
        $waiter_name = $waiters['Order_waiter']['name'];
        
        $tables = $this->Order_table->find('first', array('conditions'=>array('Order_table.reference_id'=>$reference_id,'Order_table.status'=>1)));
        if(empty($tables))
        {
            $response =array(
                'status'=> false,
                'message'=> "Table Not found or not vacant",
            );
            return json_encode($response);
        }    
        
        $this->Order_table->query("UPDATE order_tables SET waiter_id = '$waiter_id',waiter_name='$waiter_name' WHERE reference_id = '$reference_id'");
            
        $response= array('status'=> true,
            'message'=> "success",
        );
    
        return json_encode($response);
    }
    
    public function bill_preview()
    {
        $cashierid = $_REQUEST['id'];
        $ref_id=$_REQUEST['reference_id'];
        $disc=$_REQUEST['discount'];
        $sc = $_REQUEST['service_charge'];
        $type = $_REQUEST['type'];
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "User Id Missing",
            );
            return json_encode($response);
        }
        
        if($sc==''){
            $response =array(
                'status'=> false,
                'message'=> "Service Charge Missing",
            );
            return json_encode($response);
        }
        
        if($disc==''){
            $response =array(
                'status'=> false,
                'message'=> "Discount Missing",
            );
            return json_encode($response);
        }
        $todayDate = date("Y-m-d");
        
        if($type==0){
            if(!empty($disc)){
                $coup = $this->Coupon->find('first', array('conditions'=>array('Coupon.code'=>$disc,'Coupon.expiry_date >='=>$todayDate,'Coupon.status'=>1)));
                if(empty($coup))
                {
                    $response =array(
                        'status'=> false,
                        'message'=> "Coupon not found Or Coupon Expired",
                    );
                    return json_encode($response);
                }
                $disc=$coup['Coupon']['value'];
            }else{
                $disc=0;
            }
        }
        
        if($type==1){
            $disc=$disc;
        }
        
        if($type==2){
            $subtotals = $this->Order_orderhistory->query("SELECT SUM(total_price) as subtotal FROM `order_orderhistories` WHERE reference_id='$ref_id'");
            if($subtotals){
                $subtotal=$subtotals[0][0]['subtotal'];
                if($subtotal){
                    $disc=(($disc*100)/$subtotal);
                }else{
                    $response =array(
                        'status'=> false,
                        'message'=> "Bill Not Found",
                    );
                    return json_encode($response);
                }
            }else{
                $response =array(
                    'status'=> false,
                    'message'=> "Bill Not Found",
                );
                return json_encode($response);
            }
        }
        // print_r($disc);exit;
        if($disc>99){
            $response =array(
                'status'=> false,
                'message'=> "Discount is not more than 99%",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        if($disc>=0){
            $checkdiscount=$this->Order_orderhistory->find('first',array('conditions'=>array('Order_orderhistory.discount > '=>0,'Order_orderhistory.cashier_id'=>$cashierid,'Order_orderhistory.status'=>2,'Order_orderhistory.reference_id'=>$ref_id)));
            if(!empty($checkdiscount)){
                $response['status']= false;
                $response['message']= "Discount can not merge with item level discount";
                return json_encode($response);     
            }
        }else{
            $response['status']= false;
            $response['message']= "please check discount value";
            return json_encode($response);  
        }
        
        $orderdata=$this->ordercomputewithdiscount($ref_id,$cashierid,$sc,$disc);
            
        if($orderdata['status'])
        {
            $totalservicechg=$orderdata['totalservicechg'];
            $totalprice=$orderdata['totalprice'];
            $totaltax=$orderdata['totaltax'];
            $totaldiscount=$orderdata['totaldiscount'];
            $totalamount=round((($totalprice+$totaltax+$totalservicechg)-$totaldiscount),2);
            
            //print_r($totalamount);exit;
            
            $orderitems=[];
            $orderss = $this->Order_orderhistory->query("SELECT id,reference_id,group_id,cashier_id,category,category_name,kds,product_id,product_name,SUM(quantity) as quantity,price,sum(total_tax) as total_tax,sum(total_tax_percentage) as total_tax_percentage,sum(total_price) as total_price,SUM(discount) as discount,table_number,remarks,device_id,status,created FROM `order_orderhistories` WHERE reference_id='$ref_id' and status!=0 group BY product_id");
            if(!empty($orderss))
            {
                foreach($orderss as $orders){
                    if(!isset($orders['order_orderhistories']['remarks'])){
                        $orders['order_orderhistories']['remarks']='';
                    }
                    $orderitems[]=array(
                        'id' => $orders['order_orderhistories']['id'],
                        'reference_id' =>  $orders['order_orderhistories']['reference_id'],
                        'cashier_id' =>  $orders['order_orderhistories']['cashier_id'],
                        'group_id' =>  $orders['order_orderhistories']['group_id'],
                        'category' =>  $orders['order_orderhistories']['category'],
                        'category_name' =>  $orders['order_orderhistories']['category_name'],
                        'kds' =>  $orders['order_orderhistories']['kds'],
                        'product_id' =>  $orders['order_orderhistories']['product_id'],
                        'product_name' =>  $orders['order_orderhistories']['product_name'],
                        'quantity' =>  $orders[0]['quantity'],
                        'price' =>  $orders['order_orderhistories']['price'],
                        'total_tax' =>  $orders[0]['total_tax'],
                        'total_price' =>  $orders[0]['total_price'],
                        'discount' =>  $orders[0]['discount'],
                        'table_number' =>  $orders['order_orderhistories']['table_number'],
                        'remarks' =>  $orders['order_orderhistories']['remarks'],
                        'status' =>  $orders['order_orderhistories']['status'],
                        'created' =>  $orders['order_orderhistories']['created']
                    );
                }
            }
            $tablenomb=0;
            $tableno=$this->Order_table->query("SELECT number FROM `order_tables` WHERE reference_id='$ref_id'");
            if($tableno){
               $tablenomb =$tableno[0]['order_tables']['number'];
            }
            
            $finalamount=0;
            $transactionitems=[];
            $createtime = date('H:i:s');
            $transactionitems[]=array(
                'id' => '',
                'reference_id' =>  $ref_id,
                'orderno' =>  '',
                'device_id' =>  '',
                'cashier_id' =>  $cashierid,
                'table_number' =>  $tablenomb,
                'price' =>  round($totalprice),
                'total_tax' =>  round($totaltax),
                'servicecharge' =>  $totalservicechg,
                'discount' =>  $totaldiscount,
                'discount_percentage' =>  $disc,
                'delivery_charge' =>  0,
                'packing_charge' =>  0,
                'amount' =>  round($totalamount),
                'round' =>  0,
                'name' =>  '',
                'phone' =>  '',
                'address' => '',
                'remarks' =>  '',
                'status' =>  '',
                'tokenno' =>  '',
                'createtime' =>  $createtime,
                'created' =>  ''
            );
            
            $paymentitems=[];
            
            $taxitems=[];
            $taxess=$orderdata['taxes'];
            foreach($taxess as $tax){
                $taxitems[]=array(
                    'tax_id' => $tax['tax_id'],
                    'tax_name' =>  $tax['tax_name'],
                    'tax_percentage' =>  $tax['tax_percentage'],
                    'tax_value' =>  round($tax['tax_value'],1)
                );
            }
                
            $amount_diff=0;
            
            $cashier_name='';
            $cashname=$this->User->query("SELECT name FROM `users` WHERE id='$cashierid'");
            if($cashname){
               $cashier_name =$cashname[0]['users']['name'];
            }
            // print_r($cashname);exit;
            
            $printeritems=[];
            $printerss = $this->Pos_printer->query("SELECT * FROM `pos_printers` WHERE status=1");
            if(!empty($printerss))
            {
                foreach($printerss as $printers){
                    // print_r($tax);exit;
                    
                    $printeritems[]=array(
                        'id' => $printers['pos_printers']['id'],
                        'store_id' =>  $printers['pos_printers']['store_id'],
                        'name' =>  $printers['pos_printers']['name'],
                        'kds' =>  $printers['pos_printers']['kds'],
                        'ip' =>  $printers['pos_printers']['ip'],
                        'status' =>  $printers['pos_printers']['status']
                    );
                }
            }
            
            
            $response= array('status'=> true,
                'message'=> "success",
                'cashier_name'=>$cashier_name,
                'orders'=>$orderitems,
                'transactions'=>$transactionitems,
                'payments'=>$paymentitems,
                'taxes'=>$taxitems,
                'printers'=>$printeritems,
                'remaining_amount'=>number_format($amount_diff, 2, '.', '')
            );
            
            return json_encode($response);
        }else{
            $response =array(
                'status'=> false,
                'message'=> "No data found",
            );
            return json_encode($response);
        }
    }
    /*
    public function bill_generate_with_discount()
    {
        $cashierid = $_REQUEST['id'];
        $ref_id=$_REQUEST['reference_id'];
        $disc=$_REQUEST['discount'];
        $sc = $_REQUEST['service_charge'];
        $device_id = $_REQUEST['device_id'];
        $type = $_REQUEST['type'];
        $discount_type_value=$disc;
        $name='';
        if(isset($_REQUEST['name'])){
            $name=$_REQUEST['name'];
        }
        $phone='';
        if(isset($_REQUEST['phone'])){
            $phone=$_REQUEST['phone'];
        }
        $address='';
        if(isset($_REQUEST['address'])){
            $address=$_REQUEST['address'];
        }
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "User Id Missing",
            );
            return json_encode($response);
        }
        
        if($sc==''){
            $response =array(
                'status'=> false,
                'message'=> "Service Charge Missing",
            );
            return json_encode($response);
        }
        
        if($device_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Device Id Missing",
            );
            return json_encode($response);
        }
        
        if($disc==''){
            $response =array(
                'status'=> false,
                'message'=> "Discount Missing",
            );
            return json_encode($response);
        }
        $todayDate = date("Y-m-d");
        
        if($type==0){
            if(!empty($disc)){
                $coup = $this->Coupon->find('first', array('conditions'=>array('Coupon.code'=>$disc,'Coupon.expiry_date >='=>$todayDate,'Coupon.status'=>1)));
                if(empty($coup))
                {
                    $response =array(
                        'status'=> false,
                        'message'=> "Coupon not found Or Coupon Expired",
                    );
                    return json_encode($response);
                }
                $disc=$coup['Coupon']['value'];
            }else{
                $disc=0;
            }
        }
        
        if($type==1){
            $disc=$disc;
        }
        
        if($type==2){
            $subtotals = $this->Order_orderhistory->query("SELECT SUM(total_price) as subtotal FROM `order_orderhistories` WHERE reference_id='$ref_id'");
            if($subtotals){
                $subtotal=$subtotals[0][0]['subtotal'];
                if($subtotal){
                    $disc=(($disc*100)/$subtotal);
                }else{
                    $response =array(
                        'status'=> false,
                        'message'=> "Bill Not Found",
                    );
                    return json_encode($response);
                }
            }else{
                $response =array(
                    'status'=> false,
                    'message'=> "Bill Not Found",
                );
                return json_encode($response);
            }
        }
        if($disc>99){
            $response =array(
                'status'=> false,
                'message'=> "Discount is not more than 99%",
            );
            return json_encode($response);
        }
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        if($disc>=0){
            $checkdiscount=$this->Order_orderhistory->find('first',array('conditions'=>array('Order_orderhistory.discount > '=>0,'Order_orderhistory.status'=>2,'Order_orderhistory.reference_id'=>$ref_id)));
            if(!empty($checkdiscount)){
                $response['status']= false;
                $response['message']= "Discount can not merge with item level discount";
                return json_encode($response);     
            }
        }else{
            $response['status']= false;
            $response['message']= "please check discount value";
            return json_encode($response);  
        }
        $checktxnid=$this->Order_transaction->find('first',array('conditions'=>array('reference_id'=>$ref_id)));
        if(!empty($checktxnid)){
            $response['status']= false;
            $response['message']= "Reference Id Already Exist";
            return json_encode($response);     
        }
        
        $tablenomb=0;
        $tableno=$this->Order_table->query("SELECT * FROM `order_tables` WHERE reference_id='$ref_id'");
        if($tableno){
           $tablenomb =$tableno[0]['order_tables']['number'];
           $pax=$tableno[0]['order_tables']['pax'];
           $waiter_id=$tableno[0]['order_tables']['waiter_id'];
           $waiter_name=$tableno[0]['order_tables']['waiter_name'];
        }else{
            $response['status']= false;
            $response['message']= "Table Not Exist";
            return json_encode($response);     
        }
        $orderdata=$this->ordercompute($ref_id,$cashierid,$sc,$disc);
        if($orderdata['status'])
        {
            $totalservicechg=$orderdata['totalservicechg'];
            $totalprice=$orderdata['totalprice'];
            $totaltax=$orderdata['totaltax'];
            $totaldiscount=$orderdata['totaldiscount'];
            $totalamount=round((($totalprice+$totaltax+$totalservicechg)-$totaldiscount),2);
            //insert in transaction 
            $orderss = $this->Order_orderhistory->query("SELECT sum(price) as price,sum(total_tax) as total_tax,sum(total_price) as total_price,sum(discount) as discount FROM `order_orderhistories` WHERE reference_id='$ref_id' and status!=0");
            if(!empty($orderss))
            {
                $todayDate = date("Y-m-d");
                $tdaytrx=$this->Order_transaction->query("SELECT COUNT(id) as tkn FROM `order_transactions` WHERE date(created)='$todayDate' and status=2");
                $token=$tdaytrx['0']['0']['tkn']+1;
                $currenttime=date("H:i:s");
               // print_r($orderss[0][0]['total_price']+$orderss[0][0]['total_tax']-$totaldiscount);exit;
            
                $datas['Order_transaction']=array(
                    'reference_id'=>$ref_id,
                    'device_id'=>$device_id,
                    'cashier_id'=>$cashierid,
                    'price'=>$totalprice,
                    'total_tax'=>$totaltax,
                    'discount'=>$totaldiscount,
                    'discount_type' => $type,
                    'discount_type_value' =>$discount_type_value,
                    'servicecharge'=>$totalservicechg,
                    'amount'=>round($totalamount),
                    'round'=>round(round(($totalamount))-($totalamount),2),
                    'name'=>$name,
                    'phone'=>$phone,
                    'address'=>$address,
                    'tokenno'=>$token,
                    'table_number'=>$tablenomb,
                    'pax'=>$pax,
                    'waiter_id'=>$waiter_id,
                    'waiter_name'=>$waiter_name,
                    'createtime'=>$currenttime
                );
                
                if($this->Order_transaction->saveAll($datas['Order_transaction']))
                {
                    if($tablenomb!=0){
                        $this->Order_table->query("UPDATE order_tables SET status = 3 WHERE reference_id = '$ref_id'");
                    }
                    
                    $orderitems=[];
                    $orderss = $this->Order_orderhistory->query("SELECT id,reference_id,group_id,cashier_id,category,category_name,kds,product_id,product_name,SUM(quantity) as quantity,price,sum(total_tax) as total_tax,sum(total_tax_percentage) as total_tax_percentage,sum(total_price) as total_price,SUM(discount) as discount,table_number,remarks,device_id,status,created FROM `order_orderhistories` WHERE reference_id='$ref_id' and status!=0 group BY product_id");
                    if(!empty($orderss))
                    {
                        foreach($orderss as $orders){
                            if(!isset($orders['order_orderhistories']['remarks'])){
                                $orders['order_orderhistories']['remarks']='';
                            }
                            $orderitems[]=array(
                                'id' => $orders['order_orderhistories']['id'],
                                'reference_id' =>  $orders['order_orderhistories']['reference_id'],
                                'cashier_id' =>  $orders['order_orderhistories']['cashier_id'],
                                'group_id' =>  $orders['order_orderhistories']['group_id'],
                                'category' =>  $orders['order_orderhistories']['category'],
                                'category_name' =>  $orders['order_orderhistories']['category_name'],
                                'kds' =>  $orders['order_orderhistories']['kds'],
                                'product_id' =>  $orders['order_orderhistories']['product_id'],
                                'product_name' =>  $orders['order_orderhistories']['product_name'],
                                'quantity' =>  $orders[0]['quantity'],
                                'price' =>  $orders['order_orderhistories']['price'],
                                'total_tax' =>  $orders[0]['total_tax'],
                                'total_price' =>  $orders[0]['total_price'],
                                'discount' =>  $orders[0]['discount'],
                                'table_number' =>  $orders['order_orderhistories']['table_number'],
                                'remarks' =>  $orders['order_orderhistories']['remarks'],
                                'status' =>  $orders['order_orderhistories']['status'],
                                'created' =>  $orders['order_orderhistories']['created']
                            );
                        }
                    }
                    $finalamount=0;
                    $transactionitems=[];
                    $transactions = $this->Order_transaction->find('all', array('conditions'=>array('reference_id'=>$ref_id,'status !='=>0)));
                    if(!empty($transactions))
                    {
                        foreach($transactions as $orders){
                            if(!$orders['Order_transaction']['remarks']){
                                $orders['Order_transaction']['remarks']='';
                            }
                            $finalamount=$orders['Order_transaction']['amount'];
                            $cashierid=$orders['Order_transaction']['cashier_id'];
                            $reference_id=$orders['Order_transaction']['reference_id'];
                            
                            $discper = $this->Order_tax->query("SELECT discount_percentage FROM `order_tax` WHERE reference_id='$ref_id' and status=2 and discount_percentage!=0 limit 1");
                            if(!empty($discper))
                            {
                                $discount_percentage=$discper[0]['order_tax']['discount_percentage'];
                            }
                            if(!isset($discount_percentage)){
                                $discount_percentage="0";
                            }
                            
                            $transactionitems[]=array(
                                'id' => $orders['Order_transaction']['id'],
                                'reference_id' =>  $orders['Order_transaction']['reference_id'],
                                'orderno' =>  $orders['Order_transaction']['orderno'],
                                'device_id' =>  $orders['Order_transaction']['device_id'],
                                'cashier_id' =>  $orders['Order_transaction']['cashier_id'],
                                'table_number' =>  $orders['Order_transaction']['table_number'],
                                'price' =>  $orders['Order_transaction']['price'],
                                'total_tax' =>  $orders['Order_transaction']['total_tax'],
                                'servicecharge' =>  $orders['Order_transaction']['servicecharge'],
                                'discount' =>  $orders['Order_transaction']['discount'],
                                'discount_percentage' =>  $discount_percentage,
                                'discount_type' =>  $orders['Order_transaction']['discount_type'],
                                'discount_type_value' =>  $orders['Order_transaction']['discount_type_value'],
                                'delivery_charge' =>  $orders['Order_transaction']['delivery_charge'],
                                'packing_charge' =>  $orders['Order_transaction']['packing_charge'],
                                'amount' =>  $orders['Order_transaction']['amount'],
                                'round' =>  $orders['Order_transaction']['round'],
                                'name' =>  $orders['Order_transaction']['name'],
                                'phone' =>  $orders['Order_transaction']['phone'],
                                'address' =>  $orders['Order_transaction']['address'],
                                'remarks' =>  $orders['Order_transaction']['remarks'],
                                'status' =>  $orders['Order_transaction']['status'],
                                'tokenno' =>  $orders['Order_transaction']['tokenno'],
                                'createtime' =>  $orders['Order_transaction']['createtime'],
                                'created' =>  $orders['Order_transaction']['created']
                            );
                        }
                    }
                    $paymentitems=[];
                    
                    $taxitems=[];
                    $taxes = $this->Order_tax->query("SELECT tax_id,tax_name,tax_percentage,sum(tax_value) as tax_value FROM `order_tax` WHERE status!=0 and reference_id='$ref_id' GROUP by tax_id");
                    if(!empty($taxes))
                    {
                        foreach($taxes as $tax){
                            // print_r($tax);exit;
                            
                            $taxitems[]=array(
                                'tax_id' => $tax['order_tax']['tax_id'],
                                'tax_name' =>  $tax['order_tax']['tax_name'],
                                'tax_percentage' =>  $tax['order_tax']['tax_percentage'],
                                'tax_value' =>  "" .round($tax[0]['tax_value'],2)
                            );
                        }
                    }
                    $finalpayment=0;
                    $allpayments=$this->Order_payment->query("SELECT sum(amount) as pay_amount FROM `order_payments` WHERE reference_id='$ref_id'");
                    if($allpayments){
                        $finalpayment=$allpayments[0][0]['pay_amount'];
                    }
                    $amount_diff=round(($finalamount-$finalpayment),2);
                    
                    $cashier_name='';
                    $cashname=$this->User->query("SELECT name FROM `users` WHERE id='$cashierid'");
                    if($cashname){
                       $cashier_name =$cashname[0]['users']['name'];
                    }
                    // print_r($cashname);exit;
                    
                    $printeritems=[];
                    $printerss = $this->Pos_printer->query("SELECT * FROM `pos_printers` WHERE status=1");
                    if(!empty($printerss))
                    {
                        foreach($printerss as $printers){
                            // print_r($tax);exit;
                            
                            $printeritems[]=array(
                                'id' => $printers['pos_printers']['id'],
                                'store_id' =>  $printers['pos_printers']['store_id'],
                                'name' =>  $printers['pos_printers']['name'],
                                'kds' =>  $printers['pos_printers']['kds'],
                                'ip' =>  $printers['pos_printers']['ip'],
                                'status' =>  $printers['pos_printers']['status']
                            );
                        }
                    }
                    
                    
                    $response= array('status'=> true,
                        'message'=> "success",
                        'cashier_name'=>$cashier_name,
                        'orders'=>$orderitems,
                        'transactions'=>$transactionitems,
                        'payments'=>$paymentitems,
                        'taxes'=>$taxitems,
                        'printers'=>$printeritems,
                        'remaining_amount'=>number_format($amount_diff, 2, '.', '')
                    );
                }else{
                    $response =array(
                        'status'=> false,
                        'message'=> "Not generated",
                    );
                }
            }else{
                $response =array(
                    'status'=> false,
                    'message'=> "Order Not Found",
                );
            }
            return json_encode($response);
        }else{
            $response =array(
                'status'=> false,
                'message'=> "No data found",
            );
            return json_encode($response);
        }
    }
    */
    public function ordercomputewithdiscount($txnid=null,$user_id=null,$is_sc=1,$discount=0)
    {
        $response['status']=false;
        $totalservicechg=0;
        $totalprice=0;
        $totaltax1=0;
        $totaltax2=0;
        $totaldiscount=0;
        $sc=0;
        if($is_sc==1){
            $sc=servicecharge;
        }
        $discq="(((Order_orderhistory.total_price)-(Order_orderhistory.discount))*$discount/100)";
        $priceq="((Order_orderhistory.total_price)-(Order_orderhistory.discount))";
    
        $this->Order_orderhistory->virtualFields = array('tdisc'=>"SUM($discq)",'tservicechg'=>"SUM(($priceq-$discq)*($sc/100))",'tprice'=>"SUM($priceq)",'total_tax'=>"SUM(($priceq+(($priceq-$discq)*($sc/100))-$discq)*((Order_orderhistory.total_tax_percentage)/100))");  
        
        $orderhistories=$this->Order_orderhistory->find('first',array('conditions'=>array('Order_orderhistory.reference_id'=>$txnid,'status !=' =>0),'fields'=>array('tdisc','Order_orderhistory.reference_id','tprice','total_tax','tservicechg')));
        
        if(!empty($orderhistories['Order_orderhistory']['reference_id'])){
            $response['status']=true;
            $totalservicechg=round($orderhistories['Order_orderhistory']['tservicechg'],2);
            $totalprice=round($orderhistories['Order_orderhistory']['tprice'],2);
            $totaltax=round($orderhistories['Order_orderhistory']['total_tax'],2);
            $totaldiscount=round($orderhistories['Order_orderhistory']['tdisc'],2);
            
            //tax update
            $discq="(((Order_orderhistory.price)-(Order_orderhistory.discount))*$discount/100)";
            $priceq="((Order_orderhistory.price)-(Order_orderhistory.discount))";
            
            $taxes=[];
            
            $this->Order_orderhistory->virtualFields = array('tamount'=>"($priceq+(($priceq-$discq)*($sc/100))-$discq)");  
            $neworderhistories=$this->Order_orderhistory->find('all',array('conditions'=>array('Order_orderhistory.reference_id'=>$txnid,'Order_orderhistory.cashier_id'=>$user_id),'fields'=>array('Order_orderhistory.reference_id','tamount','product_id','price')));
            foreach($neworderhistories as $data){
                $reference_id=$data['Order_orderhistory']['reference_id'];
                $product_id=$data['Order_orderhistory']['product_id'];
                $tamount=$data['Order_orderhistory']['tamount'];
                $price=$data['Order_orderhistory']['price'];
                
                
                $taxitem=$this->Order_tax->find('all',array('conditions'=>array('Order_tax.reference_id'=>$txnid,'Order_tax.product_id'=>$product_id)));
                foreach($taxitem as $item){
                    $id=$item['Order_tax']['id'];
                    $tax_id=$item['Order_tax']['tax_id'];
                    $tax_percentage=$item['Order_tax']['tax_percentage'];
                    $quantity=$item['Order_tax']['quantity'];
                    $taxamount=round($tamount*$quantity,2);
                    $taxvalue=round((($tamount*$quantity*$tax_percentage)/100),2);
                    
                    if (isset($taxes[$tax_id])) {
                        $taxes[$tax_id]['tax_value'] += round($taxvalue, 2);
                    } else {
                        // Add new entry if tax_id doesn't exist
                        $taxes[$tax_id] = array(
                            'id' => $id,
                            'tax_id' =>  $item['Order_tax']['tax_id'],
                            'tax_name' => $item['Order_tax']['tax_name'],
                            'tax_percentage' => $tax_percentage,
                            'tax_value' => round($taxvalue, 2)
                        );
                    }
                }
            }
            
            $response['totalservicechg']=$totalservicechg;
            $response['totalprice']=$totalprice;
            $response['totaltax']=$totaltax;
            $response['totaldiscount']=$totaldiscount;
            $response['taxes']=$taxes;
        }
        // print_r($response);exit;
        return $response;
    }
    
    public function billupdate_discount()
    {
        $cashierid = $_REQUEST['id'];
        $ref_id=$_REQUEST['reference_id'];
        $disc=$_REQUEST['discount'];
        $sc = $_REQUEST['service_charge'];
        $device_id = $_REQUEST['device_id'];
        $type = $_REQUEST['type'];
        $table = $_REQUEST['table'];
        $discount_type_value=$disc;
        
        $name='';
        if(isset($_REQUEST['name'])){
            $name=$_REQUEST['name'];
        }
        $phone='';
        if(isset($_REQUEST['phone'])){
            $phone=$_REQUEST['phone'];
        }
        $address='';
        if(isset($_REQUEST['address'])){
            $address=$_REQUEST['address'];
        }
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "User Id Missing",
            );
            return json_encode($response);
        }
        
        if($ref_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Reference id Missing",
            );
            return json_encode($response);
        }
        
        if($disc==''){
            $response =array(
                'status'=> false,
                'message'=> "Discount Missing",
            );
            return json_encode($response);
        }
        
        
        if($sc==''){
            $response =array(
                'status'=> false,
                'message'=> "Service Charge Missing",
            );
            return json_encode($response);
        }
        
        if($device_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Device Id Missing",
            );
            return json_encode($response);
        }
        
        $todayDate = date("Y-m-d");
        
        if($type==0){
            if(!empty($disc)){
                $coup = $this->Coupon->find('first', array('conditions'=>array('Coupon.code'=>$disc,'Coupon.expiry_date >='=>$todayDate,'Coupon.status'=>1)));
                if(empty($coup))
                {
                    $response =array(
                        'status'=> false,
                        'message'=> "Coupon not found Or Coupon Expired",
                    );
                    return json_encode($response);
                }
                $disc=$coup['Coupon']['value'];
            }else{
                $disc=0;
            }
        }
        
        if($type==1){
            $disc=$disc;
        }
        
        if($type==2){
            $subtotals = $this->Order_orderhistory->query("SELECT SUM(total_price) as subtotal FROM `order_orderhistories` WHERE reference_id='$ref_id'");
            if($subtotals){
                $subtotal=$subtotals[0][0]['subtotal'];
                if($subtotal){
                    $disc=(($disc*100)/$subtotal);
                }else{
                    $response =array(
                        'status'=> false,
                        'message'=> "Bill Not Found",
                    );
                    return json_encode($response);
                }
            }else{
                $response =array(
                    'status'=> false,
                    'message'=> "Bill Not Found",
                );
                return json_encode($response);
            }
        }
        
        if($disc>99){
            $response =array(
                'status'=> false,
                'message'=> "Discount is not more than 99%",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $packagechk = $this->Order_orderhistory->find('first', array('conditions'=>array('Order_orderhistory.reference_id'=>$ref_id,'Order_orderhistory.package'=>1,'Order_orderhistory.status !='=>0)));
        if(empty($packagechk))
        {
            $response =array(
                'status'=> false,
                'message'=> "You can not Merge Discount with package.",
            );
            return json_encode($response);
        }
        
        if($disc>=0){
            $checkdiscount=$this->Order_orderhistory->find('first',array('conditions'=>array('Order_orderhistory.discount > '=>0,'Order_orderhistory.cashier_id'=>$cashierid,'Order_orderhistory.status'=>2,'Order_orderhistory.reference_id'=>$ref_id)));
            if(!empty($checkdiscount)){
                $response['status']= false;
                $response['message']= "Discount can not merge with item level discount";
                return json_encode($response);     
            }
        }else{
            $response['status']= false;
            $response['message']= "please check discount value";
            return json_encode($response);  
        }
        
        if($table){
            $tables=$this->Order_table->find('first',array('conditions'=>array('Order_table.reference_id'=>$ref_id,'Order_table.status'=>3)));
            if(empty($tables)){
                $response['status']= false;
                $response['message']= "Table is not in billing state";
                return json_encode($response);
            }
        }
        
        $txnchk = $this->Order_transaction->find('first', array('conditions'=>array('Order_transaction.reference_id'=>$ref_id, 'Order_transaction.cashier_id'=>$cashierid)));
        if(empty($txnchk))
        {
            $response= array('status'=> false,
                'message'=> "No Transaction found"
            );
            return json_encode($response);
        }
        
        $orderdata=$this->ordercompute($ref_id,$cashierid,$sc,$disc);
        
        if($orderdata['status'])
        {
            $totalservicechg=$orderdata['totalservicechg'];
            $totalprice=$orderdata['totalprice'];
            $totaltax=$orderdata['totaltax'];
            $totaldiscount=$orderdata['totaldiscount'];
            $totalamount=round((($totalprice+$totaltax+$totalservicechg)-$totaldiscount),2);
            
            $createtime = date('H:i:s');
            $this->Order_transaction->query("UPDATE `order_transactions` SET `price` = '$totalprice',`total_tax`='$totaltax',`servicecharge`='$totalservicechg',`discount`='$totaldiscount',`discount_type`='$type',`discount_type_value`='$discount_type_value',`amount`='$totalamount',`createtime`='$createtime',`name`='$name',`phone`='$phone',`address`='$address' WHERE `order_transactions`.`reference_id` = '$ref_id'");
            
            $response =array(
                'status'=> true,
                'message'=> "Saved",
            );
            return json_encode($response);
        }else{
            $response =array(
                'status'=> false,
                'message'=> "Not Saved",
            );
            return json_encode($response);
        }
    }
    
    public function sync_data()
    {
        $cashierid = $_REQUEST['id'];
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $locations = $this->User_location->query("
            SELECT location_id,id,location_name
            FROM `user_locations` 
            WHERE user_id=$cashierid AND status=1
        ");
        $all_locations=[];
        $item=[];
        foreach($locations as $location){
            $location_ids = $location['user_locations']['location_id'];
            
            $branchcategoreis = $this->Catalog_category_branches->find('all', array(
                'conditions' => array(
                    'Catalog_category_branches.location_id' => $location_ids,
                    'Catalog_category_branches.status' => 1
                )
            ));
        
            if(!empty($branchcategoreis)){
                foreach($branchcategoreis as $bracnhcategorei){
                    $branchcat_id=$bracnhcategorei['Catalog_category_branches']['category_id'];
                    $subitem=[];
                    
                    $categoreis = $this->Catalog_category->find('all', array('conditions'=>array('Catalog_category.status'=>1,'id'=>$branchcat_id)));
                    foreach($categoreis as $categorei){
                        $cat_id=$categorei['Catalog_category']['id'];
                    
                        if($categorei['Catalog_category']['is_subcategory']){
                            $subcats = $this->Catalog_subcategory->find('all', array('conditions'=>array('Catalog_subcategory.cat_id'=>$cat_id,'status'=>1)));
                            foreach($subcats as $subcat){
                                
                                $subitem[]=array(
                                    'id' => $subcat['Catalog_subcategory']['id'],
                                    'name' =>  $subcat['Catalog_subcategory']['name'],
                                    'image'=>$image,
                                    'created' =>  $subcat['Catalog_subcategory']['created']
                                );
                                
                                $branchproducts = $this->Catalog_product_branches->find('all', array('conditions'=>array('Catalog_product_branches.location_id' => $location_ids,'Catalog_product_branches.status'=>1)));
                                if(!empty($branchproducts))
                                {
                                    foreach($branchproducts as $branchproduct){
                                        $branchproduct_id=$branchproduct['Catalog_product_branches']['product_id'];
                                    
                                        $products = $this->Catalog_product->find('all', array('conditions'=>array('id'=>$branchproduct_id,'status'=>1,'subcat_id'=>$subcat['Catalog_subcategory']['id'])));
                                        if(!empty($products))
                                        {
                                            foreach($products as $product){
                                                $taxesitems=[];
                                                $taxess = $this->Catalog_product_tax->find('all', array('conditions'=>array('Catalog_product_tax.product_id'=>$product['Catalog_product']['id'])));
                                                foreach($taxess as $tax){
                                                    $taxesitems[]=array(
                                                        'tax_id' => $tax['Catalog_product_tax']['tax_id'],
                                                        'tax_name' =>  $tax['Catalog_product_tax']['tax_name'],
                                                        'tax_percentage' =>  $tax['Catalog_product_tax']['tax_percentage']
                                                    );
                                                }
                                                
                                                $groupmodifier_items = [];
                                                
                                                $modifierss = $this->Inventory_linking->find('all', [
                                                    'conditions' => [
                                                        'Inventory_linking.parent_id' => $product['Catalog_product']['id'],
                                                        'Inventory_linking.parent_type' => 'Product',
                                                        'Inventory_linking.component_type' => 'Modifier_group'
                                                    ],
                                                    'joins' => [
                                                        [
                                                            'table' => 'catalog_modifier_group',
                                                            'alias' => 'Catalog_modifier_group',
                                                            'type' => 'LEFT',
                                                            'conditions' => [
                                                                'Catalog_modifier_group.id = Inventory_linking.component_id',
                                                                'Catalog_modifier_group.status' => 1
                                                            ]
                                                        ],
                                                        [
                                                            'table' => 'inventory_linking',
                                                            'alias' => 'IL2', // Second-level linking
                                                            'type' => 'LEFT',
                                                            'conditions' => [
                                                                'IL2.parent_id = Catalog_modifier_group.id',
                                                                'IL2.parent_type' => 'Modifier_group',
                                                                'IL2.component_type' => 'Modifier',
                                                                'IL2.status' => 1
                                                            ]
                                                        ],
                                                        [
                                                            'table' => 'catalog_modifier',
                                                            'alias' => 'Catalog_modifier',
                                                            'type' => 'LEFT',
                                                            'conditions' => [
                                                                'Catalog_modifier.id = IL2.component_id',
                                                                'Catalog_modifier.status' => 1
                                                            ]
                                                        ]
                                                    ],
                                                    'fields' => [
                                                        'Inventory_linking.id',
                                                        'Inventory_linking.component_id',
                                                        'Inventory_linking.component_name',
                                                        'Inventory_linking.created',
                                                
                                                        'Catalog_modifier_group.id',
                                                        'Catalog_modifier_group.name',
                                                        'Catalog_modifier_group.description',
                                                        'Catalog_modifier_group.group_type',
                                                        'Catalog_modifier_group.sort_order',
                                                        'Catalog_modifier_group.is_default',
                                                        'Catalog_modifier_group.min',
                                                        'Catalog_modifier_group.max',
                                                
                                                        'IL2.id',
                                                        'IL2.component_id',
                                                        'IL2.component_name',
                                                
                                                        'Catalog_modifier.id',
                                                        'Catalog_modifier.name',
                                                        'Catalog_modifier.description',
                                                        'Catalog_modifier.food_type',
                                                        'Catalog_modifier.sort_order',
                                                        'Catalog_modifier.price',
                                                        'Catalog_modifier.weight'
                                                    ],
                                                    'recursive' => -1
                                                ]);
                
                                                $groupMap = [];
                                                
                                                foreach ($modifierss as $mod_item) {
                                                    $groupId = $mod_item['Inventory_linking']['component_id'];
                                                
                                                    // Initialize group if not already present
                                                    if (!isset($groupMap[$groupId])) {
                                                        $groupMap[$groupId] = [
                                                            'id' => $mod_item['Inventory_linking']['id'],
                                                            'modifier_group_id' => $groupId,
                                                            'modifier_group_name' => $mod_item['Inventory_linking']['component_name'],
                                                            'group_type' => $mod_item['Catalog_modifier_group']['group_type'],
                                                            'sort_order' => $mod_item['Catalog_modifier_group']['sort_order'],
                                                            'is_default' => $mod_item['Catalog_modifier_group']['is_default'],
                                                            'min' => $mod_item['Catalog_modifier_group']['min'],
                                                            'max' => $mod_item['Catalog_modifier_group']['max'],
                                                            'description' => $mod_item['Catalog_modifier_group']['description'],
                                                            'created' => $mod_item['Inventory_linking']['created'],
                                                            'modifiers' => []
                                                        ];
                                                    }
                                                
                                                    // Only push modifier if exists
                                                    if (!empty($mod_item['Catalog_modifier']['id'])) {
                                                        // $foodType = $mod_item['Catalog_modifier']['food_type'] == 1 ? 'Non-Veg' : 'Veg';
                                                
                                                        $modifierData = [
                                                            'id' => $mod_item['Catalog_modifier']['id'],
                                                            'name' => $mod_item['Catalog_modifier']['name'],
                                                            'modifier_name' => $mod_item['IL2']['component_name'],
                                                            'food_type' => $mod_item['Catalog_modifier']['food_type'],
                                                            'sort_order' => $mod_item['Catalog_modifier']['sort_order'],
                                                            'price' => $mod_item['Catalog_modifier']['price'],
                                                            'weight' => $mod_item['Catalog_modifier']['weight'],
                                                            'description' => $mod_item['Catalog_modifier']['description'],
                                                        ];
                                                
                                                        $groupMap[$groupId]['modifiers'][] = $modifierData;
                                                    }
                                                }
                                                // Final group array
                                                $groupmodifier_items = array_values($groupMap);
                                            
                                                if($product['Catalog_product']['image']){
                                                    $imgpth=Router::url('/', true) . DS . 'uploads' . DS . 'product_images' . DS . $product['Catalog_product']['image'];
                                                }else{
                                                    $imgpth=''; 
                                                }        
                                                // print_r($imgpth);exit;
                                                
                                                $item[]=array(
                                                    'id' => $product['Catalog_product']['id'],
                                                    'name' =>  $product['Catalog_product']['name'],
                                                    'cat_id' =>  $product['Catalog_product']['subcat_id'],
                                                    'cat_name' =>  $product['Catalog_product']['cat_name'],
                                                    'description' => $product['Catalog_product']['description'],
                                                    'food_type' =>  $product['Catalog_product']['food_type'],
                                                    'sort_order' =>  $product['Catalog_product']['sort_order'],
                                                    'recommended' =>  $product['Catalog_product']['recommended'],
                                                    'variation' =>  $product['Catalog_product']['variation'],
                                                    'price' => $product['Catalog_product']['price'],
                                                    'kds' => $product['Catalog_product']['kds'],
                                                    'markup_price' =>  $product['Catalog_product']['markup_price'],
                                                    'allergy_tags' =>  $product['Catalog_product']['allergy_tags'],
                                                    'weight' =>  $product['Catalog_product']['weight'],
                                                    'serves_people' =>  $product['Catalog_product']['serves_people'],
                                                    'type' =>  $product['Catalog_product']['type'],
                                                    'image' => $imgpth,
                                                    'taxes'=>$taxesitems,
                                                    'modifier_group'=>$groupmodifier_items,
                                                    'status' =>  $product['Catalog_product']['status'],
                                                    'created' =>  $product['Catalog_product']['created'],
                                                    'store_id' => $location_ids
                                                );
                                            }
                                        }
                                    }
                                }
                            }
                            $catitem[]=array(
                                'id' => $categorei['Catalog_category']['id'],
                                'name' =>  $categorei['Catalog_category']['name'],
                                'is_subcategory' =>  $categorei['Catalog_category']['is_subcategory'],
                                'type' =>  $categorei['Catalog_category']['type'],
                                'subcategory'=>$subitem,
                                'image'=>$image,
                                'created' =>  $categorei['Catalog_category']['created'],
                                'store_id' => $location_ids
                            );
                        }else{
                 
                            $catitem[]=array(
                                'id' => $categorei['Catalog_category']['id'],
                                'name' =>  $categorei['Catalog_category']['name'],
                                'is_subcategory' =>  $categorei['Catalog_category']['is_subcategory'],
                                'type' =>  $categorei['Catalog_category']['type'],
                                'subcategory'=>$subitem,
                                'image'=>$image,
                                'created' =>  $categorei['Catalog_category']['created'],
                                'store_id' => $location_ids
                            );
                            
                            $branchproducts = $this->Catalog_product_branches->find('all', array('conditions'=>array('Catalog_product_branches.location_id' => $location_ids,'Catalog_product_branches.status'=>1)));
                            if(!empty($branchproducts))
                            {
                                foreach($branchproducts as $branchproduct){
                                    $branchproduct_id=$branchproduct['Catalog_product_branches']['product_id'];
                            
                                    $products = $this->Catalog_product->find('all', array('conditions'=>array('Catalog_product.id'=>$branchproduct_id,'Catalog_product.status'=>1,'Catalog_product.cat_id'=>$cat_id)));
                                    if(!empty($products))
                                    {
                                        foreach($products as $product){
                                            $taxesitems=[];
                                            $taxess = $this->Catalog_product_tax->find('all', array('conditions'=>array('Catalog_product_tax.product_id'=>$product['Catalog_product']['id'])));
                                            foreach($taxess as $tax){
                                                $taxesitems[]=array(
                                                    'tax_id' => $tax['Catalog_product_tax']['tax_id'],
                                                    'tax_name' =>  $tax['Catalog_product_tax']['tax_name'],
                                                    'tax_percentage' =>  $tax['Catalog_product_tax']['tax_percentage']
                                                );
                                            }
                                        
                                        
                                            $groupmodifier_items = [];
                                            
                                            $modifierss = $this->Inventory_linking->find('all', [
                                                'conditions' => [
                                                    'Inventory_linking.parent_id' => $product['Catalog_product']['id'],
                                                    'Inventory_linking.parent_type' => 'Product',
                                                    'Inventory_linking.component_type' => 'Modifier_group'
                                                ],
                                                'joins' => [
                                                    [
                                                        'table' => 'catalog_modifier_group',
                                                        'alias' => 'Catalog_modifier_group',
                                                        'type' => 'LEFT',
                                                        'conditions' => [
                                                            'Catalog_modifier_group.id = Inventory_linking.component_id',
                                                            'Catalog_modifier_group.status' => 1
                                                        ]
                                                    ],
                                                    [
                                                        'table' => 'inventory_linking',
                                                        'alias' => 'IL2', // Second-level linking
                                                        'type' => 'LEFT',
                                                        'conditions' => [
                                                            'IL2.parent_id = Catalog_modifier_group.id',
                                                            'IL2.parent_type' => 'Modifier_group',
                                                            'IL2.component_type' => 'Modifier',
                                                            'IL2.status' => 1
                                                        ]
                                                    ],
                                                    [
                                                        'table' => 'catalog_modifier',
                                                        'alias' => 'Catalog_modifier',
                                                        'type' => 'LEFT',
                                                        'conditions' => [
                                                            'Catalog_modifier.id = IL2.component_id',
                                                            'Catalog_modifier.status' => 1
                                                        ]
                                                    ]
                                                ],
                                                'fields' => [
                                                    'Inventory_linking.id',
                                                    'Inventory_linking.component_id',
                                                    'Inventory_linking.component_name',
                                                    'Inventory_linking.created',
                                            
                                                    'Catalog_modifier_group.id',
                                                    'Catalog_modifier_group.name',
                                                    'Catalog_modifier_group.description',
                                                    'Catalog_modifier_group.group_type',
                                                    'Catalog_modifier_group.sort_order',
                                                    'Catalog_modifier_group.is_default',
                                                    'Catalog_modifier_group.min',
                                                    'Catalog_modifier_group.max',
                                            
                                                    'IL2.id',
                                                    'IL2.component_id',
                                                    'IL2.component_name',
                                            
                                                    'Catalog_modifier.id',
                                                    'Catalog_modifier.name',
                                                    'Catalog_modifier.description',
                                                    'Catalog_modifier.food_type',
                                                    'Catalog_modifier.sort_order',
                                                    'Catalog_modifier.price',
                                                    'Catalog_modifier.weight'
                                                ],
                                                'recursive' => -1
                                            ]);
                                            
                                            $groupMap = [];
                                            
                                            foreach ($modifierss as $mod_item) {
                                                $groupId = $mod_item['Inventory_linking']['component_id'];
                                                
                                                // Initialize group if not already present
                                                if (!isset($groupMap[$groupId])) {
                                                    $groupMap[$groupId] = [
                                                        'id' => $mod_item['Inventory_linking']['id'],
                                                        'modifier_group_id' => $groupId,
                                                        'modifier_group_name' => $mod_item['Inventory_linking']['component_name'],
                                                        'group_type' => $mod_item['Catalog_modifier_group']['group_type'],
                                                        'sort_order' => $mod_item['Catalog_modifier_group']['sort_order'],
                                                        'is_default' => $mod_item['Catalog_modifier_group']['is_default'],
                                                        'description' => $mod_item['Catalog_modifier_group']['description'],
                                                        'min' => $mod_item['Catalog_modifier_group']['min'],
                                                        'max' => $mod_item['Catalog_modifier_group']['max'],
                                                        'created' => $mod_item['Inventory_linking']['created'],
                                                        'modifiers' => []
                                                    ];
                                                }
                                            
                                                // Only push modifier if exists
                                                if (!empty($mod_item['Catalog_modifier']['id'])) {
                                                    $foodType = $mod_item['Catalog_modifier']['food_type'] == 1 ? 'Non-Veg' : 'Veg';
                                            
                                                    $modifierData = [
                                                        'id' => $mod_item['Catalog_modifier']['id'],
                                                        'name' => $mod_item['Catalog_modifier']['name'],
                                                        'modifier_name' => $mod_item['IL2']['component_name'],
                                                        'food_type' => $mod_item['Catalog_modifier']['food_type'],
                                                        'sort_order' => $mod_item['Catalog_modifier']['sort_order'],
                                                        'price' => $mod_item['Catalog_modifier']['price'],
                                                        'weight' => $mod_item['Catalog_modifier']['weight'],
                                                        'description' => $mod_item['Catalog_modifier']['description'],
                                                    ];
                                            
                                                    $groupMap[$groupId]['modifiers'][] = $modifierData;
                                                }
                                            }
                                            
                                            // Final group array
                                            $groupmodifier_items = array_values($groupMap);
                
                                            
                                            if($product['Catalog_product']['image']){
                                                $imgpth=Router::url('/', true) . DS . 'uploads' . DS . 'product_images' . DS . $product['Catalog_product']['image'];
                                            }else{
                                                $imgpth=''; 
                                            } 
                                            
                                            $item[]=array(
                                                'id' => $product['Catalog_product']['id'],
                                                'name' =>  $product['Catalog_product']['name'],
                                                'cat_id' =>  $product['Catalog_product']['cat_id'],
                                                'cat_name' =>  $product['Catalog_product']['cat_name'],
                                                'description' => $product['Catalog_product']['description'],
                                                'food_type' =>  $product['Catalog_product']['food_type'],
                                                'sort_order' =>  $product['Catalog_product']['sort_order'],
                                                'recommended' =>  $product['Catalog_product']['recommended'],
                                                'variation' =>  $product['Catalog_product']['variation'],
                                                'price' => $product['Catalog_product']['price'],
                                                'kds' => $product['Catalog_product']['kds'],
                                                'markup_price' =>  $product['Catalog_product']['markup_price'],
                                                'allergy_tags' =>  $product['Catalog_product']['allergy_tags'],
                                                'weight' =>  $product['Catalog_product']['weight'],
                                                'serves_people' =>  $product['Catalog_product']['serves_people'],
                                                'type' =>  $product['Catalog_product']['type'],
                                                'image' => $imgpth,
                                                'taxes'=>$taxesitems,
                                                'modifier_group'=>$groupmodifier_items,
                                                'status' =>  $product['Catalog_product']['status'],
                                                'created' =>  $product['Catalog_product']['created'],
                                                'store_id' => $location_ids
                                            );
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            
            $all_locations[]=array(
                'id' => $location['user_locations']['id'],
                'location_id' =>  $location['user_locations']['location_id'],
                'location_name' =>  $location['user_locations']['location_name']
            );
        }
        
        $printeritems=[];
        $printerss = $this->Pos_printer->query("SELECT * FROM `pos_printers` WHERE status=1");
        if(!empty($printerss))
        {
            foreach($printerss as $printers){
                // print_r($tax);exit;
                
                $printeritems[]=array(
                    'id' => $printers['pos_printers']['id'],
                    'store_id' =>  $printers['pos_printers']['store_id'],
                    'name' =>  $printers['pos_printers']['name'],
                    'kds' =>  $printers['pos_printers']['kds'],
                    'ip' =>  $printers['pos_printers']['ip'],
                    'status' =>  $printers['pos_printers']['status']
                );
            }
        }
        
        $todayDate = date("Y-m-d");
        $carditems[] = [
            'name'=>'today',
            'value'=>$todayDate
        ];
        $carditems[] = [
            'name'=>'unlimited',
            'value'=>'2030-12-31'
        ];
        $carditems[] = [
            'name'=>'custom',
            'value'=>'custom'
        ];
        
        $paymentitems[] = [
            'name'=>'cash'
        ];
        $paymentitems[] = [
            'name'=>'card'
        ];
        $paymentitems[] = [
            'name'=>'online'
        ];
        
        $response= array('status'=> true,
            'message'=> "success",
            'products'=>$item,
            'category'=>$catitem,
            'printers'=>$printeritems,
            'card_validity'=>$carditems,
            'payment_options'=>$paymentitems,
            'all_locations'=>$all_locations
        );
        return json_encode($response);
    }
    
    public function transaction_history()
    {
        $cashierid = $_REQUEST['id'];
        
        $startdate = date("Y-m-d");
        $enddate = date("Y-m-d");
            
        if(isset($_REQUEST['from'])){
            $startdate = $_REQUEST['from'];
        }
        if(isset($_REQUEST['to'])){
            $enddate = $_REQUEST['to'];
        }
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "User Id Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "Cashier not found",
            );
            return json_encode($response);
        }
        
        $transactionitems=[];
        $transactions = $this->Order_transaction->find('all', array('conditions'=>array('cashier_id'=>$cashierid,'status'=>2,'created BETWEEN ? AND ?' => array($startdate.' 00:00:01', $enddate.' 23:59:59')),'order' => array('Order_transaction.id' => 'DESC')));
        if(!empty($transactions))
        {
            foreach($transactions as $orders){
                if(!$orders['Order_transaction']['remarks']){
                    $orders['Order_transaction']['remarks']='';
                }
                $finalamount=$orders['Order_transaction']['amount'];
                $cashierid=$orders['Order_transaction']['cashier_id'];
                $reference_id=$orders['Order_transaction']['reference_id'];
                $store_id=$orders['Order_transaction']['store_id'];
                
                $discper = $this->Order_tax->query("SELECT discount_percentage FROM `order_tax` WHERE reference_id='$reference_id' and status=2 and discount_percentage!=0 limit 1");
                if(!empty($discper))
                {
                    $discount_percentage=number_format($discper[0]['order_tax']['discount_percentage'],2);
                }
                if(!isset($discount_percentage)){
                    $discount_percentage="0";
                }
                $payment_mode='';
                $pay_mode = $this->Order_payment->query("SELECT GROUP_CONCAT(type_value) as payment FROM `order_payments` WHERE reference_id='$reference_id' and store_id='$store_id' and status=2");
                if(!empty($pay_mode))
                {
                    $payment_mode=$pay_mode[0][0]['payment'];
                }
                
                $transactionitems[]=array(
                    'id' => $orders['Order_transaction']['id'],
                    'reference_id' =>  $orders['Order_transaction']['reference_id'],
                    'orderno' =>  $orders['Order_transaction']['orderno'],
                    'device_id' =>  $orders['Order_transaction']['device_id'],
                    'cashier_id' =>  $orders['Order_transaction']['cashier_id'],
                    'table_number' =>  $orders['Order_transaction']['table_number'],
                    'price' =>  $orders['Order_transaction']['price'],
                    'total_tax' =>  $orders['Order_transaction']['total_tax'],
                    'servicecharge' =>  $orders['Order_transaction']['servicecharge'],
                    'discount' =>  $orders['Order_transaction']['discount'],
                    'discount_percentage' =>  $discount_percentage,
                    'discount_type' =>  $orders['Order_transaction']['discount_type'],
                    'discount_type_value' =>  $orders['Order_transaction']['discount_type_value'],
                    'delivery_charge' =>  $orders['Order_transaction']['delivery_charge'],
                    'packing_charge' =>  $orders['Order_transaction']['packing_charge'],
                    'amount' =>  $orders['Order_transaction']['amount'],
                    'round' =>  $orders['Order_transaction']['round'],
                    'name' =>  $orders['Order_transaction']['name'],
                    'phone' =>  $orders['Order_transaction']['phone'],
                    'address' =>  $orders['Order_transaction']['address'],
                    'remarks' =>  $orders['Order_transaction']['remarks'],
                    'status' =>  $orders['Order_transaction']['status'],
                    'tokenno' =>  $orders['Order_transaction']['tokenno'],
                    'createtime' =>  $orders['Order_transaction']['createtime'],
                    'created' =>  $orders['Order_transaction']['created'],
                    'payment_mode' =>$payment_mode??''
                );
            }
        }
        
        $cashier_name='';
        $cashname=$this->User->query("SELECT name FROM `users` WHERE id='$cashierid'");
        if($cashname){
           $cashier_name =$cashname[0]['users']['name'];
        }
        
        $response= array('status'=> true,
                'message'=> "success",
                'cashier_name'=>$cashier_name,
                'transactions'=>$transactionitems
            );
        return json_encode($response);
    }
    
    public function transaction_detail()
    {
        $cashierid = $_REQUEST['id'];
        $reference_id = $_REQUEST['reference_id'];
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "User Id Missing",
            );
            return json_encode($response);
        }
        if($reference_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Reference Id Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $transactions = $this->Order_transaction->find('first', array('conditions'=>array('Order_transaction.id'=>$reference_id,'Order_transaction.status'=>2)));
        if(empty($transactions))
        {
            $response =array(
                'status'=> false,
                'message'=> "Transaction not billed",
            );
            return json_encode($response);
        }
        $transaction_reference_id=$transactions['Order_transaction']['reference_id'];
        $store_id=$transactions['Order_transaction']['store_id'];
        
        $orderitems=[];
        $orderss = $this->Order_orderhistory->query("SELECT id,reference_id,group_id,cashier_id,category,category_name,kds,product_id,product_name,SUM(quantity) as quantity,price,sum(total_tax) as total_tax,sum(total_tax_percentage) as total_tax_percentage,sum(total_price) as total_price,SUM(discount) as discount,table_number,remarks,device_id,status,created FROM `order_orderhistories` WHERE reference_id='$transaction_reference_id' and store_id='$store_id' and status!=0 group BY product_id");
        if(!empty($orderss))
        {
            foreach($orderss as $orders){
                if(!isset($orders['order_orderhistories']['remarks'])){
                    $orders['order_orderhistories']['remarks']='';
                }
                $orderitems[]=array(
                    'id' => $orders['order_orderhistories']['id'],
                    'reference_id' =>  $orders['order_orderhistories']['reference_id'],
                    'cashier_id' =>  $orders['order_orderhistories']['cashier_id'],
                    'group_id' =>  $orders['order_orderhistories']['group_id'],
                    'category' =>  $orders['order_orderhistories']['category'],
                    'category_name' =>  $orders['order_orderhistories']['category_name'],
                    'kds' =>  $orders['order_orderhistories']['kds'],
                    'product_id' =>  $orders['order_orderhistories']['product_id'],
                    'product_name' =>  $orders['order_orderhistories']['product_name'],
                    'quantity' =>  $orders[0]['quantity'],
                    'price' =>  $orders['order_orderhistories']['price'],
                    'total_tax' =>  $orders[0]['total_tax'],
                    'total_price' =>  $orders[0]['total_price'],
                    'discount' =>  $orders[0]['discount'],
                    'table_number' =>  $orders['order_orderhistories']['table_number'],
                    'remarks' =>  $orders['order_orderhistories']['remarks'],
                    'status' =>  $orders['order_orderhistories']['status'],
                    'created' =>  $orders['order_orderhistories']['created']
                );
            }
        }
        
        $cashier_name='';
        $cashname=$this->User->query("SELECT name FROM `users` WHERE id='$cashierid'");
        if($cashname){
           $cashier_name =$cashname[0]['users']['name'];
        }
        
        $response= array('status'=> true,
                'message'=> "success",
                'cashier_name'=>$cashier_name,
                'orders'=>$orderitems
            );
        return json_encode($response);
    }
    
    
    
    public function insert_manager_track()
    {
        $response['status']= false;
        $response['message']= "fail";
        
        $id = $_REQUEST['id'];
        if($id==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id is Missing",
            );
            return json_encode($response);
        }
        
        $reference_id = $_REQUEST['reference_id'];
        if($reference_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Reference Id is Missing",
            );
            return json_encode($response);
        }
        
        $pin = $_REQUEST['pin'];
        if($pin==''){
            $response =array(
                'status'=> false,
                'message'=> "Manager PIN is Missing",
            );
            return json_encode($response);
        }
        
        $type = $_REQUEST['type'];
        $remarks = $_REQUEST['remarks'];
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$id,'User.status'=>1,'User.role'=>'cashier')));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "Cashier not found",
            );
            return json_encode($response);
        }
        $location_id=$users['User']['location_id'];
        $location_name=$users['User']['location_name'];
        
        $userpinchk = $this->User->find('first', array('conditions'=>array('User.location_id'=>$location_id,'User.status'=>1,'User.role'=>'manager','User.pin'=>$pin)));
        if(empty($userpinchk))
        {
            $response =array(
                'status'=> false,
                'message'=> "Manager Pin not found for this location",
            );
            return json_encode($response);
        }
        $datas['User_track']=array(
            'user_id'=>$id,
            'reference_id'=>$reference_id,
            'location_id'=>$location_id,
            'location_name'=>$location_name,
            'type'=>$type,
            'remarks'=>$remarks
        );
        if($this->User_track->saveAll($datas['User_track']))
        {
            $response['status']= true;
            $response['message']= "Manager Track Saved Successfully..!";
        }else{
            $response['status']= false;
            $response['message']= "Manager Track not Saved..!";
        }
        return json_encode($response);
    }
    
    
    //new
    public function booked_table_list()
    {
        $cashierid = $_REQUEST['id'];
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        $tbles = $this->Order_table->find('all', array('conditions'=>array('status'=>2)));
        if(empty($tbles))
        {
            $response =array(
                'status'=> false,
                'message'=> "Tables Not found ",
            );
            return json_encode($response);
        }else{
            foreach($tbles as $tble){
                $sc=0;
                $disc=0;
                $tablereference_id=$tble['Order_table']['reference_id'];
                $item[]=array(
                    'id' => $tble['Order_table']['number'],
                    'number' =>  $tble['Order_table']['number'],
                    'reference_id' =>  $tble['Order_table']['reference_id'],
                    'is_alert' =>  $tble['Order_table']['is_alert'],
                    'is_waiter_required' =>  $tble['Order_table']['is_waiter_required'],
                    'status' =>  $tble['Order_table']['status'],
                );
            }
            $response= array('status'=> true,
                'message'=> "success",
                'tables'=>$item
            );
        }
        return json_encode($response);
    }
    
    public function merge_table()
    {
        $cashierid       = $_REQUEST['id']                ?? '';
        $main_table_id   = $_REQUEST['main_table_ref_id'] ?? '';
        $merged_table_id = $_REQUEST['merge_table_ref_id'] ?? '';
    
        if (empty($cashierid)) {
            return json_encode(['status' => false, 'message' => "Cashier Id Missing"]);
        }
        if (empty($main_table_id)) {
            return json_encode(['status' => false, 'message' => "Main Table Id Missing"]);
        }
        if (empty($merged_table_id)) {
            return json_encode(['status' => false, 'message' => "Merge Table Id Missing"]);
        }
    
        $user = $this->User->find('first', [
            'conditions' => ['User.id' => $cashierid, 'User.status' => 1],
            'fields' => ['User.id'],
            'recursive' => -1
        ]);
        if (empty($user)) {
            return json_encode(['status' => false, 'message' => "User not found"]);
        }
    
        $mainTable = $this->Order_table->find('first', [
            'conditions' => ['Order_table.reference_id' => $main_table_id, 'Order_table.status' => 2],
            'fields' => ['Order_table.id', 'Order_table.reference_id'],
            'recursive' => -1
        ]);
        if (empty($mainTable)) {
            return json_encode(['status' => false, 'message' => "Main Table Not found Or Not Booked...!"]);
        }
    
        $mergeTable = $this->Order_table->find('first', [
            'conditions' => ['Order_table.reference_id' => $merged_table_id, 'Order_table.status' => 1],
            'fields' => ['Order_table.id', 'Order_table.reference_id'],
            'recursive' => -1
        ]);
        if (empty($mergeTable)) {
            return json_encode(['status' => false, 'message' => "Merge Table Not found or table not vacant...!"]);
        }
    
        $trackingData = [
            'main_table_id'      => $mainTable['Order_table']['id'],
            'main_table_ref_id'  => $mainTable['Order_table']['reference_id'],
            'merged_table_id'    => $mergeTable['Order_table']['id'],
            'merged_table_ref_id'=> $mergeTable['Order_table']['reference_id']
        ];
    
        if ($this->Order_table_tracking->save($trackingData)) {
            $this->Order_table->updateAll(
                ['Order_table.status' => 4],
                ['Order_table.reference_id' => $merged_table_id]
            );
    
            return json_encode(['status' => true, 'message' => "Table Merged Successfully..!"]);
        }
    
        return json_encode(['status' => false, 'message' => "Table Merging not successful..!"]);
    }

    public function release_merge_table()
    {
        $cashierid = $_REQUEST['id'] ?? '';
        $merged_table_id = $_REQUEST['merge_table_ref_id'] ?? '';
    
        if (empty($cashierid)) {
            return json_encode(['status' => false, 'message' => "Cashier Id Missing"]);
        }
        if (empty($merged_table_id)) {
            return json_encode(['status' => false, 'message' => "Merge Table Id Missing"]);
        }
    
        $user = $this->User->find('first', [
            'conditions' => ['User.id' => $cashierid, 'User.status' => 1],
            'fields' => ['User.id'], // optimize field selection
            'recursive' => -1
        ]);
        if (empty($user)) {
            return json_encode(['status' => false, 'message' => "User not found"]);
        }
    
        $mergedTable = $this->Order_table->find('first', [
            'conditions' => ['Order_table.reference_id' => $merged_table_id, 'Order_table.status' => 4],
            'fields' => ['Order_table.id'],
            'recursive' => -1
        ]);
        if (empty($mergedTable)) {
            return json_encode(['status' => false, 'message' => "Merge Tables Not found"]);
        }
    
        $this->Order_table_tracking->updateAll(
            ['Order_table_tracking.status' => 0],
            ['Order_table_tracking.merged_table_ref_id' => $merged_table_id]
        );
    
        // Generate unique reference_id
        do {
            $pin = 'TX' . $cashierid . date('Y') . uniqid();
        } while ($this->Order_table->hasAny(['Order_table.reference_id' => $pin]));
    
        $this->Order_table->updateAll(
            ['Order_table.status' => 1, 'Order_table.reference_id' => "'$pin'"],
            ['Order_table.reference_id' => $merged_table_id]
        );
    
        return json_encode(['status' => true, 'message' => "Table Released Successfully..!"]);
    }
    
    public function kds_discount()
    {
        $cashierid = $_REQUEST['id'];
        $ref_id=$_REQUEST['reference_id'];
        $disc=$_REQUEST['discount'];
        $sc = $_REQUEST['service_charge'];
        $device_id = $_REQUEST['device_id'];
        $type = $_REQUEST['type'];
        $table = $_REQUEST['table'];
        $discount_type_value=$disc;
        $kds = $_REQUEST['kds'];
        
        $name='';
        if(isset($_REQUEST['name'])){
            $name=$_REQUEST['name'];
        }
        $phone='';
        if(isset($_REQUEST['phone'])){
            $phone=$_REQUEST['phone'];
        }
        $address='';
        if(isset($_REQUEST['address'])){
            $address=$_REQUEST['address'];
        }
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "User Id Missing",
            );
            return json_encode($response);
        }
        
        if($ref_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Reference id Missing",
            );
            return json_encode($response);
        }
        
        if($disc==''){
            $response =array(
                'status'=> false,
                'message'=> "Discount Missing",
            );
            return json_encode($response);
        }
        
        
        if($sc==''){
            $response =array(
                'status'=> false,
                'message'=> "Service Charge Missing",
            );
            return json_encode($response);
        }
        
        if($device_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Device Id Missing",
            );
            return json_encode($response);
        }
        if($kds==''){
            $response =array(
                'status'=> false,
                'message'=> "KDS Missing",
            );
            return json_encode($response);
        }
        
        $todayDate = date("Y-m-d");
        
        if($type==0){
            if(!empty($disc)){
                $coup = $this->Coupon->find('first', array('conditions'=>array('Coupon.code'=>$disc,'Coupon.expiry_date >='=>$todayDate,'Coupon.status'=>1)));
                if(empty($coup))
                {
                    $response =array(
                        'status'=> false,
                        'message'=> "Coupon not found Or Coupon Expired",
                    );
                    return json_encode($response);
                }
                $disc=$coup['Coupon']['value'];
            }else{
                $disc=0;
            }
        }
        
        if($type==1){
            $disc=$disc;
        }
        
        if($type==2){
            if($kds=='all'){
                $subtotals = $this->Order_orderhistory->query("SELECT SUM(total_price) as subtotal FROM `order_orderhistories` WHERE reference_id='$ref_id'");
            }else{
                $subtotals = $this->Order_orderhistory->query("SELECT SUM(total_price) as subtotal FROM `order_orderhistories` WHERE reference_id='$ref_id' and kds=$kds");
            }
            if($subtotals){
                $subtotal=$subtotals[0][0]['subtotal'];
                if($subtotal){
                    $disc=(($disc*100)/$subtotal);
                }else{
                    $response =array(
                        'status'=> false,
                        'message'=> "Bill Not Found",
                    );
                    return json_encode($response);
                }
            }else{
                $response =array(
                    'status'=> false,
                    'message'=> "Bill Not Found",
                );
                return json_encode($response);
            }
        }
        
        if($disc>99){
            $response =array(
                'status'=> false,
                'message'=> "Discount is not more than 99%",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        if($kds!='all'){
            $kdschk = $this->Pos_printer->find('first', array('conditions'=>array('Pos_printer.kds'=>$kds,'Pos_printer.status'=>1)));
            if(empty($kdschk))
            {
                $response =array(
                    'status'=> false,
                    'message'=> "KDS not found",
                );
                return json_encode($response);
            }
        }
        if($kds!='all'){
            $kdschk = $this->Order_orderhistory->find('first', array('conditions'=>array('Order_orderhistory.reference_id'=>$ref_id,'Order_orderhistory.kds'=>$kds,'Order_orderhistory.status !='=>0)));
        }else{
            $kdschk = $this->Order_orderhistory->find('first', array('conditions'=>array('Order_orderhistory.reference_id'=>$ref_id,'Order_orderhistory.status !='=>0)));
        }
        if(empty($kdschk))
        {
            $response =array(
                'status'=> false,
                'message'=> "No Item found for this KDS.",
            );
            return json_encode($response);
        }
        
        $packagechk = $this->Order_orderhistory->find('first', array('conditions'=>array('Order_orderhistory.reference_id'=>$ref_id,'Order_orderhistory.package'=>1,'Order_orderhistory.status !='=>0)));
        if(!empty($packagechk))
        {
            $response =array(
                'status'=> false,
                'message'=> "You can not Merge Discount with package.",
            );
            return json_encode($response);
        }
        
        if($disc>=0){
            $checkdiscount=$this->Order_orderhistory->find('first',array('conditions'=>array('Order_orderhistory.discount > '=>0,'Order_orderhistory.cashier_id'=>$cashierid,'Order_orderhistory.status'=>2,'Order_orderhistory.reference_id'=>$ref_id)));
            if(!empty($checkdiscount)){
                $response['status']= false;
                $response['message']= "Discount can not merge with item level discount";
                return json_encode($response);     
            }
        }else{
            $response['status']= false;
            $response['message']= "please check discount value";
            return json_encode($response);  
        }
        
        if($table){
            $tables=$this->Order_table->find('first',array('conditions'=>array('Order_table.reference_id'=>$ref_id,'Order_table.status'=>3)));
            if(empty($tables)){
                $response['status']= false;
                $response['message']= "Table is not in billing state";
                return json_encode($response);
            }
        }
        
        $txnchk = $this->Order_transaction->find('first', array('conditions'=>array('Order_transaction.reference_id'=>$ref_id, 'Order_transaction.cashier_id'=>$cashierid)));
        if(empty($txnchk))
        {
            $response= array('status'=> false,
                'message'=> "No Transaction found"
            );
            return json_encode($response);
        }
        
        if($kds=='all'){
            $orderdata=$this->ordercompute($ref_id,$cashierid,$sc,$disc);
        }else{
            $this->Order_tax->query("UPDATE order_tax SET discount_percentage='0' WHERE reference_id = '$ref_id'");
            $orderdata=$this->ordercomputewithkds($ref_id,$cashierid,$sc,$disc,$kds);
        }
        if($orderdata['status'])
        {
            $totalservicechg=$orderdata['totalservicechg'];
            $totalprice=$orderdata['totalprice'];
            $totaltax=$orderdata['totaltax'];
            $totaldiscount=$orderdata['totaldiscount'];
            $totalamount=round((($totalprice+$totaltax+$totalservicechg)-$totaldiscount),2);
            
            $createtime = date('H:i:s');
            $this->Order_transaction->query("UPDATE `order_transactions` SET `price` = '$totalprice',`total_tax`='$totaltax',`servicecharge`='$totalservicechg',`discount`='$totaldiscount',`discount_type`='$type',`discount_type_value`='$discount_type_value',`amount`='$totalamount',`createtime`='$createtime',`name`='$name',`phone`='$phone',`address`='$address' WHERE `order_transactions`.`reference_id` = '$ref_id'");
            
            $response =array(
                'status'=> true,
                'message'=> "Saved",
            );
            return json_encode($response);
        }
        
        else{
            $response =array(
                'status'=> false,
                'message'=> "Not Saved",
            );
            return json_encode($response);
        }
    }
    
    public function ordercomputewithkds($txnid=null,$user_id=null,$is_sc=1,$discount=0,$kds=0)
    {
        $response['status']=false;
        $totalservicechg=0;
        $totalprice=0;
        $totaltax1=0;
        $totaltax2=0;
        $totaldiscount=0;
        $sc=0;
        if($is_sc==1){
            $sc=servicecharge;
        }
        $alldiscount=0;
        $discq="(((Order_orderhistory.total_price)-(Order_orderhistory.discount))*$discount/100)";
        $priceq="((Order_orderhistory.total_price)-(Order_orderhistory.discount))";
    
        $this->Order_orderhistory->virtualFields = array('tdisc'=>"SUM($discq)",'tservicechg'=>"SUM(($priceq-$discq)*($sc/100))",'tprice'=>"SUM($priceq)",'total_tax'=>"SUM(($priceq+(($priceq-$discq)*($sc/100))-$discq)*((Order_orderhistory.total_tax_percentage)/100))");  
        
        $orderhistories=$this->Order_orderhistory->find('first',array('conditions'=>array('Order_orderhistory.reference_id'=>$txnid,'status !=' =>0,'kds'=>$kds),'fields'=>array('tdisc','reference_id','total_tax')));
        if(!empty($orderhistories['Order_orderhistory']['reference_id'])){
            $totaltax=round($orderhistories['Order_orderhistory']['total_tax'],2);
            $totaldiscount=round($orderhistories['Order_orderhistory']['tdisc'],2);
        }
        
                // Setup base calculations
        $discq = "(((Order_orderhistory.total_price) - (Order_orderhistory.discount)) * $alldiscount / 100)";
        $priceq = "((Order_orderhistory.total_price) - (Order_orderhistory.discount))";
        
        // Proper virtual field for total tax from items not in current KDS
        $this->Order_orderhistory->virtualFields = array(
            'total_tax_excluding_kds' => "SUM(($priceq + (($priceq - $discq) * ($sc / 100)) - $discq) * ((Order_orderhistory.total_tax_percentage) / 100))"
        );
        
        // Get total tax of items where kds != $kds
        $withoutkdsorderhistories = $this->Order_orderhistory->find('first', array(
            'conditions' => array(
                'Order_orderhistory.reference_id' => $txnid,
                'Order_orderhistory.status !=' => 0,
                'Order_orderhistory.kds !=' => $kds
            ),
            'fields' => array('Order_orderhistory.reference_id', 'Order_orderhistory.total_tax_excluding_kds'),
            'recursive' => -1
        ));
        
        // Debug output
        // print_r($withoutkdsorderhistories); exit;
        
        // Add to total tax if valid
        if (!empty($withoutkdsorderhistories['Order_orderhistory']['reference_id'])) {
            $totaltax += round($withoutkdsorderhistories['Order_orderhistory']['total_tax_excluding_kds'], 2);
        }
        
        $this->Order_orderhistory->virtualFields = array('tdisc'=>"SUM($discq)",'tservicechg'=>"SUM(($priceq-$discq)*($sc/100))",'tprice'=>"SUM($priceq)",'total_tax'=>"SUM(($priceq+(($priceq-$discq)*($sc/100))-$discq)*((Order_orderhistory.total_tax_percentage)/100))");  
        
        $orderhistories=$this->Order_orderhistory->find('first',array('conditions'=>array('Order_orderhistory.reference_id'=>$txnid,'status !=' =>0),'fields'=>array('tdisc','Order_orderhistory.reference_id','tprice','total_tax','tservicechg')));
        // print_r($orderhistories); exit;
        if(!empty($orderhistories['Order_orderhistory']['reference_id'])){
            $response['status']=true;
            $totalservicechg=round($orderhistories['Order_orderhistory']['tservicechg'],2);
            $totalprice=round($orderhistories['Order_orderhistory']['tprice'],2);
            // $totaltax=round($orderhistories['Order_orderhistory']['total_tax'],2);
            // // $totaldiscount=round($orderhistories['Order_orderhistory']['tdisc'],2);
            
            //tax update
            $alldiscq="(((Order_orderhistory.price)-(Order_orderhistory.discount))*$alldiscount/100)";
            $allpriceq="((Order_orderhistory.price)-(Order_orderhistory.discount))";
            
            $taxes=[];
            
            $this->Order_orderhistory->virtualFields = array('alltamount'=>"($priceq+(($priceq-$alldiscq)*($sc/100))-$alldiscq)");  
            $allneworderhistories=$this->Order_orderhistory->find('all',array('conditions'=>array('Order_orderhistory.reference_id'=>$txnid,'Order_orderhistory.cashier_id'=>$user_id),'fields'=>array('Order_orderhistory.reference_id','alltamount','product_id','price')));
            foreach($allneworderhistories as $data){
                $reference_id=$data['Order_orderhistory']['reference_id'];
                $product_id=$data['Order_orderhistory']['product_id'];
                $tamount=$data['Order_orderhistory']['alltamount'];
                $price=$data['Order_orderhistory']['price'];
                $taxitem=$this->Order_tax->find('all',array('conditions'=>array('Order_tax.reference_id'=>$txnid,'Order_tax.product_id'=>$product_id)));
                foreach($taxitem as $item){
                    $id=$item['Order_tax']['id'];
                    $tax_id=$item['Order_tax']['tax_id'];
                    $tax_percentage=$item['Order_tax']['tax_percentage'];
                    $quantity=$item['Order_tax']['quantity'];
                    $taxamount=round($tamount*$quantity,2);
                    $taxvalue=round((($tamount*$quantity*$tax_percentage)/100),2);
                    $this->Order_tax->query("UPDATE order_tax SET taxable_price = '$taxamount',tax_value='$taxvalue' WHERE id = '$id'");
                }
            }
            $discq="(((Order_orderhistory.price)-(Order_orderhistory.discount))*$discount/100)";
            $priceq="((Order_orderhistory.price)-(Order_orderhistory.discount))";
            
            $this->Order_orderhistory->virtualFields = array('tamount'=>"($priceq+(($priceq-$discq)*($sc/100))-$discq)");  
            $neworderhistories=$this->Order_orderhistory->find('all',array('conditions'=>array('Order_orderhistory.reference_id'=>$txnid,'Order_orderhistory.cashier_id'=>$user_id,'kds'=>$kds),'fields'=>array('Order_orderhistory.reference_id','tamount','product_id','price')));
                
            foreach($neworderhistories as $data){
                $reference_id=$data['Order_orderhistory']['reference_id'];
                $product_id=$data['Order_orderhistory']['product_id'];
                $tamount=$data['Order_orderhistory']['tamount'];
                $price=$data['Order_orderhistory']['price'];
                $taxitem=$this->Order_tax->find('all',array('conditions'=>array('Order_tax.reference_id'=>$txnid,'Order_tax.product_id'=>$product_id)));
                foreach($taxitem as $item){
                    $id=$item['Order_tax']['id'];
                    $tax_id=$item['Order_tax']['tax_id'];
                    $tax_percentage=$item['Order_tax']['tax_percentage'];
                    $quantity=$item['Order_tax']['quantity'];
                    $taxamount=round($tamount*$quantity,2);
                    $taxvalue=round((($tamount*$quantity*$tax_percentage)/100),2);
                    
                    $this->Order_tax->query("UPDATE order_tax SET taxable_price = '$taxamount',tax_value='$taxvalue' WHERE id = '$id'");
                }
                
                $taxitem=$this->Order_tax->find('all',array('conditions'=>array('Order_tax.reference_id'=>$txnid,'Order_tax.product_id'=>$product_id,'kds'=>$kds)));
                foreach($taxitem as $item){
                    $id=$item['Order_tax']['id'];
                    $tax_id=$item['Order_tax']['tax_id'];
                    $tax_percentage=$item['Order_tax']['tax_percentage'];
                    $quantity=$item['Order_tax']['quantity'];
                    $taxamount=round($tamount*$quantity,2);
                    $taxvalue=round((($tamount*$quantity*$tax_percentage)/100),2);
                    
                    $this->Order_tax->query("UPDATE order_tax SET taxable_price = '$taxamount',tax_value='$taxvalue',discount_percentage='$discount' WHERE id = '$id'");
                }
            }
            
            $response['totalservicechg']=$totalservicechg;
            $response['totalprice']=$totalprice;
            $response['totaltax']=$totaltax;
            $response['totaldiscount']=$totaldiscount;
        }
        // print_r($response);exit;
        return $response;
    }
        
    public function sync_data_to_local()
    {
        $tables = [
            'users' => 'User',
            'user_modules' => 'User_module', 
            'pos_printers' => 'Pos_printer', 
            'locations' => 'Location',       
            'catalog_category' => 'Catalog_category',
            'catalog_product' => 'Catalog_product',
            'catalog_product_addon' => 'Catalog_product_addon',
            'catalog_product_tax' => 'Catalog_product_tax',
            'catalog_subcategory' => 'Catalog_subcategory',
            'catalog_tax' => 'Catalog_tax',
            'catalog_units' => 'Catalog_unit',
            'coupons' => 'Coupon'
        ];

        foreach ($tables as $table => $modelname) {
            // Fetch unsynced data from LIVE (default) DB
            $this->$modelname->useDbConfig = 'default';
            $this->$modelname->setSource($table);
            $datas = $this->$modelname->query("SELECT * FROM $table WHERE sync = 0 ORDER BY id ASC");
    
            if ($datas) {
                foreach ($datas as $data) {
                    $user_data = $data[$table];
                    $columns = implode(", ", array_keys($user_data));
                    $escaped_values = array_map(function ($val) {
                        return "'" . addslashes($val) . "'";
                    }, array_values($user_data));
                    $values = implode(", ", $escaped_values);
    
                    $sql_local = "INSERT INTO $table ($columns) VALUES ($values) ON DUPLICATE KEY UPDATE ";
                    $update_parts = [];
                    foreach ($user_data as $column => $value) {
                        $update_parts[] = "$column = VALUES($column)";
                    }
                    $sql_local .= implode(", ", $update_parts);
    
                    // INSERT/UPDATE in local DB
                    $this->$modelname->useDbConfig = 'local_server';
                    $this->$modelname->setSource($table);
                    $insertResult = $this->$modelname->query($sql_local);
    
                    if ($insertResult !== false) {
                        // Update sync=1 in live DB
                        $this->$modelname->useDbConfig = 'default';
                        $this->$modelname->setSource($table);
                        $updatedLive = $this->$modelname->updateAll(
                            ['sync' => 1],
                            ['id' => $user_data['id']]
                        );
    
                        // Update sync=1 in local DB
                        $this->$modelname->useDbConfig = 'local_server';
                        $this->$modelname->setSource($table);
                        $updatedLocal = $this->$modelname->updateAll(
                            ['sync' => 1],
                            ['id' => $user_data['id']]
                        );
    
                        if ($updatedLive) {
                            echo "Synced & status updated for ID {$user_data['id']} in table `$table`.\n";
                        } else {
                            echo "Failed to update sync status for ID {$user_data['id']} in `$table`.\n";
                        }
                    } else {
                        echo "Failed to insert/update data for ID {$user_data['id']} in `$table`.\n";
                    }
                }
            } else {
                echo "No new data to sync for `$table`.\n";
            }
        }
    }

    public function sync_data_to_live()
    {
        $tables = [
            'users' => 'User',
            'user_modules' => 'User_module', 
            'pos_printers' => 'Pos_printer', 
            'locations' => 'Location',       
            'catalog_category' => 'Catalog_category',
            'catalog_product' => 'Catalog_product',
            'catalog_product_addon' => 'Catalog_product_addon',
            'catalog_product_tax' => 'Catalog_product_tax',
            'catalog_subcategory' => 'Catalog_subcategory',
            'catalog_tax' => 'Catalog_tax',
            'catalog_units' => 'Catalog_unit',
            'coupons' => 'Coupon'
        ];

        foreach ($tables as $table => $modelname) {
            // Fetch unsynced data from LOCAL (local_server) DB
            $this->$modelname->useDbConfig = 'local_server';
            $this->$modelname->setSource($table);
            $datas = $this->$modelname->query("SELECT * FROM $table WHERE live_sync = 0 ORDER BY id ASC");
    
            if ($datas) {
                foreach ($datas as $data) {
                    $user_data = $data[$table];
                    $columns = implode(", ", array_keys($user_data));
                    $escaped_values = array_map(function ($val) {
                        return "'" . addslashes($val) . "'";
                    }, array_values($user_data));
                    $values = implode(", ", $escaped_values);
    
                    $sql_local = "INSERT INTO $table ($columns) VALUES ($values) ON DUPLICATE KEY UPDATE ";
                    $update_parts = [];
                    foreach ($user_data as $column => $value) {
                        $update_parts[] = "$column = VALUES($column)";
                    }
                    $sql_local .= implode(", ", $update_parts);
    
                    // INSERT/UPDATE in live DB
                    $this->$modelname->useDbConfig = 'default';
                    $this->$modelname->setSource($table);
                    $insertResult = $this->$modelname->query($sql_local);
    
                    if ($insertResult !== false) {
                        // Update sync=1 in LOCAL (local_server) DB
                        $this->$modelname->useDbConfig = 'local_server';
                        $this->$modelname->setSource($table);
                        $updatedLive = $this->$modelname->updateAll(
                            ['live_sync' => 1],
                            ['id' => $user_data['id']]
                        );
    
                        // Update sync=1 in live DB
                        $this->$modelname->useDbConfig = 'default';
                        $this->$modelname->setSource($table);
                        $updatedLocal = $this->$modelname->updateAll(
                            ['live_sync' => 1],
                            ['id' => $user_data['id']]
                        );
    
                        if ($updatedLive) {
                            echo "Synced & status updated for ID {$user_data['id']} in table `$table`.\n";
                        } else {
                            echo "Failed to update sync status for ID {$user_data['id']} in `$table`.\n";
                        }
                    } else {
                        echo "Failed to insert/update data for ID {$user_data['id']} in `$table`.\n";
                    }
                }
            } else {
                echo "No new data to sync for `$table`.\n";
            }
        }
    }
    
    public function save_customer_details()
    {
        $cashierid = $_REQUEST['id'] ?? '';
        $ref_id = $_REQUEST['ref_id'] ?? '';
        $name = $_REQUEST['name'] ?? '';
        $phone = $_REQUEST['phone'] ?? '';
        $address = $_REQUEST['address'] ?? '';
        $pax = $_REQUEST['pax'] ?? 1;
    
        if (empty($cashierid)) {
            return json_encode(['status' => false, 'message' => "Cashier Id Missing"]);
        }
        if (empty($ref_id)) {
            return json_encode(['status' => false, 'message' => "Table Ref Id Missing"]);
        }
        if (empty($name)) {
            return json_encode(['status' => false, 'message' => "Customer Name Missing"]);
        }
        if (empty($phone)) {
            return json_encode(['status' => false, 'message' => "Customer Phone Missing"]);
        }
        if (empty($pax)) {
            return json_encode(['status' => false, 'message' => "PAX Missing"]);
        }
    
        $user = $this->User->find('first', [
            'conditions' => ['User.id' => $cashierid, 'User.status' => 1],
            'fields' => ['User.id'], // optimize field selection
            'recursive' => -1
        ]);
        if (empty($user)) {
            return json_encode(['status' => false, 'message' => "User not found"]);
        }
    
        $tablechk = $this->Order_table->find('first', [
            'conditions' => ['Order_table.reference_id' => $ref_id],
            'fields' => ['Order_table.id'],
            'recursive' => -1
        ]);
        if (empty($tablechk)) {
            return json_encode(['status' => false, 'message' => "Table Not found"]);
        }
    
        $this->Order_table->updateAll(
            [
                'Order_table.customer_name' => "'" . addslashes($name) . "'",
                'Order_table.customer_phone' => "'" . addslashes($phone) . "'",
                'Order_table.customer_address' => "'" . addslashes($address) . "'",
                'Order_table.customer_pax' => "'" . addslashes($pax) . "'",
            ],
            ['Order_table.reference_id' => $ref_id]
        );

    
        return json_encode(['status' => true, 'message' => "Customer Details updated Successfully..!"]);
    }
    
    public function get_customer_details()
    {
        $cashierid = $_REQUEST['id'] ?? '';
        $ref_id = $_REQUEST['ref_id'] ?? '';
    
        if (empty($cashierid)) {
            return json_encode(['status' => false, 'message' => "Cashier ID missing"]);
        }
    
        if (empty($ref_id)) {
            return json_encode(['status' => false, 'message' => "Table reference ID missing"]);
        }
    
        // Check if user exists
        $user = $this->User->find('first', [
            'conditions' => ['User.id' => $cashierid, 'User.status' => 1],
            'fields' => ['User.id'],
            'recursive' => -1
        ]);
    
        if (empty($user)) {
            return json_encode(['status' => false, 'message' => "User not found"]);
        }
    
        // Get table details
        $tablechk = $this->Order_table->find('first', [
            'conditions' => ['Order_table.reference_id' => $ref_id],
            'fields' => ['Order_table.id', 'Order_table.customer_name', 'Order_table.customer_phone', 'Order_table.customer_address', 'Order_table.customer_pax'],
            'recursive' => -1
        ]);
    
        if (empty($tablechk)) {
            return json_encode(['status' => false, 'message' => "Table not found"]);
        }
    
        $name    = trim($tablechk['Order_table']['customer_name']);
        $phone   = trim($tablechk['Order_table']['customer_phone']);
        $address = trim($tablechk['Order_table']['customer_address']);
        $customer_pax = trim($tablechk['Order_table']['customer_pax']);
    
        if (empty($name) && empty($phone) && empty($address)) {
            return json_encode(['status' => false, 'message' => "Customer details not found"]);
        }
    
    
        return json_encode([
            'status' => true,
            'message' => "Customer Found.",
            'name' => $name,
            'phone' => $phone,
            'address' => $address,
            'pax' => $customer_pax
        ]);
    }

    public function get_customer_details_by_phone()
    {
        $cashierid = $_REQUEST['id'] ?? '';
        $phone = $_REQUEST['phone'] ?? '';
    
        if (empty($cashierid)) {
            return json_encode(['status' => false, 'message' => "Cashier ID missing"]);
        }
    
        if (empty($phone)) {
            return json_encode(['status' => false, 'message' => "Phone number missing"]);
        }
    
        // Validate user
        $user = $this->User->find('first', [
            'conditions' => ['User.id' => $cashierid, 'User.status' => 1],
            'fields' => ['User.id'],
            'recursive' => -1
        ]);
    
        if (empty($user)) {
            return json_encode(['status' => false, 'message' => "User not found"]);
        }
    
        // Get customer details by phone
        $customer = $this->Order_customers->find('first', [
            'conditions' => ['Order_customers.phone' => $phone, 'status' => 1],
            'fields' => ['Order_customers.name', 'Order_customers.phone', 'Order_customers.address'],
            'recursive' => -1
        ]);
    
        if (empty($customer)) {
            return json_encode(['status' => false, 'message' => "Customer not found"]);
        }
    
        $name    = trim($customer['Order_customers']['name']);
        $address = trim($customer['Order_customers']['address']);
    
        return json_encode([
            'status' => true,
            'message' => "Customer details found.",
            'name'    => $name,
            'phone'   => $phone,
            'address' => $address
        ]);
    }
    
    //takeaway APIS
    public function create_takeaway_table()
    {
        $cashierid = $_REQUEST['id'] ?? '';
        $name = $_REQUEST['name'] ?? '';
        $phone = $_REQUEST['phone'] ?? '';
        $address = $_REQUEST['address'] ?? '';
        
        if (empty($cashierid)) {
            return json_encode(['status' => false, 'message' => "Cashier Id Missing"]);
        }
        if (empty($name)) {
            return json_encode(['status' => false, 'message' => "Customer Name Missing"]);
        }
        if (empty($phone)) {
            return json_encode(['status' => false, 'message' => "Customer Phone Missing"]);
        }
        $user = $this->User->find('first', [
            'conditions' => ['User.id' => $cashierid, 'User.status' => 1],
            'recursive' => -1
        ]);
        if (empty($user)) {
            return json_encode(['status' => false, 'message' => "User not found"]);
        }
        
        $tablechk = $this->Order_table->find('first', [
            'conditions' => ['Order_table.number' => $phone],
            'fields' => ['Order_table.id'],
            'recursive' => -1
        ]);
        if (!empty($tablechk)) {
            return json_encode(['status' => false, 'message' => "Table Already Exist"]);
        }
        
        do {
            $txnid = '';
            for ($i = 0; $i < 10; $i++) {
                $txnid .= rand(1, 9);
            }
            $existingOTP = $this->Order_transaction->find('first', array(
                'conditions' => array(
                    'reference_id' => $txnid
                )
            ));
        } while ($existingOTP); // Continue generating OTP until it doesn't exist
        
        $data['Order_table']=array(
            'number'=>$phone,
            'reference_id'=>$txnid,
            'cover_charge'=>0,
            'weekend_charge'=>0,
            'pax'=>0,
            'customer_name'=>$name,
            'customer_phone'=>$phone,
            'customer_address'=>$address,
            'location_id'=>$user['User']['location_id'],
            'location_name'=>$user['User']['location_name'],
            'is_takeaway'=>1
        );
      
        if($this->Order_table->saveAll($data['Order_table']))
        {
            $last_id = $this->Order_table->id; // ✅ last inserted ID
            
            return json_encode(['id' => $phone,'number' => $phone,'reference_id' => $txnid,'is_takeaway' => '1','status' => true, 'message' => "Customer Details updated Successfully..!"]);
        }else{
            return json_encode(['status' => false, 'message' => "Customer Details Not updated Successfully..!"]);
        }
        
    }
    
    public function takeaway_table_list()
    {
        $cashierid = $_REQUEST['id'];
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        if(isset($_REQUEST['status'])){
            $tbles = $this->Order_table->find('all', array('conditions'=>array('status'=>$_REQUEST['status'],'is_takeaway'=>1)));
        }else{
            $tbles = $this->Order_table->find('all', array('conditions'=>array('status !='=>0,'is_takeaway'=>1)));
        }
        if(empty($tbles))
        {
            $response =array(
                'status'=> false,
                'message'=> "Tables Not found ",
            );
            return json_encode($response);
        }else{
            foreach($tbles as $tble){
                $sc=0;
                $disc=0;
                $tablereference_id=$tble['Order_table']['reference_id'];
                $orderdata=$this->ordercomputewithdiscount($tablereference_id,$cashierid,$sc,$disc);
                $amount=$orderdata['totalprice'];
                
                $item[]=array(
                    'id' => $tble['Order_table']['number'],
                    'number' =>  $tble['Order_table']['number'],
                    'reference_id' =>  $tble['Order_table']['reference_id'],
                    'amount' =>  isset($amount) ? (string)$amount : "0",
                    'is_alert' =>  $tble['Order_table']['is_alert'],
                    'is_waiter_required' =>  $tble['Order_table']['is_waiter_required'],
                    'is_customer_detail_required' =>  $tble['Order_table']['is_customer_detail_required']?$tble['Order_table']['is_customer_detail_required']:"0",
                    'status' =>  $tble['Order_table']['status'],
                    'is_takeaway' =>  $tble['Order_table']['is_takeaway']
                );
            }
            $response= array('status'=> true,
                'message'=> "success",
                'tables'=>$item
            );
        }
        return json_encode($response);
    }
    
    /*
    public function takeaway_table_list()
    {
        $this->autoRender = false;
        $cashierid = $_REQUEST['id'] ?? '';
    
        if (empty($cashierid)) {
            return json_encode(['status' => false, 'message' => "Cashier Id Missing"]);
        }
    
        $user = $this->User->find('first', [
            'conditions' => ['User.id' => $cashierid, 'User.status' => 1],
            'recursive' => -1
        ]);
    
        if (empty($user)) {
            return json_encode(['status' => false, 'message' => "User not found"]);
        }
    
        $tablechk = $this->Order_table->find('all', [
            'conditions' => ['Order_table.is_takeaway' => 1],
            'recursive' => -1
        ]);
    
        if (empty($tablechk)) {
            return json_encode(['status' => false, 'message' => "No Table Found"]);
        }
    
        $items = [];
        foreach ($tablechk as $table) {
            $items[] = [
                'id' => $table['Order_table']['id'],
                'number' => $table['Order_table']['number'],
                'reference_id' => $table['Order_table']['reference_id'],
                'customer_name' => $table['Order_table']['customer_name'],
                'customer_phone' => $table['Order_table']['customer_phone'],
                'customer_address' => $table['Order_table']['customer_address'],
                'location_id' => $table['Order_table']['location_id'],
                'location_name' => $table['Order_table']['location_name'],
                'is_takeaway' => $table['Order_table']['is_takeaway'],
                'status' => $table['Order_table']['status']
            ];
        }
    
        return json_encode(['status' => true, 'message' => "Takeaway tables fetched successfully.", 'data' => $items]);
    }
    */
    //kds 
    public function kds_login()
    {
        $username = $_REQUEST['username'] ?? '';
        $password = $_REQUEST['password'] ?? '';
        
        if (empty($username)) {
            return json_encode(['status' => false, 'message' => "Username missing..!"]);
        }
        
        if (empty($password)) {
            return json_encode(['status' => false, 'message' => "Password missing..!"]);
        }
        
        $password = AuthComponent::password($password);
        
        $user = $this->Kds_user->find('first', [
            'conditions' => [
                'Kds_user.username' => $username,
                'Kds_user.password' => $password,
                'Kds_user.status' => 1
            ],
            'recursive' => 1
        ]);
        
        $stations = [];
        if (!empty($user)) {
            // $kds_stations = $this->Kds_users_station_mapping->find('all', [
            //     'conditions' => [
            //         'Kds_users_station_mapping.kds_id' => $user['Kds_user']['id'],
            //         'Kds_users_station_mapping.status' => 1
            //     ],
            //     'recursive' => 1
            // ]);
        
            // foreach ($kds_stations as $kds_station) {
            //     $stations[] = [
            //         'station_id' => $kds_station['Kds_users_station_mapping']['station_id'] ?? '',
            //         'station_name' => $kds_station['Kds_users_station_mapping']['station_name'] ?? '',
            //         'station_store_id' => $kds_station['Kds_users_station_mapping']['station_store_id'] ?? '',
            //         'station_store_name' => $kds_station['Kds_users_station_mapping']['station_store_name'] ?? '',
            //         'station_created' => $kds_station['Kds_users_station_mapping']['created'] ?? ''
            //     ];
            // }
        
            $response = [
                'status' => true,
                'message' => "Success..!",
                'id' => $user['Kds_user']['id'] ?? '',
                'username' => $user['Kds_user']['username'] ?? '',
                'role' => $user['Kds_user']['role'] ?? '',
                'location_id' => $user['Kds_user']['location_id'] ?? '',
                'location_name' => $user['Kds_user']['location_name'] ?? '',
                'user_status' => $user['Kds_user']['status'] ?? '',
                'created' => $user['Kds_user']['created'] ?? '',
                // 'stations' => $stations
            ];
        } else {
            $response = ['status' => false, 'message' => "Failed..!"];
        }
        
        return json_encode($response);
    }
    
    public function kds_listing()
    {
        $this->autoRender = false;
        $kds = $_REQUEST['station_id'] ?? '';
    
        if (empty($kds)) {
            return json_encode(['status' => false, 'message' => "KDS Id Missing"]);
        }
        
        $date = date("Y-m-d");
        if (empty($date)) {
            return json_encode(['status' => false, 'message' => "Date Missing"]);
        }
    
        $result = $this->Order_orderhistory->query("
            SELECT *,
                (SELECT waiter_name FROM order_tables WHERE reference_id = order_orderhistories.reference_id) AS waiter_name
            FROM order_orderhistories
            WHERE DATE(created) = '$date'
                AND status != 0
                
            GROUP BY reference_id, group_id
        ");
        if (empty($result)) {
            return json_encode(['status' => false, 'message' => "No Order found"]);
        }
    
        $orders = [];
    
        foreach ($result as $order) {
            $reference_id = $order['order_orderhistories']['reference_id'];
            $group_id = $order['order_orderhistories']['group_id'];
    
            $orderitems = $this->Order_orderhistory->query("
                SELECT * FROM order_orderhistories
                WHERE DATE(created) = '$date'
                    AND status != 0
                    AND reference_id = '$reference_id'
                    AND group_id = '$group_id'
            ");
        
            $items = [];
            foreach ($orderitems as $orderitem) {
                $reference_id=$orderitem['order_orderhistories']['reference_id'];
                $product_id=$orderitem['order_orderhistories']['product_id'];
                $order_id=$orderitem['order_orderhistories']['id'];
                
                $selected_modifiers=[];
                $orders_modifiers = $this->Order_modifier->query("SELECT * FROM `order_modifier` WHERE reference_id='$reference_id' and product_id='$product_id' and orderhistory_id='$order_id' and status!=0");
                foreach($orders_modifiers as $orders_modifier){
                    
                    $modifiers=$orders_modifier['order_modifier'];
                    $modifier_group_id=$modifiers['modifier_group_id'];
                    $modifier_group_name=$modifiers['modifier_group_name'];
                    $modifier_id=$modifiers['modifier_id'];
                    $modifier_name=$modifiers['modifier_name'];
                    $modifier_price=$modifiers['modifier_price'];
                    
                    $selected_modifiers[]=array(
                        'modifier_group_id' => $modifier_group_id,
                        'modifier_group_name' => $modifier_group_name,
                        'modifier_id' => $modifier_id,
                        'modifier_name' => $modifier_name,
                        'modifier_price' => $modifier_price,
                        );
                    
                }
                
                $items[] = array(
                    'order_history_id' => $orderitem['order_orderhistories']['id'],
                    'item_id'       => $orderitem['order_orderhistories']['product_id'],
                    'quantity'         => $orderitem['order_orderhistories']['quantity'],
                    'item_name'     => $orderitem['order_orderhistories']['product_name'],
                    'modifiers' => $selected_modifiers
                );
            }
    
            $orders[] = array(
                'kds_ref_id'   => $reference_id,
                'kds_group_id' => $group_id,
                'table_no'     => $order['order_orderhistories']['table_number'],
                'created'      => $order['order_orderhistories']['created'],
                'waiter_name'  => $order['order_orderhistories']['waiter_name'] ?? '',
                'kds_status'   => $order['order_orderhistories']['kds_status'],
                'items'        => $items
            );
        }
    
        return json_encode(['status' => true, 'orders' => $orders]);
    }
    
    public function kds_status_update()
    {
        $this->autoRender = false;
    
        $kds_user_id = $_REQUEST['kds_user_id'] ?? '';
        $reference_id = $_REQUEST['reference_id'] ?? '';
        $order_id = $_REQUEST['order_history_id'] ?? '';
        $status = $_REQUEST['status'] ?? '';
    
        if (empty($kds_user_id)) {
            return json_encode(['status' => false, 'message' => "KDS User Id Missing"]);
        }
        if (empty($reference_id)) {
            return json_encode(['status' => false, 'message' => "Reference Id Missing"]);
        }
        if (empty($order_id)) {
            return json_encode(['status' => false, 'message' => "Order ID Missing"]);
        }
        if (empty($status)) {
            return json_encode(['status' => false, 'message' => "Status Missing"]);
        }
    
        $user = $this->Kds_user->find('first', [
            'conditions' => [
                'Kds_user.id' => $kds_user_id,
                'Kds_user.status' => 1
            ],
            'recursive' => 1
        ]);
        if (empty($user)) {
            return json_encode(['status' => false, 'message' => "KDS user not found"]);
        }
    
        $orders = $this->Order_orderhistory->find('first', [
            'conditions' => [
                'id' => $order_id,
                'reference_id' => $reference_id
            ]
        ]);
        if (empty($orders)) {
            return json_encode(['status' => false, 'message' => "Order not found"]);
        }
    
        $data['Kds_track'][] = [
            'order_history_id'   => $order_id,
            'order_reference_id' => $reference_id,
            'kds_group_id'       => $orders['Order_orderhistory']['group_id'],
            'kds_user_id'        => $kds_user_id,
            'product_id'         => $orders['Order_orderhistory']['product_id'],
            'product_name'       => $orders['Order_orderhistory']['product_name'],
            'status'             => $status
        ];
    
        $track_id = null;
        if (empty($data['Kds_track'])) {
            return json_encode(['status' => false, 'message' => "data not found"]);
        }
        
        $this->Kds_track->create();
        $this->Kds_track->saveAll($data['Kds_track']);
        $track_id = $this->Kds_track->id; // ✅ last inserted id
        
        // Update Order_orderhistory
        $this->Order_orderhistory->updateAll(
            [
                'Order_orderhistory.kds_track_id' => "'$track_id'",
                'Order_orderhistory.kds_status'   => "'$status'"
            ],
            ['Order_orderhistory.id' => $order_id]
        );
    
        return json_encode(['status' => true, 'message' => "KDS Status Updated", 'track_id' => $track_id]);
    }

    
    /*
    public function script() {
        // Fetch all recipe links
        $subrecipes = $this->Inventory_product_semifinished_linking->query("SELECT * FROM inventory_product_semifinished_linking where status=1");
    
        foreach ($subrecipes as $recipe) {
            $product_id = $recipe['inventory_product_semifinished_linking']['product_id'];
            $product_name = $recipe['inventory_product_semifinished_linking']['product_name'];
            $semifinished_id = $recipe['inventory_product_semifinished_linking']['semifinished_id'];
            $semifinished_name = $recipe['inventory_product_semifinished_linking']['semifinished_name'];
            $semifinished_quantity = $recipe['inventory_product_semifinished_linking']['semifinished_quantity'];
            $sku_unit = $recipe['inventory_product_sku_linking']['semifinished_unit'];
            $sku_unit_name = $recipe['inventory_product_sku_linking']['semifinished_unit_name'];
            
            // Prepare new linking data
            $data['Inventory_linking'] = array(
                'parent_type' => 'Product',
                'parent_id' => $product_id,
                'parent_name' => $product_name,
                'component_type' => 'Semifinished',
                'component_id' => $semifinished_id,
                'component_name' => $semifinished_name,
                'quantity' => $semifinished_quantity,
                'component_unit'=>$sku_unit,
    			'component_unit_name'=>$sku_unit_name
            );
    
            // Save new mapping
            if (!$this->Inventory_linking->saveAll($data)) {
                
                $this->Flash->error(__('Semifinished mapping could not be saved for product ID ' . $product_id));
            }
        }
        
        // Fetch all recipe links
        $skurecipes = $this->Inventory_product_sku_linking->query("SELECT * FROM inventory_product_sku_linking where status=1");
    
        foreach ($skurecipes as $recipe) {
            $product_id = $recipe['inventory_product_sku_linking']['product_id'];
            $product_name = $recipe['inventory_product_sku_linking']['product_name'];
            $sku_id = $recipe['inventory_product_sku_linking']['sku_id'];
            $sku_name = $recipe['inventory_product_sku_linking']['sku_name'];
            $sku_quantity = $recipe['inventory_product_sku_linking']['sku_quantity'];
            $sku_unit = $recipe['inventory_product_sku_linking']['sku_unit'];
            $sku_unit_name = $recipe['inventory_product_sku_linking']['sku_unit_name'];
            
            // Prepare new linking data
            $data['Inventory_linking'] = array(
                'parent_type' => 'Product',
                'parent_id' => $product_id,
                'parent_name' => $product_name,
                'component_type' => 'Sku',
                'component_id' => $sku_id,
                'component_name' => $sku_name,
                'quantity' => $sku_quantity,
                'component_unit'=>$sku_unit,
    			'component_unit_name'=>$sku_unit_name
    		);
    
            // Save new mapping
            if (!$this->Inventory_linking->saveAll($data)) {
                $this->Flash->error(__('Semifinished mapping could not be saved for product ID ' . $product_id));
            }
        }
    
        $subtoskurecipes = $this->Inventory_semifinished_sku_linking->query("SELECT * FROM inventory_semifinished_sku_linking where status=1");
    
        foreach ($subtoskurecipes as $recipe) {
            $product_id = $recipe['inventory_semifinished_sku_linking']['semifinished_id'];
            $product_name = $recipe['inventory_semifinished_sku_linking']['semifinished_name'];
            $semifinished_id = $recipe['inventory_semifinished_sku_linking']['sku_id'];
            $semifinished_name = $recipe['inventory_semifinished_sku_linking']['sku_name'];
            $semifinished_quantity = $recipe['inventory_semifinished_sku_linking']['sku_quantity'];
            $sku_unit = $recipe['inventory_semifinished_sku_linking']['sku_unit'];
            $sku_unit_name = $recipe['inventory_semifinished_sku_linking']['sku_unit_name'];
            
            
            // Prepare new linking data
            $data['Inventory_linking'] = array(
                'parent_type' => 'Semifinished',
                'parent_id' => $product_id,
                'parent_name' => $product_name,
                'component_type' => 'Sku',
                'component_id' => $semifinished_id,
                'component_name' => $semifinished_name,
                'quantity' => $semifinished_quantity,
                'component_unit'=>$sku_unit,
    			'component_unit_name'=>$sku_unit_name
            );
    
            // Save new mapping
            if (!$this->Inventory_linking->saveAll($data)) {
                $this->Flash->error(__('Semifinished mapping could not be saved for product ID ' . $product_id));
            }
        }
        
        $subtoskurecipes = $this->Inventory_semifinished_semifinished_linking->query("SELECT * FROM inventory_semifinished_semifinished_linking where status=1");
    
        foreach ($subtoskurecipes as $recipe) {
            $product_id = $recipe['inventory_semifinished_semifinished_linking']['semifinished_id'];
            $product_name = $recipe['inventory_semifinished_semifinished_linking']['semifinished_name'];
            $semifinished_id = $recipe['inventory_semifinished_semifinished_linking']['linked_semifinished_id'];
            $semifinished_name = $recipe['inventory_semifinished_semifinished_linking']['linked_semifinished_name'];
            $semifinished_quantity = $recipe['inventory_semifinished_semifinished_linking']['linked_semifinished_quantity'];
            $sku_unit = $recipe['inventory_semifinished_semifinished_linking']['linked_semifinished_unit'];
            $sku_unit_name = $recipe['inventory_semifinished_semifinished_linking']['linked_semifinished_unit_name'];
            
            // Delete only Semifinished mappings for this product
            
            // Prepare new linking data
            $data['Inventory_linking'] = array(
                'parent_type' => 'Semifinished',
                'parent_id' => $product_id,
                'parent_name' => $product_name,
                'component_type' => 'Semifinished',
                'component_id' => $semifinished_id,
                'component_name' => $semifinished_name,
                'quantity' => $semifinished_quantity,
                'component_unit'=>$sku_unit,
    			'component_unit_name'=>$sku_unit_name
            );
    
            // Save new mapping
            if (!$this->Inventory_linking->saveAll($data)) {
                $this->Flash->error(__('Semifinished mapping could not be saved for product ID ' . $product_id));
            }
        }
        
        $modtosubrecipes = $this->Inventory_modifier_semifinished_linking->query("SELECT * FROM inventory_modifier_semifinished_linking where status=1");
    
        foreach ($modtosubrecipes as $recipe) {
            $product_id = $recipe['inventory_modifier_semifinished_linking']['modifier_id'];
            $product_name = $recipe['inventory_modifier_semifinished_linking']['modifier_name'];
            $semifinished_id = $recipe['inventory_modifier_semifinished_linking']['semifinished_id'];
            $semifinished_name = $recipe['inventory_modifier_semifinished_linking']['semifinished_name'];
            $semifinished_quantity = $recipe['inventory_modifier_semifinished_linking']['semifinished_quantity'];
            $sku_unit = $recipe['inventory_modifier_semifinished_linking']['semifinished_unit'];
            $sku_unit_name = $recipe['inventory_modifier_semifinished_linking']['semifinished_unit_name'];
            
            
            // Prepare new linking data
            $data['Inventory_linking'] = array(
                'parent_type' => 'Modifier',
                'parent_id' => $product_id,
                'parent_name' => $product_name,
                'component_type' => 'Semifinished',
                'component_id' => $semifinished_id,
                'component_name' => $semifinished_name,
                'quantity' => $semifinished_quantity,
                'component_unit'=>$sku_unit,
    			'component_unit_name'=>$sku_unit_name
            );
    
            // Save new mapping
            if (!$this->Inventory_linking->saveAll($data)) {
                $this->Flash->error(__('Semifinished mapping could not be saved for product ID ' . $product_id));
            }
        }
        
        $modtoskubrecipes = $this->Inventory_modifier_sku_linking->query("SELECT * FROM inventory_modifier_sku_linking where status=1");
    
        foreach ($modtoskubrecipes as $recipe) {
            $product_id = $recipe['inventory_modifier_sku_linking']['modifier_id'];
            $product_name = $recipe['inventory_modifier_sku_linking']['modifier_name'];
            $semifinished_id = $recipe['inventory_modifier_sku_linking']['sku_id'];
            $semifinished_name = $recipe['inventory_modifier_sku_linking']['sku_name'];
            $semifinished_quantity = $recipe['inventory_modifier_sku_linking']['sku_quantity'];
            $sku_unit = $recipe['inventory_modifier_sku_linking']['sku_unit'];
            $sku_unit_name = $recipe['inventory_modifier_sku_linking']['sku_unit_name'];
            
            
            // Prepare new linking data
            $data['Inventory_linking'] = array(
                'parent_type' => 'Modifier',
                'parent_id' => $product_id,
                'parent_name' => $product_name,
                'component_type' => 'Sku',
                'component_id' => $semifinished_id,
                'component_name' => $semifinished_name,
                'quantity' => $semifinished_quantity,
                'component_unit'=>$sku_unit,
    			'component_unit_name'=>$sku_unit_name
            );
    
            // Save new mapping
            if (!$this->Inventory_linking->saveAll($data)) {
                $this->Flash->error(__('Semifinished mapping could not be saved for product ID ' . $product_id));
            }
        }
        
        $gmodtomodrecipes = $this->Catalog_modifier_group_linkings->query("SELECT * FROM catalog_modifier_group_linkings where status=1");
    
        foreach ($gmodtomodrecipes as $recipe) {
            $product_id = $recipe['catalog_modifier_group_linkings']['group_id'];
            $product_name = $recipe['catalog_modifier_group_linkings']['group_name'];
            $semifinished_id = $recipe['catalog_modifier_group_linkings']['modifier_id'];
            $semifinished_name = $recipe['catalog_modifier_group_linkings']['modifier_name'];
            $semifinished_quantity = 1;
            
           
            // Prepare new linking data
            $data['Inventory_linking'] = array(
                'parent_type' => 'Modifier_group',
                'parent_id' => $product_id,
                'parent_name' => $product_name,
                'component_type' => 'Modifier',
                'component_id' => $semifinished_id,
                'component_name' => $semifinished_name,
                'quantity' => $semifinished_quantity
            );
    
            // Save new mapping
            if (!$this->Inventory_linking->saveAll($data)) {
                $this->Flash->error(__('Semifinished mapping could not be saved for product ID ' . $product_id));
            }
        }
        
        $protomodbrecipes = $this->Catalog_product_modifier_group_linkings->query("SELECT * FROM catalog_product_modifier_group_linkings where status=1");
    
        foreach ($protomodbrecipes as $recipe) {
            $product_id = $recipe['catalog_product_modifier_group_linkings']['product_id'];
            $product_name = $recipe['catalog_product_modifier_group_linkings']['product_name'];
            $semifinished_id = $recipe['catalog_product_modifier_group_linkings']['modifier_group_id'];
            $semifinished_name = $recipe['catalog_product_modifier_group_linkings']['modifier_group_name'];
            $semifinished_quantity = 1;
            
            
            // Prepare new linking data
            $data['Inventory_linking'] = array(
                'parent_type' => 'Product',
                'parent_id' => $product_id,
                'parent_name' => $product_name,
                'component_type' => 'Modifier_group',
                'component_id' => $semifinished_id,
                'component_name' => $semifinished_name,
                'quantity' => $semifinished_quantity
            );
    
            // Save new mapping
            if (!$this->Inventory_linking->saveAll($data)) {
                $this->Flash->error(__('Semifinished mapping could not be saved for product ID ' . $product_id));
            }
        }
        
        $this->Flash->success(__('All semifinished product mappings have been updated.'));
    }
    */
    
    public function online_order_accept()
    {
        //cashier id ,refernce id ,txn table check
        $cashierid = $_REQUEST['id'];
        $reference_id = $_REQUEST['reference_id'];
        
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "User Id Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "Cashier not found",
            );
            return json_encode($response);
        }
        
        if($reference_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Reference Id Missing",
            );
            return json_encode($response);
        }
        $transactions = $this->Order_transaction->find('first', array('conditions'=>array('Order_transaction.reference_id'=>$reference_id)));
        if(!empty($transactions))
        {
            $response =array(
                'status'=> false,
                'message'=> "Order already accepted",
            );
            return json_encode($response);
        }
        
        // Get all unprocessed online orders
        $webhooks = $this->Online_order->find('all', [
            'conditions' => ['Online_order.reference_id' => $reference_id]
        ]);
    
        foreach ($webhooks as $webhook) {
            $remarks = [];
            $data = [];
    
            $response = json_decode($webhook['Online_order']['response']);
            $txnid = $webhook['Online_order']['reference_id'];
    
            if (empty($response->order->items)) {
                $remarks[] = "Missing order items for txn $txnid";
                continue;
            }
            $items = $response->order->items;
            $details = $response->order->details;
            $store = $response->store;
            $payments = $response->order->payment ?? [];
    // print_r($response);exit;
            $deliverydatetime = date("Y-m-d H:i:s", $details->delivery_datetime / 1000);
    
            // Initialize totals
            $total_tax_value = 0;
            $total_pack_charge = 0;
    
            if (!empty($details->charges)) {
                foreach ($details->charges as $char) {
                    $title = strtolower($char->title);
                    if ($title === 'packaging charge' || $title === 'restaurant packaging charges') {
                        $total_pack_charge += $char->value;
                        foreach ($char->taxes as $char_taxes) {
                            $total_pack_taxes += $char_taxes->value;
                        }
                    }
                }
            }
            
            // Process each item
            $total_amount=0;
            foreach ($items as $item) {
                $item_tax_value = 0;
                $item_tax_rate = 0;
    
                // Sum item taxes
                if (!empty($item->taxes)) {
                    foreach ($item->taxes as $tax) {
                        $item_tax_value += $tax->value;
                        $item_tax_rate += $tax->rate;
                    }
                }
                $total_tax_value += $item_tax_value;
    
                // Total price per item after discount
                // $ttlprice = ($item->price * $item->quantity) - ($item->discount ?? 0);
                $ttlprice = ($item->price * $item->quantity) - ($item->discount ?? 0);
                $total_amount += $ttlprice;
                
                // Save order history
                $orderHistoryData = [
                    'reference_id'         => $txnid,
                    'cashier_id'           => $cashierid,
                    'category'             => $item->category->id?$item->category->id:0,
                    'category_name'        => $item->category->name?$item->category->name:'',
                    'product_id'           => $item->merchant_id?$item->merchant_id:0,
                    'product_name'         => $item->title?$item->title:'',
                    'quantity'             => $item->quantity?$item->quantity:0,
                    'price'                => $item->price?$item->price:0,
                    'total_tax'            => 0,
                    'total_tax_percentage' => 0,
                    'total_price'          => $ttlprice?$ttlprice:0,
                    'discount'             => $item->discount ?? 0,
                    'status'               => 2
                ];
                $this->Order_orderhistory->create();
                $this->Order_orderhistory->save($orderHistoryData);
                $lastorder_id = $this->Order_orderhistory->getLastInsertID();

                
                // Save taxes per item
                $discount_percentage= ( $item->discount * 100 ) / $item->price ;
                // Save taxes per item
                
                $ordertaxData = [
                    'orderhistory_id' => $lastorder_id, // Fill after saving order history if needed
                    'cashier_id'      => $cashierid,
                    'product_id'      => $item->merchant_id ?? 0,
                    'product_name'    => $item->title ?? '',
                    'price'           => $item->price ?? 0,
                    'taxable_price'   => $ttlprice ?? 0,
                    'cat_id'          => $item->category->id ?? 0,
                    'cat_name'        => $item->category->name ?? '',
                    'discount_percentage' => round($discount_percentage,2),
                    'quantity'        => $item->quantity ?? 0,
                    'tax_id'          => 0,
                    'tax_name'        => 'Online',
                    'tax_percentage'  => 0,
                    'tax_value'       => 0,
                    'reference_id'    => $txnid ?? 0,
                    'status'          => 2
                ];
                $this->Order_tax->create();
                $this->Order_tax->save($ordertaxData);
            }
                
            $currenttime = date("H:i:s", $details->delivery_datetime / 1000);
            
            $finalamount = round($total_amount);        
            $round_amount = round($total_amount,2)-round($total_amount);
        
            $todayDate = date("Y-m-d");
            $tdaytrx=$this->Order_transaction->query("SELECT COUNT(id) as tkn FROM `order_transactions` WHERE date(created)='$todayDate' and cashier_id='$cashierid'");
            $token=$tdaytrx['0']['0']['tkn']+1;
            
            $deliveryother=0;
			$deliveryother=round((($details->total_charges)-$total_pack_charge),2);

            // Save transaction
            $data['Order_transaction'][] = [
                    'reference_id'=>$txnid,
                    'cashier_id'=>$cashierid,
                    'price'=>$details->order_subtotal ?? 0,
                    'total_tax'=> 0,
                    'other_taxes'=>$total_pack_taxes ?? 0,
                    'discount'=>$details->discount ?? 0,
                    'discount_type'=>2,
                    'discount_type_value'=>$details->discount ?? 0,
                    'amount'=>round($total_amount ?? 0),
                    'round'=>round($round_amount,2),
                    'delivery_charge'=>$deliveryother ?? 0,
				    'packing_charge' => $total_pack_charge ?? 0,
                    'name' => $response->customer->name ?? '',
                    'phone' => $response->customer->phone ?? '',
                    'address' => $response->customer->address->city ?? '',
                    'createtime'=>$currenttime,
                    'token'=>$token,
                    'payment_mode'=>$response->order->details->channel,
                    'status'           => 2
                ];
            
            if (!empty($data['Order_transaction'])) {
                $this->Order_transaction->saveAll($data['Order_transaction']);
            }
            
            // Save payments
            if (!empty($payments)) {
                foreach ($payments as $payment) {
                    $data['Order_payment'][] = [
                        'reference_id' => $txnid,
                        'cashier_id'   =>  $cashierid,
                        'type'         => '9', // Map your payment type
                        'type_value'   => $details->channel ?? '',
                        'amount'       => round($total_amount) ?? 0,
                        'remarks'      => $payment->option ?? '' ,
                        'status'       => 2
                    ];
                }
            }
            
            
            if (!empty($data['Order_payment'])) {
                $this->Order_payment->saveAll($data['Order_payment']);
            }
            $this->Online_order->updateAll(
                [
                    'Online_order.status' => 1,      // new status value
                    'Online_order.cron_run' => 1     // set cron_run
                ],
                [
                    'Online_order.id' => $webhook['Online_order']['id']
                ]
            );

            
            $response =array(
                'status'=> true,
                'message'=> "Order accepted",
            );
            return json_encode($response);
        }
    }
    
    public function online_order_transaction_history()
    {
        // fetch according to store id 
        $cashierid = isset($_REQUEST['id']) ? $_REQUEST['id'] : '';
    
        $startdate = isset($_REQUEST['from']) ? $_REQUEST['from'] : date("Y-m-d");
        $enddate   = isset($_REQUEST['to'])   ? $_REQUEST['to']   : date("Y-m-d");
    
        if ($cashierid == '') {
            return json_encode([
                'status'  => false,
                'message' => "User Id Missing",
            ], JSON_UNESCAPED_UNICODE);
        }
    
        $users = $this->User->find('first', [
            'conditions' => [
                'User.id'     => $cashierid,
                'User.status' => 1
            ]
        ]);
    
        if (empty($users)) {
            return json_encode([
                'status'  => false,
                'message' => "Cashier not found",
            ], JSON_UNESCAPED_UNICODE);
        }
    
        $store_id = $users['User']['location_id'];
        $transactionitems = [];
    
        $transactions = $this->Online_order->find('all', [
            'conditions' => [
                'store_id' => $store_id,
                'created BETWEEN ? AND ?' => [
                    $startdate . ' 00:00:01',
                    $enddate . ' 23:59:59'
                ]
            ],
            'order' => ['Online_order.id' => 'DESC']
        ]);
    
        if (!empty($transactions)) {
            foreach ($transactions as $orders) {
                $total_pack_charge = 0;
    
                $finalamount   = $orders['Online_order']['total_amount'];
                $cashier_id    = $orders['Online_order']['cashier_id'];
                $reference_id  = $orders['Online_order']['reference_id'];
                $response      = $orders['Online_order']['response'];
                $response_res  = json_decode($response, true);
    
                if (json_last_error() !== JSON_ERROR_NONE) {
                    // skip invalid json responses
                    continue;
                }
    
                // packaging charges
                if (!empty($response_res['order']['details']['charges'])) {
                    foreach ($response_res['order']['details']['charges'] as $char) {
                        $title = strtolower($char['title']);
                        if ($title === 'packaging charge' || $title === 'restaurant packaging charges') {
                            $total_pack_charge += $char['value'];
                        }
                    }
                }
    
                // timestamps
                $delivery_ts = isset($response_res['order']['details']['delivery_datetime'])
                    ? intval($response_res['order']['details']['delivery_datetime']) / 1000
                    : time();
    
                $currenttime     = date("H:i:s", $delivery_ts);
                $currenttimedate = date("Y-m-d H:i:s", $delivery_ts);
    
                // auto token number
                $todayDate = date("Y-m-d");
                $tdaytrx = $this->Order_transaction->query("SELECT COUNT(id) as tkn FROM `order_transactions` WHERE date(created)='$todayDate'");
                $token = isset($tdaytrx[0][0]['tkn']) ? $tdaytrx[0][0]['tkn'] + 1 : 1;
    
                // round values
                $finalamount = round($orders['Online_order']['total_amount']);
                $round_amount = $finalamount - $orders['Online_order']['total_amount'];
    
                $transactionitems[] = [
                    'id'                => $orders['Online_order']['id'],
                    'reference_id'      => $reference_id,
                    'orderno'           => $orders['Online_order']['order_id'],
                    'device_id'         => '0',
                    'cashier_id'        => $cashier_id??'0',
                    'table_number'      => '0',
                    'price'             => $orders['Online_order']['total_price'] ?? '0',
                    'total_tax'         => $orders['Online_order']['total_taxes'] ?? '0',
                    'servicecharge'     => '0',
                    'discount'          => isset($response_res['order']['details']['discount']) ? strval($response_res['order']['details']['discount']) : "0",
                    'discount_percentage' => '0',
                    'discount_type'     => '2',
                    'discount_type_value' => 'Flat',
                    'delivery_charge'   => '0',
                    'packing_charge'    => strval($total_pack_charge) ?? '0',
                    'amount'            => strval($finalamount) ?? '0',
                    'round'             => number_format($round_amount, 2, '.', ''), 
                    'name'              => $response_res['customer']['name'] ?? '',
                    'phone'             => $response_res['customer']['phone'] ?? '',
                    'address'           => $response_res['customer']['address']['city'] ?? '',
                    'remarks'           => $orders['Online_order']['remarks'] ?? '',
                    'status'            => strval($orders['Online_order']['status']),
                    'tokenno'           => "$token",
                    'createtime'        => $currenttime,
                    'created'           => $currenttimedate,
                    'payment_mode'      => $response_res['order']['details']['channel'] ?? ''
                ];
            }
        }
    
        // cashier name
        $cashier_name = '';
        $cashname = $this->User->query("SELECT name FROM `users` WHERE id='$cashierid'");
        if ($cashname && isset($cashname[0]['users']['name'])) {
            $cashier_name = $cashname[0]['users']['name'];
        }
    
        $response = [
            'status'       => true,
            'message'      => "success",
            'cashier_name' => $cashier_name,
            'transactions' => $transactionitems
        ];
    
        return json_encode($response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    }
    
    public function online_order_food_ready()
    {
        $cashierid = $_REQUEST['id'];
        $reference_id = $_REQUEST['reference_id'];
    
        if ($cashierid == '') {
            return json_encode([
                'status' => false,
                'message' => "User Id Missing",
            ]);
        }
    
        $users = $this->User->find('first', [
            'conditions' => ['User.id' => $cashierid, 'User.status' => 1]
        ]);
        if (empty($users)) {
            return json_encode([
                'status' => false,
                'message' => "Cashier not found",
            ]);
        }
    
        if ($reference_id == '') {
            return json_encode([
                'status' => false,
                'message' => "Reference Id Missing",
            ]);
        }
    
        $store_id = $users['User']['location_id'];
    
        // Get order
        $webhook = $this->Online_order->find('first', [
            'conditions' => [
                'Online_order.store_id' => $store_id,
                'Online_order.reference_id' => $reference_id,
                'Online_order.status' => 1
            ]
        ]);
    
        if (!$webhook) {
            return json_encode([
                'status' => false,
                'message' => "Order not found",
            ]);
        }
        
        $orderno = $webhook['Online_order']['order_id'];
        $orderstatus1 = "Food Ready";
        $message1 = "Food packed at restaurant";
    
        $upresponse = $this->order_status_change($orderno, $orderstatus1, $message1);
        $chkresponse = json_decode($upresponse, true);
    
        if (!empty($chkresponse['status']) && $chkresponse['status'] == true) {
            $response = [
                'status' => true,
                'message' => "Your request to food ready is submitted."
            ];
        } else {
            $response = [
                'status' => false,
                'message' => "uperror: " . ($chkresponse['message'] ?? 'Unknown error')
            ];
        }
    
        return json_encode($response, JSON_UNESCAPED_UNICODE);
    }

    function order_status_change($orderno=null,$status=null,$message=null)
	{
		$response=array();
		$response['status']=false;
		$response['message']="fail";
		$retry_attempt=0;
	
		$this->Limit->useDbConfig = 'urban';
		
		$data=array('new_status'=>$status,'message'=>$message);
		$data_post = json_encode($data);
		//$url="http://unclejacksindia.com/testing_setup/Urbanpiper/error_up";
		$url="https://api.urbanpiper.com/external/api/v1/orders/$orderno/status/";
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data_post);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: apikey biz_adm_JfXhyVCnFTqD:fcc7319afeb58eb0852648f45eec78902079931e','Content-Type:application/json'));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"PUT");
		$output = curl_exec($ch);
		$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		if (curl_errno($ch)) {
			$error = curl_error($ch);
			$response['message']=$error;
			die(json_encode($response));
		}
		curl_close($ch);
		if($httpcode>=500)
		{
			$error['status']="error";
			$error['message']=$httpcode." error";
			$output=json_encode($error);
		}

		if($httpcode==401)
		{
			$error['status']="error";
			$error['message']=$httpcode." error";
			$output=json_encode($error);
		}
			
		$result=json_decode($output,true);
		if(!empty($result) && $result['status']=='success')
		{
			$response['status']=true;
			$response['message']=$result['message'];
		}else{
	    	$response['message']=$result['message'];
		}
		return json_encode($response);
	}
	
    public function online_order_cancelled()
    {
        $cashierid = $_REQUEST['id'];
        $reference_id = $_REQUEST['reference_id'];
        $current_state = $_REQUEST['status_code'];
    
        if ($cashierid == '') {
            return json_encode([
                'status' => false,
                'message' => "User Id Missing",
            ]);
        }
    
        $users = $this->User->find('first', [
            'conditions' => ['User.id' => $cashierid, 'User.status' => 1]
        ]);
        if (empty($users)) {
            return json_encode([
                'status' => false,
                'message' => "Cashier not found",
            ]);
        }
    
        if ($reference_id == '') {
            return json_encode([
                'status' => false,
                'message' => "Reference Id Missing",
            ]);
        }
        
        if ($current_state == '') {
            return json_encode([
                'status' => false,
                'message' => "Status Missing",
            ]);
        }
    
        $store_id = $users['User']['location_id'];
    
        // Get order
        $webhook = $this->Online_order->find('first', [
            'conditions' => [
                'Online_order.store_id' => $store_id,
                'Online_order.reference_id' => $reference_id,
                'Online_order.status' => 0
            ]
        ]);
    
        if (empty($webhook)) {
            return json_encode([
                'status' => false,
                'message' => "Order action already processed/ Order Not Found!d",
            ]);
        }
        
        $order_status=5;
        $possuccess = $this->pos_status_update(
            $existing['Online_order']['reference_id']
        );
        
        $success = $this->Online_order->updateAll(
            [
                'Online_order.status'   => 5
            ],
            ['Online_order.reference_id' => $webhook['Online_order']['reference_id']]
        );
        
        switch ($current_state) {
			case 'item_out_of_stock':
			$orderstatus1="Cancelled";
			$message1="item_out_of_stock";
			$upresponse=$this->order_status_change($orderno,$orderstatus1,$message1);
        	break;	
			case 'store_closed':
			$orderstatus1="Cancelled";
			$message1="store_closed";
			$upresponse=$this->order_status_change($orderno,$orderstatus1,$message1);
        	break;	
			case 'store_busy':
			$orderstatus1="Cancelled";
			$message1="store_busy";
			$upresponse=$this->order_status_change($orderno,$orderstatus1,$message1);
        	break;
			case 'rider_not_available':
			$orderstatus1="Cancelled";
			$message1="rider_not_available";
			$upresponse=$this->order_status_change($orderno,$orderstatus1,$message1);
        	break;
			case 'out_of_delivery_radius':
			$orderstatus1="Cancelled";
			$message1="out_of_delivery_radius";
			$upresponse=$this->order_status_change($orderno,$orderstatus1,$message1);
        	break;
        	case 'connectivity_issue':
			$orderstatus1="Cancelled";
			$message1="connectivity_issue";
			$upresponse=$this->order_status_change($orderno,$orderstatus1,$message1);
        	break;
        	case 'total_missmatch':
			$orderstatus1="Cancelled";
			$message1="total_missmatch";
			$upresponse=$this->order_status_change($orderno,$orderstatus1,$message1);
        	break;
        	case 'invalid_item':
			$orderstatus1="Cancelled";
			$message1="invalid_item";
			$upresponse=$this->order_status_change($orderno,$orderstatus1,$message1);
        	break;
        	case 'option_out_of_stock':
			$orderstatus1="Cancelled";
			$message1="option_out_of_stock";
			$upresponse=$this->order_status_change($orderno,$orderstatus1,$message1);
        	break;
        	case 'invalid_option':
			$orderstatus1="Cancelled";
			$message1="invalid_option";
			$upresponse=$this->order_status_change($orderno,$orderstatus1,$message1);
        	break;
        	case 'unspecified':
			$orderstatus1="Cancelled";
			$message1="unspecified";
			$upresponse=$this->order_status_change($orderno,$orderstatus1,$message1);
        	break;
        	
		}
		$chkresponse=json_decode($upresponse,true);
		if($chkresponse['status'])
		{
			$response['status']=true;
    		$response['message']="You are request to cancel order is submitted. It may take 5-10 minutes to complete.";
		}else{
			$response['status']=true;
    		$response['message']=$chkresponse['message'];
		}
		
        return json_encode($response, JSON_UNESCAPED_UNICODE);
    }
    
    public function pos_status_update($reference_id)
    {
        $success = true;
    
        // Update Order_orderhistory
        if (!$this->Order_orderhistory->updateAll(
            ['Order_orderhistory.status' => 0],
            ['Order_orderhistory.reference_id' => $reference_id]
        )) {
            $success = false;
        }
    
        // Update Order_tax
        if (!$this->Order_tax->updateAll(
            ['Order_tax.status' => 0],
            ['Order_tax.reference_id' => $reference_id]
        )) {
            $success = false;
        }
    
        // Update Order_transaction
        if (!$this->Order_transaction->updateAll(
            ['Order_transaction.status' => 0],
            ['Order_transaction.reference_id' => $reference_id]
        )) {
            $success = false;
        }
    
        // Update Order_payments
        if (!$this->Order_payment->updateAll(
            ['Order_payment.status' => 0],
            ['Order_payment.reference_id' => $reference_id]
        )) {
            $success = false;
        }
    
        return $success;
    }
    
    public function online_order_notify()
    {
        $cashierid = $_REQUEST['id'];
        
        if ($cashierid == '') {
            return json_encode([
                'status' => false,
                'message' => "User Id Missing",
            ]);
        }
    
        $users = $this->User->find('first', [
            'conditions' => ['User.id' => $cashierid, 'User.status' => 1]
        ]);
        if (empty($users)) {
            return json_encode([
                'status' => false,
                'message' => "Cashier not found",
            ]);
        }
    
        if ($reference_id == '') {
            return json_encode([
                'status' => false,
                'message' => "Reference Id Missing",
            ]);
        }
    
        $store_id = $users['User']['location_id'];
    
        // Get order
        $webhook = $this->Online_order->find('first', [
            'conditions' => [
                'Online_order.store_id' => $store_id,
                'Online_order.notify' => 0,
                'Online_order.status' => 0
            ]
        ]);
    
        $success = $this->Online_order->updateAll(
            [
                'Online_order.notify'   => 1
            ],
            ['Online_order.reference_id' => $webhook['Online_order']['reference_id']]
        );
        
        $response['status']=true;
		$response['title']="New Order Arrived!";
		$response['message']="Please Check!";
		
        return json_encode($response, JSON_UNESCAPED_UNICODE);
    }

    public function online_order_transaction_detail()
    {
        $cashierid = $_REQUEST['id'];
        $reference_id = $_REQUEST['reference_id'];
        
        if (empty($cashierid)) {
            return json_encode(['status' => false, 'message' => "User Id Missing"]);
        }
        if (empty($reference_id)) {
            return json_encode(['status' => false, 'message' => "Reference Id Missing"]);
        }
    
        $users = $this->User->find('first', ['conditions' => ['User.id' => $cashierid, 'User.status' => 1]]);
        if (empty($users)) {
            return json_encode(['status' => false, 'message' => "User not found"]);
        }
    
        $webhooks = $this->Online_order->find('all', ['conditions' => ['Online_order.reference_id' => $reference_id]]);
        
        $orderitems = [];
        $remarks = [];
        $total_tax_value = 0;
    
        foreach ($webhooks as $webhook) {
            $response = json_decode($webhook['Online_order']['response']);
            $txnid = $webhook['Online_order']['reference_id'];
    
            if (empty($response->order->items)) {
                return json_encode(['status' => false, 'message' => "Missing order items for txn $txnid"]);
            }
            
            $delivery_ts = isset($response->order->details->delivery_datetime)
                ? intval($response->order->details->delivery_datetime) / 1000
                : time();

            $currenttime     = date("H:i:s", $delivery_ts);
            $currenttimedate = date("Y-m-d H:i:s", $delivery_ts);
            
            
            foreach ($response->order->items as $item) {
                $item_tax_value = 0;
                $item_tax_rate = 0;
    
                if (!empty($item->taxes)) {
                    foreach ($item->taxes as $tax) {
                        $item_tax_value += $tax->value;
                        $item_tax_rate += $tax->rate;
                    }
                }
                $total_tax_value += $item_tax_value;
    
                $ttlprice = ($item->price * $item->quantity) - ($item->discount ?? 0);
                // timestamps
                
                $orderitems[] = [
                    'id'                   => '',
                    'reference_id'         => $txnid,
                    'cashier_id'           => '',
                    'group_id'             => '',
                    'category'             => isset($item->category->merchant_id) ? $item->category->merchant_id : '0',
                    'category_name'        => isset($item->category->name) ? $item->category->name : '',
                    'kds'                  => '',
                    'product_id'           => $item->merchant_id ?? '0',
                    'product_name'         => $item->title ?? '',
                    'quantity'             => strval($item->quantity) ?? '0',
                    'price'                => strval($item->price) ?? '0',
                    'total_tax'            => number_format(round($item_tax_value,2),2),
                    'total_tax_percentage' => strval($item_tax_rate),
                    'total_price'          => strval($ttlprice),
                    'discount'             => strval($item->discount) ?? '0',
                    'table_number'         => '0',
                    'remarks'              => '',
                    'status'               => '2',
                    'created'              =>  $currenttimedate
                ];
            }
        }
    
        return json_encode([
            'status'      => true,
            'message'     => "success",
            'cashier_name'=> '',
            'orders'      => $orderitems
        ]);
    }

    //kds
    
    public function reprint_data()
    {
        $cashierid = $_REQUEST['id'];
        $reference_id = $_REQUEST['reference_id'];
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "User Id Missing",
            );
            return json_encode($response);
        }
        if($reference_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Reference Id Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        $orderitems=[];
        $orderss = $this->Order_orderhistory->query("SELECT * FROM `order_orderhistories` WHERE reference_id='$reference_id' and status!=0");
        // print_r("SELECT id,reference_id,group_id,cashier_id,category,category_name,product_id,product_name,SUM(quantity) as quantity,sum(price) as price,sum(total_tax) as total_tax,sum(total_tax_percentage) as total_tax_percentage,sum(total_price) as total_price,SUM(discount) as discount FROM `order_orderhistories` WHERE reference_id='$reference_id' and status!=0 group BY product_id");exit;
        if(!empty($orderss))
        {
            
            foreach($orderss as $orders){
                $product_id=$orders['order_orderhistories']['product_id'];
                $order_id=$orders['order_orderhistories']['id'];
                $selected_modifiers=[];
                $orders_modifiers = $this->Order_modifier->query("SELECT * FROM `order_modifier` WHERE reference_id='$reference_id' and product_id='$product_id' and orderhistory_id='$order_id' and status!=0");
                foreach($orders_modifiers as $orders_modifier){
                    
                    $modifiers=$orders_modifier['order_modifier'];
                    $modifier_group_id=$modifiers['modifier_group_id'];
                    $modifier_group_name=$modifiers['modifier_group_name'];
                    $modifier_id=$modifiers['modifier_id'];
                    $modifier_name=$modifiers['modifier_name'];
                    $modifier_price=$modifiers['modifier_price'];
                    
                    $selected_modifiers[]=array(
                        'modifier_group_id' => $modifier_group_id,
                        'modifier_group_name' => $modifier_group_name,
                        'modifier_id' => $modifier_id,
                        'modifier_name' => $modifier_name,
                        'modifier_price' => $modifier_price,
                        );
                    
                }
                
                if(!isset($orders['order_orderhistories']['remarks'])){
                    $orders['order_orderhistories']['remarks']='';
                }
                $orderitems[]=array(
                    'id' => $orders['order_orderhistories']['id'],
                    'reference_id' =>  $orders['order_orderhistories']['reference_id'],
                    'cashier_id' =>  $orders['order_orderhistories']['cashier_id'],
                    'group_id' =>  $orders['order_orderhistories']['group_id'],
                    'category' =>  $orders['order_orderhistories']['category'],
                    'category_name' =>  $orders['order_orderhistories']['category_name'],
                    'kds' =>  $orders['order_orderhistories']['kds'],
                    'product_id' =>  $orders['order_orderhistories']['product_id'],
                    'product_name' =>  $orders['order_orderhistories']['product_name'],
                    'quantity' =>  $orders['order_orderhistories']['quantity'],
                    'price' =>  $orders['order_orderhistories']['price'],
                    'total_tax' =>  $orders['order_orderhistories']['total_tax'],
                    'total_price' =>  $orders['order_orderhistories']['total_price'],
                    'discount' =>  $orders['order_orderhistories']['discount'],
                    'table_number' =>  $orders['order_orderhistories']['table_number'],
                    'remarks' =>  $orders['order_orderhistories']['remarks'],
                    'selected_modifiers' => $selected_modifiers,
                    'status' =>  $orders['order_orderhistories']['status'],
                    'created' =>  $orders['order_orderhistories']['created']
                );
            }
        }
        $finalamount=0;
        $transactionitems=[];
        $transactions = $this->Order_transaction->find('all', array('conditions'=>array('reference_id'=>$reference_id,'status !='=>0)));
        if(!empty($transactions))
        {
            foreach($transactions as $orders){
                if(!$orders['Order_transaction']['remarks']){
                    $orders['Order_transaction']['remarks']='';
                }
                $finalamount=$orders['Order_transaction']['amount'];
                $cashierid=$orders['Order_transaction']['cashier_id'];
                $reference_id=$orders['Order_transaction']['reference_id'];
                
                $discper = $this->Order_tax->query("SELECT discount_percentage FROM `order_tax` WHERE reference_id='$reference_id' and status=2 and discount_percentage!=0 limit 1");
                if(!empty($discper))
                {
                    $discount_percentage=number_format($discper[0]['order_tax']['discount_percentage'],2);
                }
                if(!isset($discount_percentage)){
                    $discount_percentage="0";
                }
                
                $transactionitems[]=array(
                    'id' => $orders['Order_transaction']['id'],
                    'reference_id' =>  $orders['Order_transaction']['reference_id'],
                    'orderno' =>  $orders['Order_transaction']['orderno'],
                    'device_id' =>  $orders['Order_transaction']['device_id'],
                    'cashier_id' =>  $orders['Order_transaction']['cashier_id'],
                    'table_number' =>  $orders['Order_transaction']['table_number'],
                    'price' =>  $orders['Order_transaction']['price'],
                    'total_tax' =>  $orders['Order_transaction']['total_tax'],
                    'servicecharge' =>  $orders['Order_transaction']['servicecharge'],
                    'discount' =>  $orders['Order_transaction']['discount'],
                    'discount_percentage' =>  $discount_percentage,
                    'discount_type' =>  $orders['Order_transaction']['discount_type'],
                    'discount_type_value' =>  $orders['Order_transaction']['discount_type_value'],
                    'delivery_charge' =>  $orders['Order_transaction']['delivery_charge'],
                    'packing_charge' =>  $orders['Order_transaction']['packing_charge'],
                    'amount' =>  $orders['Order_transaction']['amount'],
                    'round' =>  $orders['Order_transaction']['round'],
                    'name' =>  $orders['Order_transaction']['name'],
                    'phone' =>  $orders['Order_transaction']['phone'],
                    'address' =>  $orders['Order_transaction']['address'],
                    'remarks' =>  $orders['Order_transaction']['remarks'],
                    'status' =>  $orders['Order_transaction']['status'],
                    'tokenno' =>  $orders['Order_transaction']['tokenno'],
                    'createtime' =>  $orders['Order_transaction']['createtime'],
                    'created' =>  $orders['Order_transaction']['created']
                );
            }
        }
        $paymentitems=[];
        $payments = $this->Order_payment->find('all', array('conditions'=>array('reference_id'=>$reference_id,'status !='=>0)));
        if(!empty($payments))
        {
            foreach($payments as $orders){
                if(!isset($orders['Order_payment']['remarks'])){
                    $orders['Order_payment']['remarks']='';
                }
                $paymentitems[]=array(
                    'id' => $orders['Order_payment']['id'],
                    'reference_id' =>  $orders['Order_payment']['reference_id'],
                    'cashier_id' =>  $orders['Order_payment']['cashier_id'],
                    'type' =>  $orders['Order_payment']['type'],
                    'type_value' =>  $orders['Order_payment']['type_value'],
                    'amount' =>  $orders['Order_payment']['amount'],
                    'status' =>  $orders['Order_payment']['status'],
                    'remarks' =>  $orders['Order_payment']['remarks'],
                    'created' =>  $orders['Order_payment']['created']
                );
            }
        }
        $taxitems=[];
        $taxes = $this->Order_tax->query("SELECT tax_id,tax_name,tax_percentage,sum(tax_value) as tax_value FROM `order_tax` WHERE reference_id='$reference_id' and status!=0 GROUP by tax_id");
        if(!empty($taxes))
        {
            foreach($taxes as $tax){
                // print_r($tax);exit;
                
                $taxitems[]=array(
                    'tax_id' => $tax['order_tax']['tax_id'],
                    'tax_name' =>  $tax['order_tax']['tax_name'],
                    'tax_percentage' =>  $tax['order_tax']['tax_percentage'],
                    'tax_value' =>  "" .round($tax[0]['tax_value'],2)
                );
            }
        }
        $finalpayment=0;
        $allpayments=$this->Order_payment->query("SELECT sum(amount) as pay_amount FROM `order_payments` WHERE reference_id='$reference_id'");
        if($allpayments){
            $finalpayment=$allpayments[0][0]['pay_amount'];
        }
        $amount_diff=round(($finalamount-$finalpayment),2);
        
        $cashier_name='';
        $cashname=$this->User->query("SELECT name FROM `users` WHERE id='$cashierid'");
        if($cashname){
           $cashier_name =$cashname[0]['users']['name'];
        }
        // print_r($cashname);exit;
        
        $printeritems=[];
        $printerss = $this->Pos_printer->query("SELECT * FROM `pos_printers` WHERE status=1");
        if(!empty($printerss))
        {
            foreach($printerss as $printers){
                // print_r($tax);exit;
                
                $printeritems[]=array(
                    'id' => $printers['pos_printers']['id'],
                    'store_id' =>  $printers['pos_printers']['store_id'],
                    'name' =>  $printers['pos_printers']['name'],
                    'kds' =>  $printers['pos_printers']['kds'],
                    'ip' =>  $printers['pos_printers']['ip'],
                    'status' =>  $printers['pos_printers']['status']
                );
            }
        }
        
        $response= array('status'=> true,
                'message'=> "success",
                'cashier_name'=>$cashier_name,
                'orders'=>$orderitems,
                'transactions'=>$transactionitems,
                'payments'=>$paymentitems,
                'taxes'=>$taxitems,
                'printers'=>$printeritems,
                'remaining_amount'=>number_format($amount_diff, 2, '.', '')
            );
        return json_encode($response);
    }
    
    public function reprint_data_multistore()
    {
        $cashierid = $_REQUEST['id'];
        $reference_id = $_REQUEST['reference_id'];
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "User Id Missing",
            );
            return json_encode($response);
        }
        if($reference_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Reference Id Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        $orderitems=[];
        $orderss = $this->Order_orderhistory->query("SELECT * FROM `order_orderhistories` WHERE reference_id='$reference_id' and status!=0");
        // print_r("SELECT id,reference_id,group_id,cashier_id,category,category_name,product_id,product_name,SUM(quantity) as quantity,sum(price) as price,sum(total_tax) as total_tax,sum(total_tax_percentage) as total_tax_percentage,sum(total_price) as total_price,SUM(discount) as discount FROM `order_orderhistories` WHERE reference_id='$reference_id' and status!=0 group BY product_id");exit;
        if(!empty($orderss))
        {
            
            foreach($orderss as $orders){
                $product_id=$orders['order_orderhistories']['product_id'];
                $order_id=$orders['order_orderhistories']['id'];
                $selected_modifiers=[];
                $orders_modifiers = $this->Order_modifier->query("SELECT * FROM `order_modifier` WHERE reference_id='$reference_id' and product_id='$product_id' and orderhistory_id='$order_id' and status!=0");
                foreach($orders_modifiers as $orders_modifier){
                    
                    $modifiers=$orders_modifier['order_modifier'];
                    $modifier_group_id=$modifiers['modifier_group_id'];
                    $modifier_group_name=$modifiers['modifier_group_name'];
                    $modifier_id=$modifiers['modifier_id'];
                    $modifier_name=$modifiers['modifier_name'];
                    $modifier_price=$modifiers['modifier_price'];
                    
                    $selected_modifiers[]=array(
                        'modifier_group_id' => $modifier_group_id,
                        'modifier_group_name' => $modifier_group_name,
                        'modifier_id' => $modifier_id,
                        'modifier_name' => $modifier_name,
                        'modifier_price' => $modifier_price,
                        );
                    
                }
                
                if(!isset($orders['order_orderhistories']['remarks'])){
                    $orders['order_orderhistories']['remarks']='';
                }
                $orderitems[]=array(
                    'id' => $orders['order_orderhistories']['id'],
                    'reference_id' =>  $orders['order_orderhistories']['reference_id'],
                    'cashier_id' =>  $orders['order_orderhistories']['cashier_id'],
                    'group_id' =>  $orders['order_orderhistories']['group_id'],
                    'category' =>  $orders['order_orderhistories']['category'],
                    'category_name' =>  $orders['order_orderhistories']['category_name'],
                    'kds' =>  $orders['order_orderhistories']['kds'],
                    'product_id' =>  $orders['order_orderhistories']['product_id'],
                    'product_name' =>  $orders['order_orderhistories']['product_name'],
                    'quantity' =>  $orders['order_orderhistories']['quantity'],
                    'price' =>  $orders['order_orderhistories']['price'],
                    'total_tax' =>  $orders['order_orderhistories']['total_tax'],
                    'total_price' =>  $orders['order_orderhistories']['total_price'],
                    'discount' =>  $orders['order_orderhistories']['discount'],
                    'table_number' =>  $orders['order_orderhistories']['table_number'],
                    'remarks' =>  $orders['order_orderhistories']['remarks'],
                    'selected_modifiers' => $selected_modifiers,
                    'status' =>  $orders['order_orderhistories']['status'],
                    'created' =>  $orders['order_orderhistories']['created']
                );
            }
        }
        $finalamount=0;
        $transactionitems=[];
        $transactions = $this->Order_transaction->query(
            "SELECT GROUP_CONCAT(id) as id,reference_id,GROUP_CONCAT(orderno) as orderno,device_id,cashier_id,table_number,
            SUM(price) as price,SUM(total_tax) as total_tax,SUM(servicecharge) as servicecharge,SUM(discount) as discount,
            SUM(discount_type_value) as discount_type_value,SUM(delivery_charge) as delivery_charge,SUM(packing_charge) as packing_charge,
            SUM(amount) as amount,SUM(round) as round,discount_type ,name,phone,address,GROUP_CONCAT(remarks) as remarks,status,GROUP_CONCAT(tokenno) as tokenno,
            createtime,created FROM `order_transactions` WHERE reference_id='$reference_id' and status!=0");
        
        if(!empty($transactions))
        {
            foreach($transactions as $orders){
                
                if(!$orders[0]['remarks']){
                    $orders[0]['remarks']='';
                }
                $finalamount=$orders[0]['amount'];
                $cashierid=$orders[0]['cashier_id'];
                $reference_id=$orders['order_transactions']['reference_id'];
                
                $discper = $this->Order_tax->query("SELECT SUM(discount_percentage) as discount_percentage FROM `order_tax` WHERE reference_id='$reference_id' and status=2 and discount_percentage!=0");
                if(!empty($discper))
                {
                    $discount_percentage=number_format($discper[0][0]['discount_percentage'],2);
                }
                if(!isset($discount_percentage)){
                    $discount_percentage="0";
                }
                
                $transactionitems[]=array(
                    'id' => $orders[0]['id'],
                    'reference_id' =>  $orders['order_transactions']['reference_id'],
                    'orderno' =>  $orders[0]['orderno'],
                    'device_id' =>  $orders['order_transactions']['device_id'],
                    'cashier_id' =>  $orders['order_transactions']['cashier_id'],
                    'table_number' =>  $orders['order_transactions']['table_number'],
                    'price' =>  number_format($orders[0]['price'],2),
                    'total_tax' =>  number_format($orders[0]['total_tax'],2),
                    'servicecharge' =>  $orders[0]['servicecharge'],
                    'discount' =>  $orders[0]['discount'],
                    'discount_percentage' =>  $discount_percentage,
                    'discount_type' =>  $orders['order_transactions']['discount_type'],
                    'discount_type_value' =>  $orders[0]['discount_type_value'],
                    'delivery_charge' =>  $orders[0]['delivery_charge'],
                    'packing_charge' =>  $orders[0]['packing_charge'],
                    'amount' =>  $orders[0]['amount'],
                    'round' =>  $orders[0]['round'],
                    'name' =>  $orders['order_transactions']['name'],
                    'phone' =>  $orders['order_transactions']['phone'],
                    'address' =>  $orders['order_transactions']['address'],
                    'remarks' =>  $orders['order_transactions']['remarks'],
                    'status' =>  $orders['order_transactions']['status'],
                    'tokenno' =>  $orders[0]['tokenno'],
                    'createtime' =>  $orders['order_transactions']['createtime'],
                    'created' =>  $orders['order_transactions']['created']
                );
            }
        }
        $paymentitems=[];
        $payments = $this->Order_payment->find('all', array('conditions'=>array('reference_id'=>$reference_id,'status !='=>0)));
        if(!empty($payments))
        {
            foreach($payments as $orders){
                if(!isset($orders['Order_payment']['remarks'])){
                    $orders['Order_payment']['remarks']='';
                }
                $paymentitems[]=array(
                    'id' => $orders['Order_payment']['id'],
                    'reference_id' =>  $orders['Order_payment']['reference_id'],
                    'cashier_id' =>  $orders['Order_payment']['cashier_id'],
                    'type' =>  $orders['Order_payment']['type'],
                    'type_value' =>  $orders['Order_payment']['type_value'],
                    'amount' =>  $orders['Order_payment']['amount'],
                    'status' =>  $orders['Order_payment']['status'],
                    'remarks' =>  $orders['Order_payment']['remarks'],
                    'created' =>  $orders['Order_payment']['created']
                );
            }
        }
        $taxitems=[];
        $taxes = $this->Order_tax->query("SELECT tax_id,tax_name,tax_percentage,sum(tax_value) as tax_value FROM `order_tax` WHERE reference_id='$reference_id' and status!=0 GROUP by tax_id");
        if(!empty($taxes))
        {
            foreach($taxes as $tax){
                // print_r($tax);exit;
                
                $taxitems[]=array(
                    'tax_id' => $tax['order_tax']['tax_id'],
                    'tax_name' =>  $tax['order_tax']['tax_name'],
                    'tax_percentage' =>  $tax['order_tax']['tax_percentage'],
                    'tax_value' =>  "" .round($tax[0]['tax_value'],2)
                );
            }
        }
        
        $finalpayment=0;
        $allpayments=$this->Order_payment->query("SELECT sum(amount) as pay_amount FROM `order_payments` WHERE reference_id='$reference_id'");
        if($allpayments){
            $finalpayment=$allpayments[0][0]['pay_amount'];
        }
        
        $amount_diff=round(($finalamount-$finalpayment),2);
        
        $cashier_name='';
        $cashname=$this->User->query("SELECT name FROM `users` WHERE id='$cashierid'");
        if($cashname){
           $cashier_name =$cashname[0]['users']['name'];
        }
        
        $printeritems=[];
        $printerss = $this->Pos_printer->query("SELECT * FROM `pos_printers` WHERE status=1");
        if(!empty($printerss))
        {
            foreach($printerss as $printers){
                // print_r($tax);exit;
                
                $printeritems[]=array(
                    'id' => $printers['pos_printers']['id'],
                    'store_id' =>  $printers['pos_printers']['store_id'],
                    'name' =>  $printers['pos_printers']['name'],
                    'kds' =>  $printers['pos_printers']['kds'],
                    'ip' =>  $printers['pos_printers']['ip'],
                    'status' =>  $printers['pos_printers']['status']
                );
            }
        }
        
        $response= array('status'=> true,
                'message'=> "success",
                'cashier_name'=>$cashier_name,
                'orders'=>$orderitems,
                'transactions'=>$transactionitems,
                'payments'=>$paymentitems,
                'taxes'=>$taxitems,
                'printers'=>$printeritems,
                'remaining_amount'=>number_format($amount_diff, 2, '.', '')
            );
        return json_encode($response);
    }
    
    public function fetch_paymentdata_storeid()
    {
        $cashierid = $_REQUEST['id'];
        $reference_id = $_REQUEST['reference_id'];
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "User Id Missing",
            );
            return json_encode($response);
        }
        if($reference_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Reference Id Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        $finalamount=0;
        $transactionitems=[];
        $transactions = $this->Order_transaction->find('all', array('conditions'=>array('id'=>$reference_id,'status !='=>0)));
        if(!empty($transactions))
        {
            foreach($transactions as $orders){
                if(!$orders['Order_transaction']['remarks']){
                    $orders['Order_transaction']['remarks']='';
                }
                $finalamount=$orders['Order_transaction']['amount'];
                $cashierid=$orders['Order_transaction']['cashier_id'];
                $reference_id=$orders['Order_transaction']['reference_id'];
                
                $discper = $this->Order_tax->query("SELECT discount_percentage FROM `order_tax` WHERE reference_id='$reference_id' and status=2 and discount_percentage!=0 limit 1");
                if(!empty($discper))
                {
                    $discount_percentage=number_format($discper[0]['order_tax']['discount_percentage'],2);
                }
                if(!isset($discount_percentage)){
                    $discount_percentage="0";
                }
                
                $transactionitems[]=array(
                    'id' => $orders['Order_transaction']['id'],
                    'reference_id' =>  $orders['Order_transaction']['reference_id'],
                    'orderno' =>  $orders['Order_transaction']['orderno'],
                    'device_id' =>  $orders['Order_transaction']['device_id'],
                    'cashier_id' =>  $orders['Order_transaction']['cashier_id'],
                    'table_number' =>  $orders['Order_transaction']['table_number'],
                    'price' =>  $orders['Order_transaction']['price'],
                    'total_tax' =>  $orders['Order_transaction']['total_tax'],
                    'servicecharge' =>  $orders['Order_transaction']['servicecharge'],
                    'discount' =>  $orders['Order_transaction']['discount'],
                    'discount_percentage' =>  $discount_percentage,
                    'discount_type' =>  $orders['Order_transaction']['discount_type'],
                    'discount_type_value' =>  $orders['Order_transaction']['discount_type_value'],
                    'delivery_charge' =>  $orders['Order_transaction']['delivery_charge'],
                    'packing_charge' =>  $orders['Order_transaction']['packing_charge'],
                    'amount' =>  $orders['Order_transaction']['amount'],
                    'round' =>  $orders['Order_transaction']['round'],
                    'name' =>  $orders['Order_transaction']['name'],
                    'phone' =>  $orders['Order_transaction']['phone'],
                    'address' =>  $orders['Order_transaction']['address'],
                    'remarks' =>  $orders['Order_transaction']['remarks'],
                    'status' =>  $orders['Order_transaction']['status'],
                    'tokenno' =>  $orders['Order_transaction']['tokenno'],
                    'createtime' =>  $orders['Order_transaction']['createtime'],
                    'created' =>  $orders['Order_transaction']['created']
                );
            }
        }
        else
        {
            $response =array(
                'status'=> false,
                'message'=> "Transaction not found.",
            );
            return json_encode($response);
        }
        
        $reference_id=$transactions['Order_transaction']['reference_id'];
        $store_id=$transactions['Order_transaction']['store_id'];
        
        $orderitems=[];
        $orderss = $this->Order_orderhistory->query("SELECT * FROM `order_orderhistories` WHERE reference_id='$reference_id' and store_id='$store_id' and status!=0");
        // print_r("SELECT id,reference_id,group_id,cashier_id,category,category_name,product_id,product_name,SUM(quantity) as quantity,sum(price) as price,sum(total_tax) as total_tax,sum(total_tax_percentage) as total_tax_percentage,sum(total_price) as total_price,SUM(discount) as discount FROM `order_orderhistories` WHERE reference_id='$reference_id' and status!=0 group BY product_id");exit;
        if(!empty($orderss))
        {
            
            foreach($orderss as $orders){
                $product_id=$orders['order_orderhistories']['product_id'];
                $order_id=$orders['order_orderhistories']['id'];
                $selected_modifiers=[];
                $orders_modifiers = $this->Order_modifier->query("SELECT * FROM `order_modifier` WHERE reference_id='$reference_id' and product_id='$product_id' and orderhistory_id='$order_id' and status!=0");
                foreach($orders_modifiers as $orders_modifier){
                    
                    $modifiers=$orders_modifier['order_modifier'];
                    $modifier_group_id=$modifiers['modifier_group_id'];
                    $modifier_group_name=$modifiers['modifier_group_name'];
                    $modifier_id=$modifiers['modifier_id'];
                    $modifier_name=$modifiers['modifier_name'];
                    $modifier_price=$modifiers['modifier_price'];
                    
                    $selected_modifiers[]=array(
                        'modifier_group_id' => $modifier_group_id,
                        'modifier_group_name' => $modifier_group_name,
                        'modifier_id' => $modifier_id,
                        'modifier_name' => $modifier_name,
                        'modifier_price' => $modifier_price,
                        );
                    
                }
                
                if(!isset($orders['order_orderhistories']['remarks'])){
                    $orders['order_orderhistories']['remarks']='';
                }
                $orderitems[]=array(
                    'id' => $orders['order_orderhistories']['id'],
                    'reference_id' =>  $orders['order_orderhistories']['reference_id'],
                    'cashier_id' =>  $orders['order_orderhistories']['cashier_id'],
                    'group_id' =>  $orders['order_orderhistories']['group_id'],
                    'category' =>  $orders['order_orderhistories']['category'],
                    'category_name' =>  $orders['order_orderhistories']['category_name'],
                    'kds' =>  $orders['order_orderhistories']['kds'],
                    'product_id' =>  $orders['order_orderhistories']['product_id'],
                    'product_name' =>  $orders['order_orderhistories']['product_name'],
                    'quantity' =>  $orders['order_orderhistories']['quantity'],
                    'price' =>  $orders['order_orderhistories']['price'],
                    'total_tax' =>  $orders['order_orderhistories']['total_tax'],
                    'total_price' =>  $orders['order_orderhistories']['total_price'],
                    'discount' =>  $orders['order_orderhistories']['discount'],
                    'table_number' =>  $orders['order_orderhistories']['table_number'],
                    'remarks' =>  $orders['order_orderhistories']['remarks'],
                    'selected_modifiers' => $selected_modifiers,
                    'status' =>  $orders['order_orderhistories']['status'],
                    'created' =>  $orders['order_orderhistories']['created']
                );
            }
        }
        
        $paymentitems=[];
        $payments = $this->Order_payment->find('all', array('conditions'=>array('reference_id'=>$reference_id,'store_id'=>$store_id,'status !='=>0)));
        if(!empty($payments))
        {
            foreach($payments as $orders){
                if(!isset($orders['Order_payment']['remarks'])){
                    $orders['Order_payment']['remarks']='';
                }
                $paymentitems[]=array(
                    'id' => $orders['Order_payment']['id'],
                    'reference_id' =>  $orders['Order_payment']['reference_id'],
                    'cashier_id' =>  $orders['Order_payment']['cashier_id'],
                    'type' =>  $orders['Order_payment']['type'],
                    'type_value' =>  $orders['Order_payment']['type_value'],
                    'amount' =>  $orders['Order_payment']['amount'],
                    'status' =>  $orders['Order_payment']['status'],
                    'remarks' =>  $orders['Order_payment']['remarks'],
                    'created' =>  $orders['Order_payment']['created']
                );
            }
        }
        $taxitems=[];
        $taxes = $this->Order_tax->query("SELECT tax_id,tax_name,tax_percentage,sum(tax_value) as tax_value FROM `order_tax` WHERE reference_id='$reference_id' and store_id='$store_id' and status!=0 GROUP by tax_id");
        if(!empty($taxes))
        {
            foreach($taxes as $tax){
                // print_r($tax);exit;
                
                $taxitems[]=array(
                    'tax_id' => $tax['order_tax']['tax_id'],
                    'tax_name' =>  $tax['order_tax']['tax_name'],
                    'tax_percentage' =>  $tax['order_tax']['tax_percentage'],
                    'tax_value' =>  "" .round($tax[0]['tax_value'],2)
                );
            }
        }
        $finalpayment=0;
        $allpayments=$this->Order_payment->query("SELECT sum(amount) as pay_amount FROM `order_payments` WHERE reference_id='$reference_id' and store_id='$store_id'");
        if($allpayments){
            $finalpayment=$allpayments[0][0]['pay_amount'];
        }
        $amount_diff=round(($finalamount-$finalpayment),2);
        
        $cashier_name='';
        $cashname=$this->User->query("SELECT name FROM `users` WHERE id='$cashierid'");
        if($cashname){
           $cashier_name =$cashname[0]['users']['name'];
        }
        // print_r($cashname);exit;
        
        $printeritems=[];
        $printerss = $this->Pos_printer->query("SELECT * FROM `pos_printers` WHERE status=1");
        if(!empty($printerss))
        {
            foreach($printerss as $printers){
                // print_r($tax);exit;
                
                $printeritems[]=array(
                    'id' => $printers['pos_printers']['id'],
                    'store_id' =>  $printers['pos_printers']['store_id'],
                    'name' =>  $printers['pos_printers']['name'],
                    'kds' =>  $printers['pos_printers']['kds'],
                    'ip' =>  $printers['pos_printers']['ip'],
                    'status' =>  $printers['pos_printers']['status']
                );
            }
        }
        
        $response= array('status'=> true,
                'message'=> "success",
                'cashier_name'=>$cashier_name,
                'orders'=>$orderitems,
                'transactions'=>$transactionitems,
                'payments'=>$paymentitems,
                'taxes'=>$taxitems,
                'printers'=>$printeritems,
                'remaining_amount'=>number_format($amount_diff, 2, '.', '')
            );
        return json_encode($response);
    }
    
    public function payment_mode_update_storeid()
    {
        $response['status']= false;
        $response['message']= "fail";
        
        $cashierid = $_REQUEST['id'];
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "Cashier Id is Missing",
            );
            return json_encode($response);
        }
        
        $reference_id = $_REQUEST['reference_id'];
        if($reference_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Reference Id is Missing",
            );
            return json_encode($response);
        }
        
        $payment_type = $_REQUEST['type'];
        if($payment_type==''){
            $response =array(
                'status'=> false,
                'message'=> "Payment type is Missing",
            );
            return json_encode($response);
        }
        
        $payment_type_value = $_REQUEST['type_value'];
        if($payment_type_value==''){
            $response =array(
                'status'=> false,
                'message'=> "Payment type Value is Missing",
            );
            return json_encode($response);
        }
        
        $amount = $_REQUEST['amount'];
        if($amount==''){
            $response =array(
                'status'=> false,
                'message'=> "Payment Amount is Missing",
            );
            return json_encode($response);
        }
        
        $device_id=$_REQUEST['device_id'];
        $remarks='';
        $remarks=$_REQUEST['remarks'];
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        
        //payment save
        
        $transactions = $this->Order_transaction->find('first', array('conditions'=>array('Order_transaction.id'=>$reference_id,'Order_transaction.status'=>2)));
        if(empty($transactions))
        {
            $response =array(
                'status'=> false,
                'message'=> "Transaction not billed",
            );
            return json_encode($response);
        }
        $reference_id=$transactions['Order_transaction']['reference_id'];
        $total_amount=$transactions['Order_transaction']['amount'];
        $store_id=$transactions['Order_transaction']['store_id'];
        if($amount>=$total_amount){
            $this->Order_payment->query("UPDATE order_payments SET status = 0 WHERE reference_id = '$reference_id' and store_id='$store_id'");
                                
            $datas['Order_payment']=array(
                'reference_id'=>$reference_id,
                'device_id'=>$device_id,
                'store_id'=>$store_id,
                'cashier_id'=>$cashierid,
                'type'=>$payment_type,
                'type_value'=>$payment_type_value,
                'amount'=>$amount,
                'remarks'=>$remarks,
                'status'=>2
            );
            
            if($this->Order_payment->saveAll($datas['Order_payment']))
            {
                $response['status']= true;
                $response['message']= "Payment Mode Updated Successfully..!";
            }else{
                $response['status']= false;
                $response['message']= "Payment Mode not Saved..!";
            }
        }else{
            $response['status']= false;
            $response['message']= "Update Failed !! Payment Mode Update Can't accept Partial payments..!!";
        }
        return json_encode($response);
    }
    
    public function fetch_printdata_gstwise()
    {
        $cashierid = $_REQUEST['id'];
        $reference_id = $_REQUEST['reference_id'];
        
        $response = array();
        if($cashierid==''){
            $response =array(
                'status'=> false,
                'message'=> "User Id Missing",
            );
            return json_encode($response);
        }
        if($reference_id==''){
            $response =array(
                'status'=> false,
                'message'=> "Reference Id Missing",
            );
            return json_encode($response);
        }
        
        $users = $this->User->find('first', array('conditions'=>array('User.id'=>$cashierid,'User.status'=>1)));
        if(empty($users))
        {
            $response =array(
                'status'=> false,
                'message'=> "User not found",
            );
            return json_encode($response);
        }
        $orderitems=[];
        $orderss = $this->Order_orderhistory->query("SELECT * FROM `order_orderhistories` WHERE reference_id='$reference_id' and status!=0");
        // print_r("SELECT id,reference_id,group_id,cashier_id,category,category_name,product_id,product_name,SUM(quantity) as quantity,sum(price) as price,sum(total_tax) as total_tax,sum(total_tax_percentage) as total_tax_percentage,sum(total_price) as total_price,SUM(discount) as discount FROM `order_orderhistories` WHERE reference_id='$reference_id' and status!=0 group BY product_id");exit;
        if(!empty($orderss))
        {
            
            foreach($orderss as $orders){
                $product_id=$orders['order_orderhistories']['product_id'];
                $order_id=$orders['order_orderhistories']['id'];
                $selected_modifiers=[];
                $orders_modifiers = $this->Order_modifier->query("SELECT * FROM `order_modifier` WHERE reference_id='$reference_id' and product_id='$product_id' and orderhistory_id='$order_id' and status!=0");
                foreach($orders_modifiers as $orders_modifier){
                    
                    $modifiers=$orders_modifier['order_modifier'];
                    $modifier_group_id=$modifiers['modifier_group_id'];
                    $modifier_group_name=$modifiers['modifier_group_name'];
                    $modifier_id=$modifiers['modifier_id'];
                    $modifier_name=$modifiers['modifier_name'];
                    $modifier_price=$modifiers['modifier_price'];
                    
                    $selected_modifiers[]=array(
                        'modifier_group_id' => $modifier_group_id,
                        'modifier_group_name' => $modifier_group_name,
                        'modifier_id' => $modifier_id,
                        'modifier_name' => $modifier_name,
                        'modifier_price' => $modifier_price,
                        );
                    
                }
                
                if(!isset($orders['order_orderhistories']['remarks'])){
                    $orders['order_orderhistories']['remarks']='';
                }
                $orderitems[]=array(
                    'id' => $orders['order_orderhistories']['id'],
                    'reference_id' =>  $orders['order_orderhistories']['reference_id'],
                    'cashier_id' =>  $orders['order_orderhistories']['cashier_id'],
                    'group_id' =>  $orders['order_orderhistories']['group_id'],
                    'category' =>  $orders['order_orderhistories']['category'],
                    'category_name' =>  $orders['order_orderhistories']['category_name'],
                    'kds' =>  $orders['order_orderhistories']['kds'],
                    'product_id' =>  $orders['order_orderhistories']['product_id'],
                    'product_name' =>  $orders['order_orderhistories']['product_name'],
                    'quantity' =>  $orders['order_orderhistories']['quantity'],
                    'price' =>  $orders['order_orderhistories']['price'],
                    'total_tax' =>  $orders['order_orderhistories']['total_tax'],
                    'total_price' =>  $orders['order_orderhistories']['total_price'],
                    'discount' =>  $orders['order_orderhistories']['discount'],
                    'table_number' =>  $orders['order_orderhistories']['table_number'],
                    'remarks' =>  $orders['order_orderhistories']['remarks'],
                    'selected_modifiers' => $selected_modifiers,
                    'status' =>  $orders['order_orderhistories']['status'],
                    'created' =>  $orders['order_orderhistories']['created']
                );
            }
        }
        $finalamount=0;
        $transactionitems=[];
        $transactions = $this->Order_transaction->query(
            "SELECT GROUP_CONCAT(id) as id,reference_id,GROUP_CONCAT(orderno) as orderno,device_id,cashier_id,table_number,
            SUM(price) as price,SUM(total_tax) as total_tax,SUM(servicecharge) as servicecharge,SUM(discount) as discount,
            SUM(discount_type_value) as discount_type_value,SUM(delivery_charge) as delivery_charge,SUM(packing_charge) as packing_charge,
            SUM(amount) as amount,SUM(round) as round,discount_type ,name,phone,address,GROUP_CONCAT(remarks) as remarks,status,GROUP_CONCAT(tokenno) as tokenno,
            createtime,created FROM `order_transactions` WHERE reference_id='$reference_id' and status!=0");
        
        if(!empty($transactions))
        {
            foreach($transactions as $orders){
                
                if(!$orders[0]['remarks']){
                    $orders[0]['remarks']='';
                }
                $finalamount=$orders[0]['amount'];
                $cashierid=$orders[0]['cashier_id'];
                $reference_id=$orders['order_transactions']['reference_id'];
                
                $discper = $this->Order_tax->query("SELECT SUM(discount_percentage) as discount_percentage FROM `order_tax` WHERE reference_id='$reference_id' and status=2 and discount_percentage!=0");
                if(!empty($discper))
                {
                    $discount_percentage=number_format($discper[0][0]['discount_percentage'],2);
                }
                if(!isset($discount_percentage)){
                    $discount_percentage="0";
                }
                
                $transactionitems[]=array(
                    'id' => $orders[0]['id'],
                    'reference_id' =>  $orders['order_transactions']['reference_id'],
                    'orderno' =>  $orders[0]['orderno'],
                    'device_id' =>  $orders['order_transactions']['device_id'],
                    'cashier_id' =>  $orders['order_transactions']['cashier_id'],
                    'cashier_name' => isset($users['User']['username']) ? $users['User']['username'] : '',
                    'table_number' =>  $orders['order_transactions']['table_number'],
                    'price' =>  number_format($orders[0]['price'],2),
                    'total_tax' =>  number_format($orders[0]['total_tax'],2),
                    'servicecharge' =>  $orders[0]['servicecharge'],
                    'discount' =>  $orders[0]['discount'],
                    'discount_percentage' =>  $discount_percentage,
                    'discount_type' =>  $orders['order_transactions']['discount_type'],
                    'discount_type_value' =>  $orders[0]['discount_type_value'],
                    'delivery_charge' =>  $orders[0]['delivery_charge'],
                    'packing_charge' =>  $orders[0]['packing_charge'],
                    'amount' =>  $orders[0]['amount'],
                    'round' =>  $orders[0]['round'],
                    'name' =>  $orders['order_transactions']['name'],
                    'phone' =>  $orders['order_transactions']['phone'],
                    'address' =>  $orders['order_transactions']['address'],
                    'remarks' =>  $orders['order_transactions']['remarks'],
                    'status' =>  $orders['order_transactions']['status'],
                    'tokenno' =>  $orders[0]['tokenno'],
                    'createtime' =>  $orders['order_transactions']['createtime'],
                    'created' =>  $orders['order_transactions']['created']
                );
            }
        }
        $paymentitems=[];
        $payments = $this->Order_payment->find('all', array('conditions'=>array('reference_id'=>$reference_id,'status !='=>0)));
        if(!empty($payments))
        {
            foreach($payments as $orders){
                if(!isset($orders['Order_payment']['remarks'])){
                    $orders['Order_payment']['remarks']='';
                }
                $paymentitems[]=array(
                    'id' => $orders['Order_payment']['id'],
                    'reference_id' =>  $orders['Order_payment']['reference_id'],
                    'cashier_id' =>  $orders['Order_payment']['cashier_id'],
                    'type' =>  $orders['Order_payment']['type'],
                    'type_value' =>  $orders['Order_payment']['type_value'],
                    'amount' =>  $orders['Order_payment']['amount'],
                    'status' =>  $orders['Order_payment']['status'],
                    'remarks' =>  $orders['Order_payment']['remarks'],
                    'created' =>  $orders['Order_payment']['created']
                );
            }
        }
        $taxitems=[];
        $taxes = $this->Order_tax->query("SELECT tax_id,tax_name,tax_percentage,sum(tax_value) as tax_value FROM `order_tax` WHERE reference_id='$reference_id' and status!=0 GROUP by tax_id");
        if(!empty($taxes))
        {
            foreach($taxes as $tax){
                // print_r($tax);exit;
                
                $taxitems[]=array(
                    'tax_id' => $tax['order_tax']['tax_id'],
                    'tax_name' =>  $tax['order_tax']['tax_name'],
                    'tax_percentage' =>  $tax['order_tax']['tax_percentage'],
                    'tax_value' =>  "" .round($tax[0]['tax_value'],2)
                );
            }
        }
        
        $finalpayment=0;
        $allpayments=$this->Order_payment->query("SELECT sum(amount) as pay_amount FROM `order_payments` WHERE reference_id='$reference_id' and status=2");
        if($allpayments){
            $finalpayment=$allpayments[0][0]['pay_amount'];
        }
        
        $amount_diff=round(($finalamount-$finalpayment),2);
        
        $cashier_name='';
        $cashname=$this->User->query("SELECT name FROM `users` WHERE id='$cashierid'");
        if($cashname){
           $cashier_name =$cashname[0]['users']['name'];
        }
        
        $printeritems=[];
        $printerss = $this->Pos_printer->query("SELECT * FROM `pos_printers` WHERE status=1");
        if(!empty($printerss))
        {
            foreach($printerss as $printers){
                // print_r($tax);exit;
                
                $printeritems[]=array(
                    'id' => $printers['pos_printers']['id'],
                    'store_id' =>  $printers['pos_printers']['store_id'],
                    'name' =>  $printers['pos_printers']['name'],
                    'kds' =>  $printers['pos_printers']['kds'],
                    'ip' =>  $printers['pos_printers']['ip'],
                    'status' =>  $printers['pos_printers']['status']
                );
            }
        }
        
        $brandsale=[];
        $brandsaless = $this->Order_transaction->query("SELECT store_id,(SELECT name from locations WHERE id=order_transactions.store_id) as brandname,(SELECT print_line4 from locations WHERE id=order_transactions.store_id) as brandgst,orderno,(SELECT GROUP_CONCAT(CONCAT(type_value, ' - ', amount)) from order_payments WHERE status=2 and reference_id=order_transactions.reference_id and store_id=order_transactions.store_id) as payment_mode FROM `order_transactions` WHERE reference_id='$reference_id' GROUP by store_id");
        if(!empty($brandsaless))
        {
            foreach($brandsaless as $brandsales){
                // print_r($brandsales);exit;
                
                $brandsale[]=array(
                   'store_id'     => $brandsales['order_transactions']['store_id'] ?? '',
                'brandname'    => $brandsales[0]['brandname'] ?? '',
                'brandgst'     => $brandsales[0]['brandgst'] ?? '',
                'orderno'      => $brandsales['order_transactions']['orderno'] ?? '',
                'payment_mode' => $brandsales[0]['payment_mode'] ?? ''
                );
            }
        }
        
        
        $response= array('status'=> true,
                'message'=> "success",
                'cashier_name'=>$cashier_name,
                'orders'=>$orderitems,
                'transactions'=>$transactionitems,
                'payments'=>$paymentitems,
                'taxes'=>$taxitems,
                'printers'=>$printeritems,
                'brandsale'=>$brandsale,
                'remaining_amount'=>number_format($amount_diff, 2, '.', '')
            );
        return json_encode($response);
    }
    
    
}