<?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 DsrController
 * @author Aether2
 */
class DashboardController extends AppController {
    public $uses = array();
    
	public $components = array('Paginator');
    public function beforeFilter() {
        parent::beforeFilter();
        // Allow users to register and logout.
        $this->Auth->allow( );
        $this->layout = "dashboard";
        $this->response->disableCache();
    }
    
    public function create_pin()
	{
	    $sendmessage= new UtilityController;
        
	    $this->layout = "login";
		$id=$_REQUEST['id'];
		$this->set(compact('id'));
		
		$carddetail=$this->Card->find('first',array('conditions'=>array('Card.id'=>$id)));
	    if(!$carddetail){
            $this->Flash->error(__('Card not found'));
        }
        
        if ($this->request->is(array('post', 'put'))) {
            $id=$this->data['User']['id'];
            $pin = $this->data['User']['pin'];
            $otpnew = $this->data['User']['otp'];
            if($id==''){
                $this->Flash->error(__('ID error'));
            }
            if($pin==''){
                $this->Flash->error(__('Pin could not be Blank'));
            }
            if($otpnew==''){
                $this->Flash->error(__('OTP could not be Blank'));
            }
            $cardotpchk=$this->Card->find('first',array('conditions'=>array('Card.id'=>$id,'Card.otp'=>$otpnew)));
            if(!$cardotpchk){
                $this->Flash->error(__('Wrong OTP'));
                return false;
            }
            
            $pinupdate = $this->Card->query("UPDATE cards SET pin='$pin',otp='0',sync='0' WHERE id=$id");
            $this->Flash->success(__('Pin has been saved.'));
        }else{
            $name=$carddetail['Card']['name'];
            $mobile=$carddetail['Card']['mobile'];
            $otp = mt_rand(1000, 9999);
    		$query=$this->Card->query("UPDATE cards SET otp='$otp',sync='0' WHERE id = '$id'");
            
            $message = "Hi $name, please use $otp to login to PhyloPay.";
    		$msg=$sendmessage->message($message,$mobile);
    // 		
        }
		
	}
	
    public function home()
    {
        $this->layout = "users";
    
        // Ensure the user is authenticated
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        // Wallet balance and total active cards
        $cardbal = $this->Card->query("
            SELECT 
                SUM(cardbalance) AS wallet_bal,
                SUM(IF(status IN (2,1), 1, 0)) AS activecard 
            FROM cards
        ");
        $wallet_balance  = $cardbal[0][0]['wallet_bal'] ?? 0;
        $tot_activecards = $cardbal[0][0]['activecard'] ?? 0;
    
        // Total distinct cardtracking users
        $cardtrackingUsers = $this->Cardtracking->query("
            SELECT COUNT(DISTINCT(customerphone)) AS customers 
            FROM cardtracking
        ");
        $totalusers = $cardtrackingUsers[0][0]['customers'] ?? 0;
    
        // Determine date range from request
        $date = $this->request->data['home']['sdate'] ?? null;
        $todayDate = date("Y-m-d");
    
        if ($date == 2) {
            $days_ago = date("Y-m-d", strtotime("-30 days"));
        } elseif ($date == 1) {
            $days_ago = date("Y-m-d", strtotime("-7 days"));
        } else {
            $days_ago = $todayDate;
        }
        
        // Open table count
        $open_tables = $this->Order_table->query("
            SELECT COUNT(id) AS open_table 
            FROM order_tables 
            WHERE status = '2' 
        ");
        // print_r($open_tables);exit;
        $open_table = $open_tables[0][0]['open_table'] ?? 0;
    
        // Open table total amount
        $open_tables_amount = $this->Order_table->query("
            SELECT SUM(total_price) AS open_table 
            FROM order_orderhistories 
            WHERE reference_id IN (
                SELECT reference_id 
                FROM order_tables 
                WHERE status = '2' 
            )
        ");
        $open_table_amount = $open_tables_amount[0][0]['open_table'] ?? 0;
    
        // Card status counts in date range
        $cardStats = $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 '$days_ago 00:00:01' AND '$todayDate 23:59:59'
        ");
        $activecards   = $cardStats[0][0]['activecard'] ?? 0;
        $inactivecards = $cardStats[0][0]['inactivecard'] ?? 0;
    
        // Cardtracking financials
        $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 '$days_ago 00:00:01' AND '$todayDate 23:59:59'
        ");
        $totaladded    = $cardtracking[0][0]['totadd'] ?? 0;
        $totalused     = $cardtracking[0][0]['totused'] ?? 0;
        $totalsecurity = $cardtracking[0][0]['totsec'] ?? 0;
        $totalrefund   = $cardtracking[0][0]['totref'] ?? 0;
        $users         = $cardtracking[0][0]['customers'] ?? 0;
    
        
        $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(round) AS round,SUM(price) AS price  FROM `order_transactions` where  created BETWEEN '$days_ago 00:00:01' and '$todayDate 23:59:59' 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 '$days_ago 00:00:01' and '$todayDate 23:59:59' and status=2");
    		
    // 		print_r("SELECT COUNT(id) as total_count,SUM(pax) AS pax,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(round) AS round,SUM(price) AS price  FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' and status=2");exit;
		// Orders taxable sale
        $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  '$days_ago 00:00:01' and '$todayDate 23:59:59' AND status = 2 GROUP BY tax_id ) AS order_tax");   
        $taxable_price=0;
        foreach($taxablepricess as $taxableprices){
            $taxable_price=round($taxable_price+$taxableprices['order_tax']['taxable_price'],2);
        }
        
        $payments = $this->Order_payment->query("SELECT SUM(amount) as total_amount,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=7,amount,0)) AS no_charge_with_tax,SUM(IF(type=7,round(amount-(SELECT total_tax from order_transactions WHERE reference_id=order_payments.reference_id and status=2 limit 1),2),0)) AS  no_charge,SUM(IF(type=8,amount,0)) AS storecard FROM `order_payments` where created BETWEEN '$days_ago 00:00:01' and '$todayDate 23:59:59' and status=2");
		    
		$transactionswithnctax = $this->Order_transaction->query("SELECT SUM(total_tax) AS total_tax,SUM(pax) AS pax,SUM(amount) AS amount FROM `order_transactions` where  created BETWEEN '$days_ago 00:00:01' and '$todayDate 23:59:59' and status=2 ");
        $transactionscount = $this->Order_transaction->query("SELECT COUNT(id) as total_count FROM `order_transactions` where  created BETWEEN '$days_ago 00:00:01' and '$todayDate 23:59:59'  and status=2 ");
        
        // Send data to view
        $this->set(compact(
            'transactionswithnctax',
            'transactionscount',
            'open_table_amount',
            'open_table',
            'transactions',
            'payments',
            'taxable_price',
            'discount',
            'wallet_balance',
            'tot_activecards',
            'activecards',
            'inactivecards',
            'totalusers',
            'totaladded',
            'totalused',
            'totalsecurity',
            'totalrefund',
            'users',
            'transactionsubtotal'
        ));
    }

    public function login() {
        $this->layout = "login";
        $this->set('title', 'Login Page');
    
        // Already logged in?
        if ($this->Session->check('Auth.User') || $this->Session->check('Auth.Location')) {
            if ($this->Session->check('Auth.User')) {
                return $this->redirect(['controller' => 'dashboard', 'action' => 'home']);
            }
            if ($this->Session->check('Auth.Location')) {
                return $this->redirect(['controller' => 'Outlet', 'action' => 'indent']);
            }
        }
    
        if ($this->request->is('post')) {
    
            // ---- 1. Try login with Users table ----
            $this->Auth->authenticate = [
                'Form' => [
                    'userModel' => 'User',
                    'fields'    => ['username' => 'username', 'password' => 'password']
                ]
            ];
            $this->Auth->constructAuthenticate();
    
            if ($this->Auth->login()) {
                $id = $this->Session->read('Auth.User.id');
                if ($id != 1) {
                    // Fetch modules
                    $moduless = $this->User_module->query("SELECT GROUP_CONCAT(name) as modulenames FROM user_modules WHERE user_id=$id");
                    $modules = $moduless[0][0]['modulenames'];
                    $this->Session->write('Auth.User.modules', $modules);
    
                    // Fetch locations
                    $locations = $this->User_location->query("SELECT GROUP_CONCAT(location_id) as location_ids FROM user_locations WHERE user_id=$id AND status=1");
                    $location_ids = $locations[0][0]['location_ids'];
                    $this->Session->write('Auth.User.location_ids', $location_ids);
                }
    
                return $this->redirect(['controller' => 'dashboard', 'action' => 'home']);
            }
    
            // ---- 2. Try login with Locations table ----
            // Copy posted User[...] data into Location[...] so Auth can check it
            if (!empty($this->request->data['User'])) {
                $this->request->data['Location'] = $this->request->data['User'];
            }
    
            $this->Auth->logout(); // clear previous attempt
            $this->Auth->authenticate = [
                'Form' => [
                    'userModel' => 'Location',
                    'fields'    => ['username' => 'username', 'password' => 'password'],
                    'scope'     => ['Location.type' => 'OUTLET']
                ]
            ];
            $this->Auth->constructAuthenticate();
    
            if ($this->Auth->login()) {
                $location = $this->Auth->user();
                $this->Session->write('Auth.Location', $location);
                return $this->redirect(['controller' => 'Outlet', 'action' => 'indent']);
            }
    
            // ---- 3. Both failed ----
            $this->Flash->error(__('Invalid username or password, try again'));
        }
    }

    public function logout() {
        // Clear CakePHP Auth session
        $this->Auth->logout();
    
        // Manually clear both User & Location sessions
        $this->Session->delete('Auth.User');
        $this->Session->delete('Auth.Location');
    
        // Redirect to login page
        return $this->redirect('/');
    }
    

    public function wallet_report() {
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		$startDate = date('m/d/Y');
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }    
        
        $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 '$startdate 00:00:01' and '$enddate 23:59:59'");
        $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 '$startdate 00:00:01' and '$enddate 23:59:59'");
        $totaladded=$cardtracking[0][0]['totadd'];
        $totalused=$cardtracking[0][0]['totused'];
        $totalsecurity=$cardtracking[0][0]['totsec'];
        $totalrefund=$cardtracking[0][0]['totref'];
     
		
		$yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
    
        $this->set(compact('activecards','inactivecards','totaladded','totalused','totalsecurity','totalrefund'));
	}
	
	public function wallet_reportexport() {
        $date_range= $_GET['sdate'];
	    $dates = explode(" - ", $date_range);
        $start_date = trim($dates[0]);
        $end_date = trim($dates[1]);
        $startdate= date('Y-m-d', strtotime($start_date));
        $enddate= date('Y-m-d', strtotime($end_date));

        $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 '$startdate 00:00:01' and '$enddate 23:59:59'");
        $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 '$startdate 00:00:01' and '$enddate 23:59:59'");
        $totaladded=$cardtracking[0][0]['totadd'];
        $totalused=$cardtracking[0][0]['totused'];
        $totalsecurity=$cardtracking[0][0]['totsec'];
        $totalrefund=$cardtracking[0][0]['totref'];
        
        
        App::import('Vendor', 'PHPExcel/PHPExcel');
           error_reporting(0);
           ini_set('display_errors', TRUE);
           ini_set('display_startup_errors', TRUE);
           if (PHP_SAPI == 'cli')
                die('This example should only be run from a Web Browser');
           $objPHPExcel = new PHPExcel();
           // Set document properties
           $objPHPExcel->getProperties()->setCreator("Aether")
           ->setLastModifiedBy("Aether")
           ->setTitle("Office 2007 XLSX Aether Document")
           ->setSubject("Office 2007 XLSX Aether Document")
           ->setDescription("Aether Export Data File.")
           ->setKeywords("office 2007 openxml php")
           ->setCategory("AetherPos Export Data File");
           // Add some data
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', '   ' .'WALLET REPORT FROM '.$startdate.' TO '.$enddate);
           
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A3', '   ' .'Card Data');
            
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A4', 'Active Cards');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B4', $activecards);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A5', 'Inactive Cards');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B5', $inactivecards);
            
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A7', '   ' .'Wallet Data');
            
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A8', 'Total Balance Added');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B8', round($totaladded,2));
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A9', 'Total Used Amount');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B9', round($totalused,2));
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A10', 'Refunded Amount');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B10', round($totalrefund,2));
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A11', 'Security Amount');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B11', round($totalsecurity,2));
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A12', 'Net Balance');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B12', round(($totaladded-$totalused),2));
            
            $objPHPExcel->getActiveSheet()->getStyle("A1:B3")->getFont()->setBold(true);
            $objPHPExcel->getActiveSheet()->getStyle("A7:B7")->getFont()->setBold(true);
            $objPHPExcel->getActiveSheet()->mergeCells('A1:B1');
            
            $baseRow = 3;
            $r=1;
        
		    $objPHPExcel->getActiveSheet()->setTitle('Export Data');
            $objPHPExcel->setActiveSheetIndex(0);
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="'.'WALLET REPORT.xls"');
            header('Cache-Control: max-age=0');
            header('Cache-Control: max-age=1');
            header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
            header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
            header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
            header ('Pragma: public'); // HTTP/1.0
            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            $objWriter->save('php://output');
            exit;
               
	}
	
	public function wallet_reportpdf() {
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
        $this->layout = "login";
	    if($this->request->is('post', 'put'))
        {
            $date_range=  $this->request->data['sdate'];
    	    $dates = explode(" - ", $date_range);
            $start_date = trim($dates[0]);
            $end_date = trim($dates[1]);
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
    
            $card = $this->Card->query("SELECT SUM(IF(status IN (1,2),1,0)) AS activecard, SUM(IF(status=0,1,0)) AS inactivecard FROM cards WHERE created between '$startdate 00:00:01' and '$enddate 23:59:59'");
            $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 '$startdate 00:00:01' and '$enddate 23:59:59'");
            $totaladded=$cardtracking[0][0]['totadd'];
            $totalused=$cardtracking[0][0]['totused'];
            $totalsecurity=$cardtracking[0][0]['totsec'];
            $totalrefund=$cardtracking[0][0]['totref'];
            
            
            $this->set(compact('startdate','enddate','activecards','inactivecards','totaladded','totalused','totalsecurity','totalrefund'));
        }
    }
    
    public function wallet_history() {
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        $this->layout = "users";
		
		$startDate = date('m/d/Y');
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }   
        
		$cards = $this->Card->query("SELECT cards.id,cards.cardnumber,cards.cardbalance,cards.name,cards.mobile,cardtracking.txnid,cardtracking.customername,cardtracking.cashierName,cardtracking.type,cardtracking.amount,cardtracking.payment_mode as mop,cards.created FROM `cards` LEFT JOIN `cardtracking` ON cardtracking.cardnumber = cards.cardnumber where cards.created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' ORDER BY cardtracking.id desc");
		$yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        
		$this->set(compact('cards'));
	}
	
	public function wallet_historyexport() {
        $date_range= $_GET['sdate'];
	    $dates = explode(" - ", $date_range);
        $start_date = trim($dates[0]);
        $end_date = trim($dates[1]);
        $startdate= date('Y-m-d', strtotime($start_date));
        $enddate= date('Y-m-d', strtotime($end_date));

        $cards = $this->Card->query("SELECT cards.id,cards.cardnumber,cards.cardbalance,cards.name,cards.mobile,cardtracking.txnid,cardtracking.customername,cardtracking.cashierName,cardtracking.type,cardtracking.amount,cardtracking.payment_mode,cards.created FROM `cards` LEFT JOIN `cardtracking` ON cardtracking.cardnumber = cards.cardnumber where cards.created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59'  ORDER BY cardtracking.id desc");
		$datas=array();
    	foreach($cards as $card){
    	    if(isset($card['cardtracking']['txnid'])){
        	    $datas[]=array(
    				'txnid'=>$card['cardtracking']['txnid'],
    				'cashierName'=>$card['cardtracking']['cashierName'],
    				'cardnumber'=>$card['cards']['cardnumber'],
    				'mobile'=>$card['cards']['mobile'],
    				'name'=>$card['cards']['name'],
    				'type'=>$card['cardtracking']['type'],
    				'payment_mode'=>$card['cardtracking']['payment_mode'],
    				'amount'=>$card['cardtracking']['amount'],
    				'created'=>$card['cards']['created']
    			);
    	    }
        }
        
        App::import('Vendor', 'PHPExcel/PHPExcel');
           error_reporting(0);
           ini_set('display_errors', TRUE);
           ini_set('display_startup_errors', TRUE);
           if (PHP_SAPI == 'cli')
                die('This example should only be run from a Web Browser');
           $objPHPExcel = new PHPExcel();
           // Set document properties
           $objPHPExcel->getProperties()->setCreator("Aether")
           ->setLastModifiedBy("Aether")
           ->setTitle("Office 2007 XLSX Aether Document")
           ->setSubject("Office 2007 XLSX Aether Document")
           ->setDescription("Aether Export Data File.")
           ->setKeywords("office 2007 openxml php")
           ->setCategory("AetherPos Export Data File");
           // Add some data
           $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', '   ' .'WALLET HISTORY FROM '.$startdate.' TO '.$enddate);
           
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A3', 'SR. NO.');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B3', 'Txn id');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C3', 'Cashier Name');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('D3', 'Card Number');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E3', 'Phone');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('F3', 'Customer');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('G3', 'Type');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('H3', 'Payment Mode');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('I3', 'Amount');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('J3', 'Created');
            $objPHPExcel->getActiveSheet()->getStyle("A1:J3")->getFont()->setBold(true);
            $objPHPExcel->getActiveSheet()->mergeCells('A1:J1');
            
            $baseRow = 3;
            $r=1;
            
	        foreach($datas as $dat){
				  
				    if($dat['type']==1){
                        $type='credit';
                    }elseif($dat['type']==2){
                        $type='debit';
                    }elseif($dat['type']==3){
                        $type='security';
                    }else{
                        $type='refund';
                    }
                    
                    if($dat['payment_mode']=='card_charge'){
                        $purpose='Card Charge';
                    }else{
                        $purpose=$dat['payment_mode'];
                    }
                    
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.($baseRow + $r),$r);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.($baseRow + $r),$dat['txnid']);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C'.($baseRow + $r),$dat['cashierName']);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('D'.($baseRow + $r),$dat['cardnumber']);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E'.($baseRow + $r),$dat['mobile']);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('F'.($baseRow + $r),$dat['name']);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('G'.($baseRow + $r),$type);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('H'.($baseRow + $r),$purpose);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('I'.($baseRow + $r),$dat['amount']);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('J'.($baseRow + $r),$dat['created']);
					   			  
						   $r++;
				   
				}
			    $objPHPExcel->getActiveSheet()->setTitle('Export Data');
                $objPHPExcel->setActiveSheetIndex(0);
                header('Content-Type: application/vnd.ms-excel');
                header('Content-Disposition: attachment;filename="'.'WALLET HISTORY.xls"');
                header('Cache-Control: max-age=0');
                header('Cache-Control: max-age=1');
                header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
                header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
                header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
                header ('Pragma: public'); // HTTP/1.0
                $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
                $objWriter->save('php://output');
                exit;
               
	}
	
	public function wallet_historypdf() {
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
        $this->layout = "login";
	    if($this->request->is('post', 'put'))
        {
            $date_range=  $this->request->data['sdate'];
    	    $dates = explode(" - ", $date_range);
            $start_date = trim($dates[0]);
            $end_date = trim($dates[1]);
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
    
            $cards = $this->Card->query("SELECT cards.id,cards.cardnumber,cards.cardbalance,cards.name,cards.mobile,cardtracking.txnid,cardtracking.customername,cardtracking.cashierName,cardtracking.type,cardtracking.amount,cardtracking.payment_mode as mop,cards.created FROM `cards` LEFT JOIN `cardtracking` ON cardtracking.cardnumber = cards.cardnumber where cards.created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59'  ORDER BY cardtracking.id desc");
    		$datas=array();
        	foreach($cards as $card){
        	    if(isset($card['cardtracking']['txnid'])){
            	    $datas[]=array(
        				'txnid'=>$card['cardtracking']['txnid'],
        				'cashierName'=>$card['cardtracking']['cashierName'],
        				'cardnumber'=>$card['cards']['cardnumber'],
        				'mobile'=>$card['cards']['mobile'],
        				'name'=>$card['cards']['name'],
        				'type'=>$card['cardtracking']['type'],
        				'payment_mode'=>$card['cardtracking']['mop'],
        				'amount'=>$card['cardtracking']['amount'],
        				'created'=>$card['cards']['created']
        			);
        	    }
            }
            $this->set(compact('startdate','enddate','datas'));
        }
    }
    
    public function item_sale_report() {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "users";
        $startDate = date('m/d/Y', strtotime('0 days'));
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
    		$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }
        $cashier_id = $this->request->data['Search']['cashier'] ?? null;
        $cashierCondition = $cashier_id ? "AND store_id = $cashier_id" : "";
        $orderhistories = $this->Order_orderhistory->query("SELECT product_id, product_name, category_name, (SELECT unit_name FROM catalog_product WHERE id=order_orderhistories.product_id) AS unit_name, SUM(quantity) AS totalquantity, SUM(price*quantity)/SUM(quantity) AS final_price FROM order_orderhistories WHERE status = 2 AND created BETWEEN '$startdate 00:00:01' AND '$enddate 23:59:59' $cashierCondition GROUP BY product_id");

        $ncorderhistories = $this->Order_orderhistory->query("SELECT product_id, product_name, category_name, (SELECT unit_name FROM catalog_product WHERE id=order_orderhistories.product_id) AS unit_name, SUM(quantity) AS totalquantity, SUM(price*quantity)/SUM(quantity) AS final_price FROM order_orderhistories WHERE status = 2 AND created BETWEEN '$startdate 00:00:01' AND '$enddate 23:59:59' AND reference_id IN (SELECT reference_id FROM order_payments WHERE type=7 AND status=2 AND store_id=order_orderhistories.store_id) $cashierCondition GROUP BY product_id");
        $productcosts = [];
        foreach ([true  => $ncorderhistories, false => $orderhistories] as $isNc => $histories) {
            foreach ($histories as $history) {
                $data = $history['order_orderhistories'];
                $calc = $history[0];
                $product_id = $data['product_id'];
                $unit_name = $calc['unit_name'];
                $quantity = $calc['totalquantity'];
                $final_price = $calc['final_price'];
                $subproductingcost = 0;
    
                $semifinisheds = $this->Inventory_linking->find('all', [
                    'conditions' => ['parent_id' => $product_id,'parent_type' => 'Product','component_type' => 'Semifinished', 'status' => 1]
                ]);
    
                foreach ($semifinisheds as $semifinished) {
                    $semifinished_id = $semifinished['Inventory_linking']['component_id'];
                    $semifinished_quantity = $semifinished['Inventory_linking']['quantity'];
                    $totalIngCost = 0;
    
                    $ingredients = $this->Inventory_linking->find('all', [
                        'conditions' => ['parent_id' => $semifinished_id,'parent_type' => 'Semifinished','component_type' => 'Sku', 'status' => 1]
                    ]);
    
                    foreach ($ingredients as $ingredient) {
                        $sku_id = $ingredient['Inventory_linking']['component_id'];
                        $sku_quantity = $ingredient['Inventory_linking']['quantity'];
    
                        $startDatetime = $startdate . ' 00:00:01';
                        $endDatetime = $enddate . ' 23:59:59';
    
                        $stockin = $this->Inventory_purchase_order_item->find('first', [
                            'conditions' => [
                                'created BETWEEN ? AND ?' => [$startDatetime, $endDatetime],
                                'sku_id' => $sku_id,
                                'status' => 3
                            ],
                            'group' => ['sku_id'],
                            'fields' => [
                                'ROUND(SUM(sku_price), 2) AS sku_price',
                                'SUM(stockin_quantity) AS tquantity',
                                'SUM(sku_price * stockin_quantity) AS tamount'
                            ]
                        ]);
                        if (empty($stockin)) {
                            $stockin = $this->Inventory_purchase_order_item->find('first', [
                                'conditions' => ['sku_id' => $sku_id],
                                'order' => ['id DESC'],
                                'fields' => ['sku_price']
                            ]);
                        }
    
                        $ingcost = !empty($stockin[0]['sku_price']) ? $stockin[0]['sku_price'] : 0;
                        $totalIngCost += round($ingcost * $sku_quantity, 2);
                    }
    
                    $subproductingcost += round($totalIngCost * $semifinished_quantity, 2);
                }
    
                $unit_cost = round($subproductingcost, 2);
                $total_cost = round($unit_cost * $quantity, 2);
    
                if (!isset($productcosts[$product_id])) {
                    $productcosts[$product_id] = [
                        'product_id' => $product_id,
                        'product_name' => $data['product_name'],
                        'category_name' => $data['category_name'],
                        'unit_name' => $unit_name,
                        'totalquantity' => 0,
                        'final_price' => 0,
                        'unit_cost' => 0,
                        'total_cost' => 0,
                        'nctotalquantity' => 0,
                        'ncfinal_price' => 0,
                        'nctotal_cost' => 0
                    ];
                }
    
                if ($isNc) {
                    $productcosts[$product_id]['nctotalquantity'] += $quantity;
                    $productcosts[$product_id]['ncfinal_price'] += $final_price;
                    $productcosts[$product_id]['nctotal_cost'] += $total_cost;
                    
                } else {
                    $productcosts[$product_id]['totalquantity'] += $quantity;
                    $productcosts[$product_id]['final_price'] += $final_price;
                    $productcosts[$product_id]['unit_cost'] = $unit_cost;
                    $productcosts[$product_id]['total_cost'] += $total_cost;
                }
            }
        }
        
        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;
        
        $conditions = [
            'status' => 1,
            'type'   => 'Outlet'
        ];
        
        if ($userRole !== 'admin' && !empty($userLocationId)) {
            
            $userLocationIds = Hash::extract(
                ['ids' => is_array($userLocationId) ? $userLocationId : explode(',', $userLocationId)],
                'ids.{n}'
            );
            $conditions['id IN'] = array_map('trim', $userLocationIds);
        }
        
        $users = $this->Location->find('all', [
            'conditions' => $conditions
        ]);

        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        $this->set(compact('users', 'productcosts', 'orderhistories', 'cashier_id'));
    }
	
	public function item_sale_reportexport() {
        $date_range = $_GET['sdate'] ?? '';
        $cashier_id = $_GET['cashier'] ?? null;
    
        $dates = explode(" - ", $date_range);
        $start_date = trim($dates[0]);
        $end_date = trim($dates[1]);
    
        $startdate = date('Y-m-d', strtotime($start_date));
        $enddate = date('Y-m-d', strtotime($end_date));
        $cashierCondition = $cashier_id ? "AND store_id = $cashier_id" : "";
    
        // Fetch regular and NC order histories
        $orderhistories = $this->Order_orderhistory->query("SELECT product_id, product_name, category_name, (SELECT unit_name FROM catalog_product WHERE id=order_orderhistories.product_id) AS unit_name, SUM(quantity) AS totalquantity, SUM(price*quantity)/SUM(quantity) AS final_price FROM order_orderhistories WHERE status = 2 AND created BETWEEN '$startdate 00:00:01' AND '$enddate 23:59:59' $cashierCondition GROUP BY product_id");
    
        $ncorderhistories = $this->Order_orderhistory->query("SELECT product_id, product_name, category_name, (SELECT unit_name FROM catalog_product WHERE id=order_orderhistories.product_id) AS unit_name, SUM(quantity) AS totalquantity, SUM(price*quantity)/SUM(quantity) AS final_price FROM order_orderhistories WHERE status = 2 AND created BETWEEN '$startdate 00:00:01' AND '$enddate 23:59:59' AND reference_id IN (SELECT reference_id FROM order_payments WHERE type=7 AND status=2) $cashierCondition GROUP BY product_id");
    
        $productcosts = [];
    
        foreach ([true  => $ncorderhistories, false => $orderhistories] as $isNc => $histories) {
            foreach ($histories as $history) {
                $data = $history['order_orderhistories'];
                $calc = $history[0];
                $product_id = $data['product_id'];
                $unit_name = $calc['unit_name'];
                $quantity = $calc['totalquantity'];
                $final_price = $calc['final_price'];
                $subproductingcost = 0;
    
                $semifinisheds = $this->Inventory_linking->find('all', [
                    'conditions' => ['parent_id' => $product_id,'parent_type' => 'Product','component_type' => 'Semifinished', 'status' => 1]
                ]);
                
                foreach ($semifinisheds as $semifinished) {
                    $semifinished_id = $semifinished['Inventory_linking']['component_id'];
                    $semifinished_quantity = $semifinished['Inventory_linking']['quantity'];
                    $totalIngCost = 0;
    
                    $ingredients = $this->Inventory_linking->find('all', [
                        'conditions' => ['parent_id' => $semifinished_id,'parent_type' => 'Semifinished','component_type' => 'Sku', 'status' => 1]
                    ]);
    
    
                    foreach ($ingredients as $ingredient) {
                        $sku_id = $ingredient['Inventory_linking']['component_id'];
                        $sku_quantity = $ingredient['Inventory_linking']['quantity'];
    
                        $stockin = $this->Inventory_purchase_order_item->find('first', [
                            'conditions' => [
                                'created BETWEEN ? AND ?' => [$startdate . ' 00:00:01', $enddate . ' 23:59:59'],
                                'sku_id' => $sku_id,
                                'status' => 3
                            ],
                            'group' => ['sku_id'],
                            'fields' => [
                                'ROUND(SUM(sku_price), 2) AS sku_price',
                                'SUM(stockin_quantity) AS tquantity',
                                'SUM(sku_price * stockin_quantity) AS tamount'
                            ]
                        ]);
    
                        if (empty($stockin)) {
                            $stockin = $this->Inventory_purchase_order_item->find('first', [
                                'conditions' => ['sku_id' => $sku_id],
                                'order' => ['id DESC'],
                                'fields' => ['sku_price']
                            ]);
                        }
    
                        $ingcost = !empty($stockin[0]['sku_price']) ? $stockin[0]['sku_price'] : 0;
                        $totalIngCost += round($ingcost * $sku_quantity, 2);
                    }
    
                    $subproductingcost += round($totalIngCost * $semifinished_quantity, 2);
                }
    
                $unit_cost = round($subproductingcost, 2);
                $total_cost = round($unit_cost * $quantity, 2);
    
                if (!isset($productcosts[$product_id])) {
                    $productcosts[$product_id] = [
                        'product_id' => $product_id,
                        'product_name' => $data['product_name'],
                        'category_name' => $data['category_name'],
                        'unit_name' => $unit_name,
                        'totalquantity' => 0,
                        'final_price' => 0,
                        'unit_cost' => 0,
                        'total_cost' => 0,
                        'nctotalquantity' => 0,
                        'ncfinal_price' => 0,
                        'nctotal_cost' => 0
                    ];
                }
    
                if ($isNc) {
                    $productcosts[$product_id]['nctotalquantity'] += $quantity;
                    $productcosts[$product_id]['ncfinal_price'] += $final_price;
                    $productcosts[$product_id]['nctotal_cost'] += $total_cost;
                } else {
                    $productcosts[$product_id]['totalquantity'] += $quantity;
                    $productcosts[$product_id]['final_price'] += $final_price;
                    $productcosts[$product_id]['unit_cost'] = $unit_cost;
                    $productcosts[$product_id]['total_cost'] += $total_cost;
                }
            }
        }
    
        App::import('Vendor', 'PHPExcel/PHPExcel');
    
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()->setCreator("POS Export")
            ->setTitle("Item Sale Report");
    
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', 'ITEM SALE REPORT FROM ' . $startdate . ' TO ' . $enddate);
        $objPHPExcel->getActiveSheet()->mergeCells('A1:M1');
        $objPHPExcel->getActiveSheet()->getStyle("A1:M1")->getFont()->setBold(true);
    
        $headers = [
            'SR. NO.', 'Product Name', 'Category', 'Unit', 'Cost Price', 'Selling Price',
            'Billed Qty', 'Billed Amt', 'Billed Cost', 'NC Qty', 'NC Amount', 'NC Cost', 'Contribution %'
        ];
    
        $col = 'A';
        foreach ($headers as $header) {
            $objPHPExcel->getActiveSheet()->setCellValue($col . '3', $header);
            $col++;
        }
    
        $objPHPExcel->getActiveSheet()->getStyle("A3:M3")->getFont()->setBold(true);
    
        $row = 4;
        $sr = 1;
    
        foreach ($productcosts as $product) {
            $totalquantity = $product['totalquantity'] ? $product['totalquantity']:0;
            $billed_amount = $product['totalquantity'] * $product['final_price'];
            $billed_cost = $product['total_cost'];
            $contribution = ($billed_amount > 0 && $product['ncfinal_price'] > 0)
                ? round(($billed_amount / $product['ncfinal_price']) * 100, 2)
                : 0;
    
    
           $objPHPExcel->getActiveSheet()->fromArray([
                $sr++,
                $product['product_name'] ?? '',
                $product['category_name'] ?? '',
                $product['unit_name'] ?? '',
                number_format((float)($product['unit_cost'] ?? 0), 2),
                number_format((float)($product['final_price'] ?? 0), 2),
                (string)(int)($product['totalquantity'] ?? 0),
                number_format((float)($billed_amount ?? 0), 2),
                number_format((float)($billed_cost ?? 0), 2),
                (int)($product['nctotalquantity'] ?? 0),
                number_format((float)($product['ncfinal_price'] ?? 0), 2),
                number_format((float)($product['nctotal_cost'] ?? 0), 2),
                number_format((float)($contribution ?? 0), 2) . '%'
            ], null, 'A' . $row);
    
            $row++;
        }
        
        $objPHPExcel->getActiveSheet()->setTitle('ItemSaleReport');
        $objPHPExcel->setActiveSheetIndex(0);
    
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="ITEM_SALE_REPORT.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

	public function discount_report() {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "users";
        $startDate = date('m/d/Y', strtotime('0 days'));
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }
        $cashier_id = $this->request->data['Search']['cashier'] ?? null;
        $cashierCondition = $cashier_id ? "AND t.store_id = $cashier_id" : "";
        
        $transactions = $this->Order_transaction->query("
            SELECT 
                (SELECT name FROM locations WHERE id = t.store_id) AS cashier,
                (
                    SELECT SUM(quantity) 
                    FROM order_orderhistories 
                    WHERE reference_id = t.reference_id AND status = 2
                ) AS quantity,
                SUM(t.discount) AS tdiscount,
                t.orderno,
                t.discount,
                t.discount_type,
                t.discount_type_value,
                t.name,
                t.phone,
                t.address,
                (
                    SELECT remarks 
                    FROM user_tracks 
                    WHERE reference_id = t.reference_id 
                    LIMIT 1
                ) AS remarks,
                t.reference_id,
                t.amount,
                (
                    SELECT GROUP_CONCAT(type_value) 
                    FROM order_payments 
                    WHERE reference_id = t.reference_id
                ) AS type,
                p.created
            FROM 
                order_transactions t
            INNER JOIN 
                order_payments p ON p.reference_id = t.reference_id
            WHERE 
                p.status = 2 
                AND t.discount_type_value != 0 
                AND t.status = 2 
                $cashierCondition
                AND p.created BETWEEN '{$startdate} 00:00:01' AND '{$enddate} 23:59:59'
            GROUP BY 
                t.reference_id
        ");
            
        
        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;
    
        $conditions = [
            'status' => 1,
            'type'   => 'Outlet'
        ];
        
        // Add location filter for non-admins
        if ($userRole !== 'admin' && !empty($userLocationId)) {
            
            $userLocationIds = Hash::extract(
                ['ids' => is_array($userLocationId) ? $userLocationId : explode(',', $userLocationId)],
                'ids.{n}'
            );
            $conditions['id IN'] = array_map('trim', $userLocationIds);
        }
        
        $users = $this->Location->find('all', [
            'conditions' => $conditions
        ]);
        
        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        $this->set(compact('users', 'transactions'));
    }
    	
	public function discount_reportexport() {
        $this->autoRender = false;
    
        $date_range = $_GET['sdate'] ?? '';
        $cashier_id = $_GET['cashier'] ?? null;
    
        $dates = explode(" - ", $date_range);
        $start_date = trim($dates[0]);
        $end_date = trim($dates[1]);
    
        $startdate = date('Y-m-d', strtotime($start_date));
        $enddate = date('Y-m-d', strtotime($end_date));
        $cashierCondition = $cashier_id ? "AND t.store_id = $cashier_id" : "";
        
        // Query transactions
        $transactions = $this->Order_transaction->query("
            SELECT 
                (SELECT name FROM locations WHERE id = t.store_id) AS cashiername,
                (SELECT SUM(quantity) FROM order_orderhistories WHERE reference_id = t.reference_id AND status = 2) AS quantity,
                t.discount,
                t.discount_type,
                t.discount_type_value,
                t.orderno,
                t.name,
                t.phone,
                t.address,
                (SELECT remarks FROM user_tracks WHERE reference_id = t.reference_id LIMIT 1) AS remarks,
                t.reference_id,
                t.amount,
                (SELECT GROUP_CONCAT(type_value) FROM order_payments WHERE reference_id = t.reference_id) AS type,
                p.created
            FROM 
                order_transactions t
            INNER JOIN 
                order_payments p ON p.reference_id = t.reference_id
            WHERE 
                p.status = 2 
                AND t.discount_type_value != 0 
                AND t.status = 2 
                $cashierCondition
                AND p.created BETWEEN '{$startdate} 00:00:01' AND '{$enddate} 23:59:59'
            GROUP BY 
                t.reference_id
        ");
    
        App::import('Vendor', 'PHPExcel/PHPExcel');
    
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()->setCreator("POS Export")
            ->setTitle("Discount Report");
    
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', 'DISCOUNT REPORT FROM ' . $startdate . ' TO ' . $enddate);
        $objPHPExcel->getActiveSheet()->mergeCells('A1:N1');
        $objPHPExcel->getActiveSheet()->getStyle("A1:N1")->getFont()->setBold(true);
    
        $headers = [
            'SR. NO.', 'Bill No','Payment Type', 'Date','Time', 'Totel Discount', 'Discount Type','Coupon', 'Amount','Remarks', 'Customer Name', 'Phone', 'Address', 'Store Name'
        ];
    
        $col = 'A';
        foreach ($headers as $header) {
            $objPHPExcel->getActiveSheet()->setCellValue($col . '3', $header);
            $col++;
        }
        $objPHPExcel->getActiveSheet()->getStyle("A3:N3")->getFont()->setBold(true);
        
        $row = 4;
        $sr = 1;
        
        
        
        foreach ($transactions as $tr) {
            $t = $tr['t'];
            $p = $tr['p'] ?? $t; // fallback if 'p' not set
            
            if($t['discount_type']=='0'){
                $discountTypes='Coupon';
            }elseif($t['discount_type']=='1'){
                $discountTypes='Percentage';
            }elseif($t['discount_type']=='2'){
                $discountTypes='Flat';
            }
            
            $objPHPExcel->getActiveSheet()->fromArray([
                $sr++,
                $t['orderno'] ?? '',
                $tr[0]['type'] ?? '',
                isset($p['created']) ? date('d-m-Y', strtotime($p['created'])) : '',
                isset($p['created']) ? date('h:i A', strtotime($p['created'])) : '',
                number_format((float)($t['discount_type_value'] ?? 0), 2),
                $discountTypes,
                '-',
                number_format((float)($t['amount'] ?? 0), 2),
                $tr[0]['remarks'] ?? '',
                $t['name'] ?? '',
                $t['phone'] ?? '',
                $t['address'] ?? '',
                $tr[0]['cashier'] ?? ''
            ], null, 'A' . $row);
        
            $row++;
        }
    
        $objPHPExcel->getActiveSheet()->setTitle('DiscountReport');
        $objPHPExcel->setActiveSheetIndex(0);
    
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="DISCOUNT_REPORT.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

	public function bill_wise_summary() {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "users";
        $startDate = date('m/d/Y', strtotime('0 days'));
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }
        $cashier_id = $this->request->data['Search']['cashier'] ?? null;
        $cashierCondition = $cashier_id ? " and t.store_id = $cashier_id" : "";
        $cashierCondition2 = $cashier_id ? " and store_id = $cashier_id" : "";
        
        $transactions = $this->Order_transaction->query("
            SELECT 
                (SELECT name FROM locations WHERE id = t.store_id) AS cashier,
                (
                    SELECT SUM(quantity) 
                    FROM order_orderhistories 
                    WHERE reference_id = t.reference_id AND status = 2 and store_id = t.store_id
                ) AS quantity,
                t.orderno,
                t.reference_id,
                t.total_tax AS total_tax,
                t.price AS price,
                t.amount AS amount,
                (
                    SELECT GROUP_CONCAT(type_value) 
                    FROM order_payments 
                    WHERE status=2 and reference_id = t.reference_id and store_id = t.store_id
                ) AS type,
                t.created AS created
            FROM 
                order_transactions t
            WHERE 
                t.status = 2 
                $cashierCondition
                AND t.created BETWEEN '{$startdate} 00:00:01' AND '{$enddate} 23:59:59'
        ");
        
        
        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;
    
        $conditions = [
            'status' => 1,
            'type'   => 'Outlet'
        ];
        
        // Add location filter for non-admins
        if ($userRole !== 'admin' && !empty($userLocationId)) {
           
            $userLocationIds = Hash::extract(
                ['ids' => is_array($userLocationId) ? $userLocationId : explode(',', $userLocationId)],
                'ids.{n}'
            );
            $conditions['id IN'] = array_map('trim', $userLocationIds);
        }
        
        $users = $this->Location->find('all', [
            'conditions' => $conditions
        ]);
        
        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        $this->set(compact('users', 'transactions'));
    }
    
    public function bill_wise_summary_export() {
        $this->autoRender = false;
    
        $date_range = $_GET['sdate'] ?? '';
        $cashier_id = $_GET['cashier'] ?? null;
    
        $dates = explode(" - ", $date_range);
        $start_date = trim($dates[0]);
        $end_date = trim($dates[1]);
    
        $startdate = date('Y-m-d', strtotime($start_date));
        $enddate = date('Y-m-d', strtotime($end_date));
        
        $cashierCondition = $cashier_id ? " t.store_id = $cashier_id" : "";
        
        $transactions = $this->Order_transaction->query("
            SELECT 
                (SELECT name FROM locations WHERE id = t.store_id) AS cashier,
                (
                    SELECT SUM(quantity) 
                    FROM order_orderhistories 
                    WHERE reference_id = t.reference_id AND status = 2 and store_id = t.store_id
                ) AS quantity,
                t.orderno,
                t.reference_id,
                t.total_tax AS total_tax,
                t.price AS price,
                t.amount AS amount,
                (
                    SELECT GROUP_CONCAT(type_value) 
                    FROM order_payments 
                    WHERE status = 2 and reference_id = t.reference_id and store_id = t.store_id
                ) AS type,
                t.created AS created
            FROM 
                order_transactions t
            WHERE 
                t.status = 2 
                " . (!empty($cashierCondition) ? " AND $cashierCondition" : "") . "
                AND t.created BETWEEN '{$startdate} 00:00:01' AND '{$enddate} 23:59:59'
        ");
    
        App::import('Vendor', 'PHPExcel/PHPExcel');
    
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()->setCreator("POS Export")
            ->setTitle("Discount Report");
    
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', 'DISCOUNT REPORT FROM ' . $startdate . ' TO ' . $enddate);
        $objPHPExcel->getActiveSheet()->mergeCells('A1:N1');
        $objPHPExcel->getActiveSheet()->getStyle("A1:N1")->getFont()->setBold(true);
    
        $headers = [
            'SR. NO.', 'Bill No','Store','Payment Type', 'Date','Time', 'Item Total', 'Bill Price','Bill Tax', 'Bill Amount'
        ];
    
        $col = 'A';
        foreach ($headers as $header) {
            $objPHPExcel->getActiveSheet()->setCellValue($col . '3', $header);
            $col++;
        }
        $objPHPExcel->getActiveSheet()->getStyle("A3:N3")->getFont()->setBold(true);
        
        $row = 4;
        $sr = 1;
        
        foreach ($transactions as $tr) {
            $t = $tr['t'];
            $p = $tr['p'] ?? $t; // fallback if 'p' not set
            
            $objPHPExcel->getActiveSheet()->fromArray([
                $sr++,
                $tr['t']['orderno'] ?? '',
                $tr[0]['cashier'] ?? '',
                $tr[0]['type'] ?? '',
                isset($tr['t']['created']) ? date('d-m-Y', strtotime($tr['t']['created'])) : '',
                isset($tr['t']['created']) ? date('h:i A', strtotime($tr['t']['created'])) : '',
                number_format((float)($tr[0]['quantity'] ?? 0), 2),
                number_format((float)($tr['t']['price'] ?? 0), 2),
                number_format((float)($tr['t']['total_tax'] ?? 0), 2),
                number_format((float)($tr['t']['amount'] ?? 0), 2),
            ], null, 'A' . $row);
        
            $row++;
        }
    
        $objPHPExcel->getActiveSheet()->setTitle('Billwise');
        $objPHPExcel->setActiveSheetIndex(0);
    
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="Billwise_REPORT.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

    public function hourly_sales() {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "users";
        $startDate = date('m/d/Y');
        $endDate   = date('m/d/Y');
    
        if ($this->request->is('post', 'put')) {
            $daterange  = $this->request->data['daterange'] ?? '';
            $dates      = explode(" - ", $daterange);
            $start_date = trim($dates[0] ?? $startDate);
            $end_date   = trim($dates[1] ?? $endDate);
    
            $startDate = date('m/d/Y', strtotime($start_date));
            $endDate   = date('m/d/Y', strtotime($end_date));
            $startdate = date('Y-m-d', strtotime($start_date));
            $enddate   = date('Y-m-d', strtotime($end_date));
        } else {
            $startdate = date('Y-m-d', strtotime($startDate));
            $enddate   = date('Y-m-d', strtotime($endDate));
        }
    
        $cashier_id = $this->request->data['Search']['cashier'] ?? null;
    
        // prepare dates
        $datearray = [];
        $loopstartdate = $startdate;
        while (strtotime($loopstartdate) <= strtotime($enddate)) {
            $datearray[] = $loopstartdate;
            $loopstartdate = date("Y-m-d", strtotime("+1 day", strtotime($loopstartdate)));
        }
    
        $itemArray = [];
    
        // loop date and hours
        foreach ($datearray as $date) {
            for ($h = 0; $h < 24; $h++) {
                $from = $date . ' ' . str_pad($h, 2, "0", STR_PAD_LEFT) . ':00:01';
                $to   = $date . ' ' . str_pad($h, 2, "0", STR_PAD_LEFT) . ':59:59';
    
                $sql = "
                    SELECT 
                        IFNULL(SUM(amount), 0) AS totalsale,
                        COUNT(id) AS totalinvoice
                    FROM order_transactions
                    WHERE status = 2
                      AND created BETWEEN '$from' AND '$to'
                ";
                if ($cashier_id) {
                    $sql .= " AND store_id = " . (int)$cashier_id;
                }
    
                $result = $this->Order_transaction->query($sql);
                $row = $result[0][0] ?? ['totalsale' => 0, 'totalinvoice' => 0];
    
                $hourLabel = date("ga", strtotime($from)) . '-' . date("ga", strtotime($from . ' +1 hour'));

                $itemArray[$date][$hourLabel] = [
                    'totalsale'    => $row['totalsale'],
                    'totalinvoice' => $row['totalinvoice'],
                    'date'         => $date,
                ];
            }
        }
        
        // location filter
        $authUser       = $this->Session->read('Auth.User');
        $userRole       = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;
    
        $conditions = [
            'status' => 1,
            'type'   => 'Outlet'
        ];
        if ($userRole !== 'admin' && !empty($userLocationId)) {
            $userLocationIds = Hash::extract(
                ['ids' => is_array($userLocationId) ? $userLocationId : explode(',', $userLocationId)],
                'ids.{n}'
            );
            $conditions['id IN'] = array_map('trim', $userLocationIds);
        }
    
        $users = $this->Location->find('all', ['conditions' => $conditions]);
        
        $yourStartDateValue = $startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        $this->set(compact('users', 'datearray', 'itemArray'));
    }

    
    public function hourly_sales_export() {
        $this->autoRender = false;
        App::import('Vendor', 'PHPExcel/PHPExcel');
    
        // Get date range and cashier filter from GET
        $date_range = $_GET['sdate'] ?? '';
        $cashier_id = $_GET['cashier'] ?? null;
    
        // Parse dates
        $dates = explode(" - ", $date_range);
        $start_date = trim($dates[0] ?? date('m/d/Y'));
        $end_date   = trim($dates[1] ?? date('m/d/Y'));
        $startdate  = date('Y-m-d', strtotime($start_date));
        $enddate    = date('Y-m-d', strtotime($end_date));
    
        // Generate hourly slots labels (12am-1am, 1am-2am, ..., 11pm-12am)
        $hourSlots = [];
        for ($h = 0; $h < 24; $h++) {
            $fromLabel = date("ga", strtotime("$h:00"));
            $toLabel   = date("ga", strtotime(($h + 1) . ":00"));
            $hourSlots[] = $fromLabel . '-' . $toLabel;
        }
    
        // Loop through each date
        $loopDate = $startdate;
        $itemArray = [];
    
        while (strtotime($loopDate) <= strtotime($enddate)) {
            foreach ($hourSlots as $h => $slot) {
                // Compute full datetime for SQL
                $fromDateTime = $loopDate . ' ' . str_pad($h, 2, '0', STR_PAD_LEFT) . ':00:00';
                $toDateTime   = $loopDate . ' ' . str_pad($h, 2, '0', STR_PAD_LEFT) . ':59:59';
    
                $sql = "
                    SELECT 
                        IFNULL(SUM(amount),0) AS totalsale,
                        COUNT(id) AS totalinvoice
                    FROM order_transactions
                    WHERE status = 2 
                      AND created BETWEEN '$fromDateTime' AND '$toDateTime'
                ";
                if ($cashier_id) {
                    $sql .= " AND store_id = " . (int)$cashier_id;
                }
    
                $result = $this->Order_transaction->query($sql);
                $row = $result[0][0] ?? ['totalsale' => 0, 'totalinvoice' => 0];
    
                $itemArray[$loopDate][$slot] = [
                    'totalsale'    => $row['totalsale'],
                    'totalinvoice' => $row['totalinvoice'],
                    'date'         => $loopDate
                ];
            }
            $loopDate = date("Y-m-d", strtotime("+1 day", strtotime($loopDate)));
        }
    
        // Create Excel
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()->setCreator("POS Export")->setTitle("Hourly Sales Report");
    
        $sheet = $objPHPExcel->setActiveSheetIndex(0);
        $sheet->setCellValue('A1', 'HOURLY SALES REPORT FROM ' . $start_date . ' TO ' . $end_date);
        $sheet->mergeCells('A1:Z1');
        $sheet->getStyle("A1:Z1")->getFont()->setBold(true);
    
        // Set headers
        $headers = ['Date'];
        foreach ($hourSlots as $slot) {
            $headers[] = $slot . ' (₹)';
            $headers[] = $slot . ' (Bills)';
        }
        foreach ($headers as $i => $header) {
            $sheet->setCellValueByColumnAndRow($i, 3, $header); // Row 3
        }
        $lastCol = PHPExcel_Cell::stringFromColumnIndex(count($headers) - 1);
        $sheet->getStyle("A3:{$lastCol}3")->getFont()->setBold(true);
    
        // Fill data
        $row = 4;
        $totals = [];
        $grandSale = 0;
        $grandInvoices = 0;
    
        foreach ($itemArray as $date => $hourlyData) {
            $col = 0;
            $sheet->setCellValueByColumnAndRow($col++, $row, $date);
    
            foreach ($hourSlots as $slot) {
                $sale    = (float)$hourlyData[$slot]['totalsale'];
                $invoice = (int)$hourlyData[$slot]['totalinvoice'];
    
                $sheet->setCellValueByColumnAndRow($col++, $row, number_format($sale, 2));
                $sheet->setCellValueByColumnAndRow($col++, $row, $invoice);
    
                if (!isset($totals[$slot])) {
                    $totals[$slot] = ['sale' => 0, 'invoice' => 0];
                }
                $totals[$slot]['sale'] += $sale;
                $totals[$slot]['invoice'] += $invoice;
    
                $grandSale += $sale;
                $grandInvoices += $invoice;
            }
            $row++;
        }
    
        // Add total row
        $col = 0;
        $sheet->setCellValueByColumnAndRow($col++, $row, 'TOTAL');
        foreach ($hourSlots as $slot) {
            $sheet->setCellValueByColumnAndRow($col++, $row, number_format($totals[$slot]['sale'], 2));
            $sheet->setCellValueByColumnAndRow($col++, $row, $totals[$slot]['invoice']);
        }
    
        // Add grand total
        $row += 2;
        $sheet->setCellValueByColumnAndRow(0, $row, 'GRAND TOTAL');
        $sheet->setCellValueByColumnAndRow(1, $row, number_format($grandSale, 2));
        $sheet->setCellValueByColumnAndRow(2, $row, $grandInvoices);
        $sheet->getStyle("A{$row}:C{$row}")->getFont()->setBold(true);
    
        $sheet->setTitle('Hourly Sales');
        $objPHPExcel->setActiveSheetIndex(0);
    
        // Output Excel
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="Hourly_Sales_Report_' . $start_date . '_to_' . $end_date . '.xls"');
        header('Cache-Control: max-age=0');
    
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

    public function bill_cancel() {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "users";
        $startDate = date('m/d/Y', strtotime('0 days'));
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }
        $cashier_id = $this->request->data['Search']['cashier'] ?? null;
        $cashierCondition = $cashier_id ? " and t.store_id = $cashier_id" : "";
    
        $transactions = $this->Order_transaction->query("
            SELECT 
                (SELECT name FROM locations WHERE id = t.store_id) AS cashier,
                t.orderno,
                t.reference_id,
                t.created,
                (
                    SELECT remarks 
                    FROM user_tracks 
                    WHERE reference_id = t.reference_id 
                    LIMIT 1
                ) AS remarks,
                MAX(t.price) AS price,
                MAX(t.amount) AS amount,
                (
                    SELECT GROUP_CONCAT(type_value) 
                    FROM order_payments 
                    WHERE reference_id = t.reference_id
                ) AS type
            FROM 
                order_transactions t
            WHERE 
                t.status = 0
                $cashierCondition
                AND t.created BETWEEN '{$startdate} 00:00:01' AND '{$enddate} 23:59:59'
            GROUP BY 
                t.reference_id
        ");
    
        
        
        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;
    
        $conditions = [
            'status' => 1,
            'type'   => 'Outlet'
        ];
        
        // Add location filter for non-admins
        if ($userRole !== 'admin' && !empty($userLocationId)) {
            $userLocationIds = Hash::extract(
                ['ids' => is_array($userLocationId) ? $userLocationId : explode(',', $userLocationId)],
                'ids.{n}'
            );
            $conditions['id IN'] = array_map('trim', $userLocationIds);
        }
        
        $users = $this->Location->find('all', [
            'conditions' => $conditions
        ]);
        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        $this->set(compact('users', 'transactions'));
    }
    
    public function bill_cancel_export() {
        $date_range = $_GET['sdate'] ?? '';
        $dates = explode(" - ", $date_range);
        $start_date = trim($dates[0]);
        $end_date = trim($dates[1]);
    
        $startdate = date('Y-m-d', strtotime($start_date));
        $enddate = date('Y-m-d', strtotime($end_date));
    
        $cashier_id = $_GET['cashier'] ?? null;
    
        if ($cashier_id) {
            $cashierData = $this->Location->find('first', ['conditions' => ['Location.id' => $cashier_id]]);
            $cashiername = $cashierData['Location']['name'] ?? 'Unknown';
            $cashierCondition = " and t.store_id = " . (int)$cashier_id;
        } else {
            $cashiername = 'All Stores';
            $cashierCondition = '';
        }
    
        $transactions = $this->Order_transaction->query("
            SELECT 
                (SELECT name FROM locations WHERE id = t.store_id) AS cashier,
                t.orderno,
                t.reference_id,
                t.created,
                (
                    SELECT remarks 
                    FROM user_tracks 
                    WHERE reference_id = t.reference_id 
                    LIMIT 1
                ) AS remarks,
                MAX(t.price) AS price,
                MAX(t.amount) AS amount,
                (
                    SELECT GROUP_CONCAT(type_value) 
                    FROM order_payments 
                    WHERE reference_id = t.reference_id
                ) AS type
            FROM 
                order_transactions t
            WHERE 
                t.status = 0
                $cashierCondition
                AND t.created BETWEEN '{$startdate} 00:00:01' AND '{$enddate} 23:59:59'
            GROUP BY 
                t.reference_id
        ");
        
        $datas = [];
        foreach ($transactions as $transaction) {
            $t = $transaction;
            
            $datas[] = [
                'bill_no' => $t['t']['orderno'],
                'cashierName' => $t[0]['cashier'],
                'type' => $t[0]['type'],
                'amount' => round($t[0]['amount'], 2),
                'remarks' => $t[0]['remarks'] ?? '',
                'created' => date('d-m-Y h:i A', strtotime($t['t']['created'])),
            ];
        }
        App::import('Vendor', 'PHPExcel/PHPExcel');
        error_reporting(0);
    
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()->setCreator("Aether")
            ->setTitle("Cancelled Bills Report")
            ->setDescription("Auto-generated Cancelled Bill Report");
    
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'BILL CANCEL REPORT FROM ' . $startdate . ' TO ' . $enddate);
    
        // Column Headers
        $headers = [
            'A3' => 'SR. NO.', 'B3' => 'Bill No', 'C3' => 'Store Name',
            'D3' => 'Payment Type', 'E3' => 'Date', 'F3' => 'Remarks','G3' => 'Amount'
        ];
    
        foreach ($headers as $cell => $value) {
            $objPHPExcel->getActiveSheet()->setCellValue($cell, $value);
        }
    
        $objPHPExcel->getActiveSheet()->mergeCells('A1:G1');
        $objPHPExcel->getActiveSheet()->getStyle('A1:G3')->getFont()->setBold(true);
    
        $baseRow = 3;
        $r = 1;
        foreach ($datas as $dat) {
            $rowNum = $baseRow + $r;
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue("A{$rowNum}", $r)
                ->setCellValue("B{$rowNum}", $dat['bill_no'])
                ->setCellValue("C{$rowNum}", $dat['cashierName'])
                ->setCellValue("D{$rowNum}", $dat['type'])
                ->setCellValue("E{$rowNum}", $dat['amount'])
                ->setCellValue("F{$rowNum}", $dat['remarks'])
                ->setCellValue("G{$rowNum}", $dat['created']);
            $r++;
        }
    
        // Finalize export
        $objPHPExcel->getActiveSheet()->setTitle('Cancelled Bills');
        $objPHPExcel->setActiveSheetIndex(0);
    
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="BILL_CANCEL_REPORT_' . date('Ymd_His') . '.xls"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
        header('Cache-Control: cache, must-revalidate');
        header('Pragma: public');
    
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }
    
    public function void_order() {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "users";
        $startDate = date('m/d/Y', strtotime('0 days'));
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }
        $cashier_id = $this->request->data['Search']['cashier'] ?? null;
        
        $conditions = [
            'Order_orderhistory.status' => 0,
            'Order_orderhistory.created >=' => $startdate . ' 00:00:01',
            'Order_orderhistory.created <=' => $enddate . ' 23:59:59',
        ];
        
        if (!empty($cashier_id)) {
            $conditions['Order_orderhistory.store_id'] = $cashier_id;
        }
        
        // Join user_tracks on reference_id and user_id
        $joins = [
            [
                'table' => 'user_tracks',
                'alias' => 'UserTrack',
                'type' => 'LEFT',
                'conditions' => [
                    'UserTrack.reference_id = Order_orderhistory.reference_id'
                ]
            ]
        ];
        
        $orderhistories = $this->Order_orderhistory->find('all', [
            'conditions' => $conditions,
            'joins' => $joins,
            'fields' => [
                'Order_orderhistory.*',
                'UserTrack.*'
            ],
            'order' => ['Order_orderhistory.id' => 'DESC']
        ]);
        // print_r($orderhistories);exit;
        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;
        
        $conditions = [
            'status' => 1,
            'type'   => 'Outlet'
        ];
        
        // Add location filter for non-admins
        if ($userRole !== 'admin' && !empty($userLocationId)) {
            $userLocationIds = Hash::extract(
                ['ids' => is_array($userLocationId) ? $userLocationId : explode(',', $userLocationId)],
                'ids.{n}'
            );
            $conditions['id IN'] = array_map('trim', $userLocationIds);
        }
        $users = $this->Location->find('all', [
            'conditions' => $conditions
        ]);
        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        $this->set(compact('users', 'orderhistories'));
    }
    
    public function void_order_export() {
        $date_range = $_GET['sdate'] ?? '';
        $dates = explode(" - ", $date_range);
        $start_date = trim($dates[0]);
        $end_date = trim($dates[1]);
    
        $startdate = date('Y-m-d', strtotime($start_date));
        $enddate = date('Y-m-d', strtotime($end_date));
    
        $cashier_id = $_GET['cashier'] ?? null;
    
        $conditions = [
            'Order_orderhistory.status' => 0,
            'Order_orderhistory.created >=' => $startdate . ' 00:00:01',
            'Order_orderhistory.created <=' => $enddate . ' 23:59:59',
        ];
        
        if (!empty($cashier_id)) {
            $conditions['Order_orderhistory.store_id'] = $cashier_id;
        }
        
        // Join user_tracks on reference_id and user_id
        $joins = [
            [
                'table' => 'user_tracks',
                'alias' => 'UserTrack',
                'type' => 'LEFT',
                'conditions' => [
                    'UserTrack.reference_id = Order_orderhistory.reference_id'
                ]
            ]
        ];
        
        $transactions = $this->Order_orderhistory->find('all', [
            'conditions' => $conditions,
            'joins' => $joins,
            'fields' => [
                'Order_orderhistory.*',
                'UserTrack.*'
            ],
            'order' => ['Order_orderhistory.id' => 'DESC']
        ]);
        
        $datas = [];
        foreach ($transactions as $transaction) {
            $t = $transaction;
            
            $datas[] = [
                'Product' => $t['Order_orderhistory']['product_name'],
                'Quantity' => $t['Order_orderhistory']['quantity'],
                'Price' => $t['Order_orderhistory']['price'],
                'Remarks' => $t['UserTrack']['remarks'],
                'By' => $t['UserTrack']['location_name'],
                'created' => date('d-m-Y h:i A', strtotime($t['Order_orderhistory']['created'])),
            ];
        }
        App::import('Vendor', 'PHPExcel/PHPExcel');
        error_reporting(0);
    
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()->setCreator("Aether")
            ->setTitle("Void Orders Report")
            ->setDescription("Auto-generated Void Orders Report");
    
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'VOID ORDER REPORT FROM ' . $startdate . ' TO ' . $enddate);
    
        // Column Headers
        $headers = [
            'A3' => 'SR. NO.', 'B3' => 'Product', 'C3' => 'Quantity',
            'D3' => 'Price', 'E3' => 'Remarks', 'F3' => 'By','G3' => 'Date'
        ];
    
        foreach ($headers as $cell => $value) {
            $objPHPExcel->getActiveSheet()->setCellValue($cell, $value);
        }
    
        $objPHPExcel->getActiveSheet()->mergeCells('A1:G1');
        $objPHPExcel->getActiveSheet()->getStyle('A1:G3')->getFont()->setBold(true);
    
        $baseRow = 3;
        $r = 1;
        foreach ($datas as $dat) {
            $rowNum = $baseRow + $r;
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue("A{$rowNum}", $r)
                ->setCellValue("B{$rowNum}", $dat['Product'])
                ->setCellValue("C{$rowNum}", $dat['Quantity'])
                ->setCellValue("D{$rowNum}", $dat['Price'])
                ->setCellValue("E{$rowNum}", $dat['Remarks'])
                ->setCellValue("F{$rowNum}", $dat['By'])
                ->setCellValue("G{$rowNum}", $dat['created']);
            $r++;
        }
    
        // Finalize export
        $objPHPExcel->getActiveSheet()->setTitle('Void Order');
        $objPHPExcel->setActiveSheetIndex(0);
    
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="VOID_ORDER_REPORT_' . date('Ymd_His') . '.xls"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
        header('Cache-Control: cache, must-revalidate');
        header('Pragma: public');
    
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }
    public function transaction_report() {
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        $this->layout = "users";
		
		$startDate = date('m/d/Y');
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }   
        
        
        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;
        
        
        if (!empty($this->request->data['Search']['cashier'])) {
            $cashier_id = $this->request->data['Search']['cashier'];
        } else {
            $cashier_id = null; 
        }
        if($cashier_id){
            $cashiernames=$this->Location->find('first',array('conditions'=>array('id'=>$cashier_id)));

            $cashiername=$cashiernames['Location']['name'];

            $where_location = " and store_id = " . (int)$cashier_id;
            
            $transactions = $this->Order_transaction->query("SELECT *,(select name from locations where id=order_transactions.store_id) as store_name,(SELECT GROUP_CONCAT(type_value) FROM `order_payments` WHERE reference_id=order_transactions.reference_id and store_id=order_transactions.store_id) as mode  FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' $where_location ORDER BY id desc");
        }else{
            if($userRole!='admin'){
                $where_location = "AND store_id IN (" . $userLocationId . ")";
            
                $transactions = $this->Order_transaction->query("SELECT *,(select name from locations where id=order_transactions.store_id) as store_name,(SELECT GROUP_CONCAT(type_value) FROM `order_payments` WHERE reference_id=order_transactions.reference_id and store_id=order_transactions.store_id) as mode  FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' $where_location ORDER BY id desc"); 
            }else{
                $cashiername='All Cashiers';
            
                $transactions = $this->Order_transaction->query("SELECT *,(select name from locations where id=order_transactions.store_id) as store_name,(SELECT GROUP_CONCAT(type_value) FROM `order_payments` WHERE reference_id=order_transactions.reference_id and store_id=order_transactions.store_id) as mode  FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' ORDER BY id desc");
            }
        }
    
		
		$this->set(compact('cashiername'));
		$yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        
        $conditions = [
            'status' => 1,
            'type'   => 'Outlet'
        ];
        
        if ($userRole !== 'admin' && !empty($userLocationId)) {
        
            $userLocationIds = Hash::extract(
                ['ids' => is_array($userLocationId) ? $userLocationId : explode(',', $userLocationId)],
                'ids.{n}'
            );
            $conditions['id IN'] = array_map('trim', $userLocationIds);
        }
        
        $users = $this->Location->find('all', [
            'conditions' => $conditions
        ]);

        $this->set(compact('users'));
	    
		$this->set(compact('transactions'));
	}
	
	public function transaction_reportexport() {
        $date_range= $_GET['sdate'];
	    $dates = explode(" - ", $date_range);
        $start_date = trim($dates[0]);
        $end_date = trim($dates[1]);
        $startdate= date('Y-m-d', strtotime($start_date));
        $enddate= date('Y-m-d', strtotime($end_date));

        $cashier_id=$_GET['cashier'];
        if($cashier_id){
            $cashiernames=$this->Location->find('first',array('conditions'=>array('id'=>$cashier_id)));
            $cashiername=$cashiernames['Location']['name'];

            $transactions = $this->Order_transaction->query("SELECT *,(SELECT GROUP_CONCAT(type_value) FROM `order_payments` WHERE reference_id=order_transactions.reference_id and store_id=order_transactions.store_id) as mode FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' and store_id=$cashier_id ORDER BY id desc");
        }else{
            $cashiername='All Cashiers';
            $transactions = $this->Order_transaction->query("SELECT *,(SELECT GROUP_CONCAT(type_value) FROM `order_payments` WHERE reference_id=order_transactions.reference_id and store_id=order_transactions.store_id) as mode FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' ORDER BY id desc");
        }
        
        $datas=array();
        // print_r($transactions);exit;
    	foreach($transactions as $transaction){
    	    if($transaction['order_transactions']['status']==0){
                $status='cancelled';
            }elseif($transaction['order_transactions']['status']==1){
                $status='pending';
            }elseif($transaction['order_transactions']['status']==2){
                $status='completed';
            }
            
            $datas[]=array(
				'txnid'=>$transaction['order_transactions']['reference_id'],
				'cashierName'=>$cashiername,
				'table_number'=>$transaction['order_transactions']['table_number'],
				'phone'=>$transaction['order_transactions']['phone'],
				'name'=>$transaction['order_transactions']['name'],
				'mode'=>$transaction[0]['mode'],
				'amount'=>round($transaction['order_transactions']['amount'],2),
				'status'=>$status,
				'created'=>$transaction['order_transactions']['created']
			);
    	}
        
        App::import('Vendor', 'PHPExcel/PHPExcel');
           error_reporting(0);
           ini_set('display_errors', TRUE);
           ini_set('display_startup_errors', TRUE);
           if (PHP_SAPI == 'cli')
                die('This example should only be run from a Web Browser');
           $objPHPExcel = new PHPExcel();
           // Set document properties
           $objPHPExcel->getProperties()->setCreator("Aether")
           ->setLastModifiedBy("Aether")
           ->setTitle("Office 2007 XLSX Aether Document")
           ->setSubject("Office 2007 XLSX Aether Document")
           ->setDescription("Aether Export Data File.")
           ->setKeywords("office 2007 openxml php")
           ->setCategory("AetherPos Export Data File");
           // Add some data
           $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', '   ' .'TRANSACTION REPORT FROM '.$startdate.' TO '.$enddate);
           
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A3', 'SR. NO.');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B3', 'Txn id');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C3', 'Store');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('D3', 'Table Number');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E3', 'Phone');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('F3', 'Name');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('G3', 'Payment Mode');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('H3', 'Amount');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('I3', 'Status');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('J3', 'Created');
            $objPHPExcel->getActiveSheet()->getStyle("A1:J3")->getFont()->setBold(true);
            $objPHPExcel->getActiveSheet()->mergeCells('A1:J1');
            
            $baseRow = 3;
            $r=1;
            
	        foreach($datas as $dat){
				  
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.($baseRow + $r),$r);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.($baseRow + $r),$dat['txnid']);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C'.($baseRow + $r),$dat['cashierName']);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('D'.($baseRow + $r),$dat['table_number']);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E'.($baseRow + $r),$dat['phone']);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('F'.($baseRow + $r),$dat['name']);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('G'.($baseRow + $r),$dat['mode']);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('H'.($baseRow + $r),$dat['amount']);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('I'.($baseRow + $r),$dat['status']);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('J'.($baseRow + $r),$dat['created']);
					   			  
						   $r++;
				   
				}
			    $objPHPExcel->getActiveSheet()->setTitle('Export Data');
                $objPHPExcel->setActiveSheetIndex(0);
                header('Content-Type: application/vnd.ms-excel');
                header('Content-Disposition: attachment;filename="'.'TRANSACTION REPORT.xls"');
                header('Cache-Control: max-age=0');
                header('Cache-Control: max-age=1');
                header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
                header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
                header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
                header ('Pragma: public'); // HTTP/1.0
                $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
                $objWriter->save('php://output');
                exit;
               
	}
	
	public function transaction_reportpdf() {
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
        $this->layout = "login";
	    if($this->request->is('post', 'put'))
        {
            $date_range=  $this->request->data['sdate'];
    	    $dates = explode(" - ", $date_range);
            $start_date = trim($dates[0]);
            $end_date = trim($dates[1]);
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
    
            $cashier_id=  $this->request->data['cashier'];
            if($cashier_id){
                $cashiernames=$this->Location->find('first',array('conditions'=>array('id'=>$cashier_id)));
                $cashiername=$cashiernames['Location']['name'];

                $transactions = $this->Order_transaction->query("SELECT *,(SELECT GROUP_CONCAT(type_value) FROM `order_payments` WHERE reference_id=order_transactions.reference_id and store_id=order_transactions.store_id) as mode FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' and store_id=$cashier_id ORDER BY id desc");
            }else{  
                $cashiername='All Stores';
                $transactions = $this->Order_transaction->query("SELECT *,(SELECT GROUP_CONCAT(type_value) FROM `order_payments` WHERE reference_id=order_transactions.reference_id and store_id=order_transactions.store_id) as mode FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' ORDER BY id desc");
            }
            
            $datas=array();
            // print_r($transactions);exit;
        	foreach($transactions as $transaction){
        	    if($transaction['order_transactions']['status']==0){
                    $status='cancelled';
                }elseif($transaction['order_transactions']['status']==1){
                    $status='pending';
                }elseif($transaction['order_transactions']['status']==2){
                    $status='completed';
                }
                
                $datas[]=array(
    				'txnid'=>$transaction['order_transactions']['reference_id'],
    				'cashierName'=>$cashiername,
    				'table_number'=>$transaction['order_transactions']['table_number'],
    				'phone'=>$transaction['order_transactions']['phone'],
    				'name'=>$transaction['order_transactions']['name'],
    				'mode'=>$transaction[0]['mode'],
    				'amount'=>round($transaction['order_transactions']['amount'],2),
    				'status'=>$status,
    				'created'=>$transaction['order_transactions']['created']
    			);
        	}
                
            $this->set(compact('startdate','enddate','datas'));
        }
    }
	public function item_sale_reportpdf() {
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
        $this->layout = "login";
	    if($this->request->is('post', 'put'))
        {
            $date_range=  $this->request->data['sdate'];
    	    $dates = explode(" - ", $date_range);
            $start_date = trim($dates[0]);
            $end_date = trim($dates[1]);
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
 
            $cashier_id=  $this->request->data['cashier'];
    	    if($cashier_id){
                $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 '$startdate 00:00:01' and '$enddate 23:59:59' and store_id=$cashier_id GROUP BY product_id");
            }else{
                $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 '$startdate 00:00:01' and '$enddate 23:59:59'  GROUP BY product_id");            
            }
            $datas=array();
        	foreach($orderhistories as $orderhistory){
    	        $datas[]=array(
    				'product_id'=>$orderhistory['order_orderhistories']['product_id'],
    				'product_name'=>$orderhistory['order_orderhistories']['product_name'],
    				'category_name'=>$orderhistory['order_orderhistories']['category_name'],
    				'totalquantity'=>$orderhistory[0]['totalquantity'],
    				'price'=>$orderhistory['order_orderhistories']['price']
    			);
        	}
            
            $this->set(compact('startdate','enddate','datas'));
        }
    }
	
	
	
    public function dsr_report()
    {
        if (!$this->Session->check('Auth.User.id')) {
            $this->redirect(array('controller' => 'dashboard', 'action' => 'login'));
        }

        $this->layout = "users";

        $startDate = date('m/d/Y', strtotime('0 days'));
        $endDate = date('m/d/Y');


        $this->loadModel('LocationMapping');
        $mappings = $this->LocationMapping->query("SELECT DISTINCT CONCAT('GRP', location_id) AS location_id, location_name FROM location_mapping WHERE status = 1 ORDER BY location_name ASC");

        if ($this->request->is('post', 'put')) {
            $daterange = $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate = date('Y-m-d', strtotime($start_date));
            $enddate = date('Y-m-d', strtotime($end_date));
        } else {
            $startdate = date('Y-m-d', strtotime($startDate));
            $enddate = date('Y-m-d', strtotime($endDate));
        }

        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;


        $conditions = [
            'status' => 1,
            'type' => 'Outlet'
        ];

        if ($userRole !== 'admin' && !empty($userLocationId)) {
            // Normalize to array in case of multiple IDs
            // $userLocationIds = is_array($userLocationId) ? $userLocationId : [$userLocationId];
            // $conditions['id IN'] = $userLocationIds; // CakePHP automatically handles IN
            $userLocationIds = Hash::extract(
                ['ids' => is_array($userLocationId) ? $userLocationId : explode(',', $userLocationId)],
                'ids.{n}'
            );
            $conditions['id IN'] = array_map('trim', $userLocationIds);
        }

        $isHouseOfKebab = false;
        $originalCashierId = null;

        if (!empty($this->request->data['Search']['cashier'])) {
            $cashier_input = $this->request->data['Search']['cashier'];
            if (is_array($cashier_input)) {
                $loc_id = $cashier_input;
            } else {
                $loc_id = array($cashier_input);
            }

            if (in_array('999', $loc_id)) {
                $isHouseOfKebab = true;
                $originalCashierId = 999;

                $loc_id = array_map(function ($id) {
                    return ($id == '999') ? '2' : $id;
                }, $loc_id);
            }
        } else {
            $loc_id = array();
        }

        $loc_id = array_filter($loc_id);
        if ($isHouseOfKebab) {
            App::uses('ConnectionManager', 'Model');

            $db = ConnectionManager::getDataSource('houseofkebab');

            $this->Order_payment->setDataSource('houseofkebab');
            $this->Order_transaction->setDataSource('houseofkebab');
            $this->Order_tax->setDataSource('houseofkebab');
        }


        if (!empty($loc_id)) {

            $loc_id = (array) $loc_id;
            $numericIds = [];
            $grpIds = [];

            foreach ($loc_id as $id) {
                if (is_string($id) && strpos($id, 'GRP') === 0) {
                    $grpIds[] = (int) str_replace('GRP', '', $id);
                } else {
                    $numericIds[] = (int) $id;
                }
            }

            if (!empty($grpIds)) {
                $mappedStoreIds = $this->LocationMapping->find('list', [
                    'fields' => ['store_id', 'store_id'],
                    'conditions' => [
                        'location_id' => $grpIds,
                        'status' => 1
                    ]
                ]);

                $numericIds = array_merge($numericIds, array_values($mappedStoreIds));
            }

            $loc_id = array_values(array_unique($numericIds));

            $cashiernames = $this->Location->find('list', array('fields' => array('name'), 'conditions' => array('id' => $loc_id)));
            $cashiername = implode(', ', $cashiernames);


            $where_location = "";
            $where_location = " and store_id IN (" . implode(',', $loc_id) . ")";
            $where_location_new = " WHERE store_id IN (" . implode(',', $loc_id) . ")";

            if ($isHouseOfKebab) {
                $cashiername = "HOUSE OF KEBAB, SECTOR - 66, GURUGRAM";
            }
            $payments = $this->Order_payment->query("SELECT SUM(amount) as total_amount,SUM(IF(type=1,amount,0)) AS cash,SUM(IF(type=2,amount,0)) AS card,SUM(IF(type=6,amount,0)) AS upi,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 and store_id=order_payments.store_id),2),0)) AS no_charge,SUM(IF(type=8,amount,0)) AS storecard FROM `order_payments` where status=2 and created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' $where_location");

            $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 00:00:01' and '$enddate 23:59:59' $where_location and status=2 and reference_id NOT IN (SELECT reference_id from order_payments WHERE type=7 and status=2 $where_location)");
            $transactionsnc = $this->Order_transaction->query("SELECT SUM(total_tax) AS total_tax FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' $where_location and status=2 and reference_id IN (SELECT reference_id from order_payments WHERE type=7 and status=2 $where_location)");

            $transactionsubtotal = $this->Order_transaction->query("SELECT SUM(price) AS price,SUM(discount) AS discount  FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' and status=2 $where_location");

            $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 00:00:01' and '$enddate 23:59:59' and status=2 and reference_id IN (SELECT reference_id FROM `order_orderhistories` WHERE status !=0 $where_location) $where_location GROUP by tax_id ");


            $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 00:00:01' and '$enddate 23:59:59' and status=2 and reference_id IN (SELECT reference_id FROM `order_orderhistories`   $where_location_new) $where_location GROUP by kds,tax_id) as sub GROUP by kds,tax_value) as final GROUP by kds,tax_percentage");

            $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 00:00:01' and '$enddate 23:59:59' AND status = 2 and tax_percentage!=0 and reference_id IN (SELECT reference_id FROM `order_orderhistories` WHERE status !=0 $where_location) $where_location GROUP BY tax_id ) AS order_tax");

            $transactionswithnctax = $this->Order_transaction->query("SELECT SUM(total_tax) AS total_tax FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' $where_location and status=2 ");
            $transactionscount = $this->Order_transaction->query("SELECT COUNT(id) as total_count FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' $where_location and status=2 ");

        } else {
            $cashiername = 'All Stores';
            if ($userRole != 'admin') {

                $where_location = "AND store_id IN (" . $userLocationId . ")";

                $payments = $this->Order_payment->query("SELECT SUM(amount) as total_amount,SUM(IF(type=1,amount,0)) AS cash,SUM(IF(type=2,amount,0)) AS card,SUM(IF(type=6,amount,0)) AS upi,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 00:00:01' and '$enddate 23:59:59' $where_location");

                $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 00:00:01' and '$enddate 23:59:59' $where_location and status=2 and reference_id NOT IN (SELECT reference_id from order_payments WHERE type=7 and status=2 $where_location)");

                $transactionsnc = $this->Order_transaction->query("SELECT SUM(total_tax) AS total_tax FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' $where_location and status=2 and reference_id IN (SELECT reference_id from order_payments WHERE type=7 and status=2 $where_location)");

                $transactionsubtotal = $this->Order_transaction->query("SELECT SUM(price) AS price,SUM(discount) AS discount  FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' and status=2 $where_location");

                $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 00:00:01' and '$enddate 23:59:59' and status=2 and reference_id IN (SELECT reference_id FROM `order_orderhistories` WHERE  status !=0 $where_location) $where_location GROUP by tax_id ");

                $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 00:00:01' and '$enddate 23:59:59' and status=2 and reference_id IN (SELECT reference_id FROM `order_orderhistories`  $where_location_new) $where_location GROUP by kds,tax_id) as sub GROUP by kds,tax_value) as final GROUP by kds,tax_percentage");

                $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 00:00:01' and '$enddate 23:59:59' AND status = 2 and tax_percentage!=0 and reference_id IN (SELECT reference_id FROM `order_orderhistories` WHERE  status !=0 $where_location) $where_location GROUP BY tax_id ) AS order_tax");

                $transactionswithnctax = $this->Order_transaction->query("SELECT SUM(total_tax) AS total_tax FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' $where_location and status=2");
                $transactionscount = $this->Order_transaction->query("SELECT COUNT(id) as total_count FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' $where_location and status=2 ");

            } else {

                $payments = $this->Order_payment->query("SELECT SUM(amount) as total_amount,SUM(IF(type=1,amount,0)) AS cash,SUM(IF(type=2,amount,0)) AS card,SUM(IF(type=6,amount,0)) AS upi,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 00:00:01' and '$enddate 23:59:59' ");

                $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(round) AS round,SUM(price) AS price  FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' and status=2 and reference_id NOT IN (SELECT reference_id from order_payments WHERE type=7 and status=2)");

                $transactionsnc = $this->Order_transaction->query("SELECT SUM(total_tax) AS total_tax FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' and status=2 and reference_id 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 00:00:01' and '$enddate 23:59:59' and status=2");

                $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 00:00:01' and '$enddate 23:59:59' and status=2  GROUP by tax_id");

                $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 00:00:01' and '$enddate 23:59:59' and status=2 GROUP by kds,tax_id) as sub GROUP by kds,tax_value) as final GROUP by kds,tax_percentage");

                $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 00:00:01' and '$enddate 23:59:59' AND status = 2 and tax_percentage!=0 GROUP BY tax_id ) AS order_tax");

                //
                $transactionswithnctax = $this->Order_transaction->query("SELECT SUM(total_tax) AS total_tax  FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' and status=2");
                $transactionscount = $this->Order_transaction->query("SELECT COUNT(id) as total_count  FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' and status=2");


            }
        }

        if ($isHouseOfKebab) {
            $this->Order_payment->setDataSource('default');
            $this->Order_transaction->setDataSource('default');
            $this->Order_tax->setDataSource('default');
        }

        $taxable_price = 0;
        foreach ($taxablepricess as $taxableprices) {
            $taxable_price = round($taxable_price + $taxableprices['order_tax']['taxable_price'], 2);
        }

        $yourStartDateValue = $startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);

        $users = $this->Location->find('all', array('conditions' => $conditions));

        $this->set(compact('users'));
        $this->set(compact('mappings'));
        // print_r($transactionsubtotal);exit;
        $this->set(compact('transactionscount', 'payments', 'cashiername', 'transactions', 'taxes', 'taxable_price', 'sales', 'transactionsubtotal', 'transactionsnc', 'transactionswithnctax'));
    }

    public function dsr_reportexport()
    {
        $date_range = $_GET['sdate'];
        $dates = explode(" - ", $date_range);
        $start_date = trim($dates[0]);
        $end_date = trim($dates[1]);
        $startdate = date('Y-m-d', strtotime($start_date));
        $enddate = date('Y-m-d', strtotime($end_date));

        $cashier_id = $_GET['cashier'];

        $storesToProcess = [];
        $isHouseOfKebab = false;

        if ($cashier_id) {
            $loc_ids = explode(',', $cashier_id);
            $loc_ids = array_filter($loc_ids);

            if (in_array('999', $loc_ids)) {
                $isHouseOfKebab = true;
                $loc_ids = array_map(function ($id) {
                    return ($id == '999') ? '2' : $id;
                }, $loc_ids);

                App::uses('ConnectionManager', 'Model');
                $db = ConnectionManager::getDataSource('houseofkebab');

                $this->Order_payment->setDataSource('houseofkebab');
                $this->Order_transaction->setDataSource('houseofkebab');
                $this->Order_tax->setDataSource('houseofkebab');

                $storesToProcess = [
                    '2' => 'HOUSE OF KEBAB, SECTOR - 66, GURUGRAM'
                ];
            }

            else{
                    
                if (!empty($loc_ids)) {
                    $loc_ids = (array) $loc_ids;
                    $numericIds = [];
                    $grpIds = [];

                    foreach ($loc_ids as $id) {
                        if (is_string($id) && strpos($id, 'GRP') === 0) {
                            $grpIds[] = (int) str_replace('GRP', '', $id);
                        } else {
                            $numericIds[] = (int) $id;
                        }
                    }
                    
                    if (!empty($grpIds)) {
                        $this->loadModel('LocationMapping');

                        $combineCount = $this->LocationMapping->find('count', [
                            'conditions' => [
                                'location_id' => $grpIds,
                                'status' => 1,
                                'is_combine' => 1
                            ]
                        ]);

                        if ($combineCount > 0) {
                            
                            $mappedStoreIds = $this->LocationMapping->find('list', [
                                'fields' => ['store_id', 'store_id'],
                                'conditions' => [
                                    'location_id' => $grpIds,
                                    'status' => 1
                                ]
                            ]);
                            $numericIds = array_merge($numericIds, array_values($mappedStoreIds));
                            $final_loc_ids = array_values(array_unique($numericIds));

                            return $this->_dsrCombinedReport($startdate, $enddate, $final_loc_ids);
                        }
                        else{
                            $mappedStoreIds = $this->LocationMapping->find('list', [
                                'fields' => ['store_id', 'store_id'],
                                'conditions' => [
                                    'location_id' => $grpIds,
                                    'status' => 1
                                ]
                            ]);
                            $numericIds = array_merge($numericIds, array_values($mappedStoreIds));
                        }
                    }

                    $final_loc_ids = array_values(array_unique($numericIds));

                    $storesToProcess = $this->Location->find('list', array(
                        'fields' => array('id', 'name'),
                        'conditions' => array('id' => $final_loc_ids)
                    ));

                }

            }

        } else {
            $storesToProcess = ['All' => 'All Stores'];
        }

        App::import('Vendor', 'PHPExcel/PHPExcel');
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()->setCreator("Aether")->setTitle("DSR Report Export");

        $sheetIndex = 0;

        foreach ($storesToProcess as $storeId => $storeName) {

            if ($isHouseOfKebab && $storeId == 'All') {
                $storeName = "HOUSE OF KEBAB, SECTOR - 66, GURUGRAM";
            }

            if ($sheetIndex > 0) {
                $objPHPExcel->createSheet();
            }
            $objPHPExcel->setActiveSheetIndex($sheetIndex);
            $sheet = $objPHPExcel->getActiveSheet();

            $sheetTitle = substr(preg_replace('/[\/\\\?\*\[\]]/', '', $storeName), 0, 30);
            $sheet->setTitle($sheetTitle ?: 'Sheet' . $sheetIndex);

            $authUser = $this->Session->read('Auth.User');
            $userRole = $authUser['role'] ?? '';
            $userLocationId = $authUser['location_ids'] ?? 0;

            $datas = array();
            $allTaxTypes = [];
            $allSalesTypes = [];

            $period = new DatePeriod(
                new DateTime($startdate),
                new DateInterval('P1D'),
                (new DateTime($enddate))->modify('+1 day')
            );

            foreach ($period as $dateObj) {
                $day = $dateObj->format('Y-m-d');
                $dayStart = "$day 00:00:01";
                $dayEnd = "$day 23:59:59";

                $cashierFilter = "";
                $cashierFilternew = "";
                $cashierFilternewwithoutnochrage = "";

                if ($storeId !== 'All') {
                    
                    $currentStoreId = $storeId;

                    $cashierFilter = " AND store_id = $currentStoreId";
                    $cashierFilternew = " AND reference_id IN (
                        SELECT reference_id
                        FROM order_orderhistories
                        WHERE reference_id NOT IN (SELECT reference_id from order_payments WHERE type=7 and status=2 AND store_id = $currentStoreId)
                        AND store_id = $currentStoreId
                    )";
                    $cashierFilternewwithoutnochrage = " AND reference_id IN (
                        SELECT reference_id
                        FROM order_orderhistories
                        WHERE  store_id = $currentStoreId
                    )";

                } else {
                    
                    if ($userRole != 'admin') {
                        $cashierFilter = " AND store_id IN (" . $userLocationId . ")";
                        
                        $cashierFilternew = " AND reference_id IN (
                             SELECT reference_id
                             FROM order_orderhistories
                             WHERE reference_id NOT IN (SELECT reference_id from order_payments WHERE type=7 and status=2 AND store_id IN (" . $userLocationId . "))
                             AND store_id IN (" . $userLocationId . ")
                         )";
                        $cashierFilternewwithoutnochrage = " AND reference_id IN (
                             SELECT reference_id
                             FROM order_orderhistories
                             WHERE store_id IN (" . $userLocationId . ")
                         )";
                    } else {
                        
                        $cashierFilter = '';
                        $cashierFilternew = '';
                        $cashierFilternewwithoutnochrage = '';
                    }
                }

                $noChargeFilter = "reference_id NOT IN (SELECT reference_id from order_payments WHERE type=7 and status=2 $cashierFilter)";

                $payments = $this->Order_payment->query("SELECT SUM(amount) as total_amount,
                    SUM(IF(type=1,amount,0)) AS cash,
                    SUM(IF(type=2,amount,0)) AS card,
                    SUM(IF(type=6,amount,0)) AS upi,
                    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 total_tax from order_transactions WHERE reference_id=order_payments.reference_id $cashierFilter limit 1),2),0)) AS no_charge,
                    SUM(IF(type=8,amount,0)) AS storecard
                    FROM order_payments
                    WHERE status=2 and created BETWEEN '$dayStart' AND '$dayEnd' $cashierFilter");

                $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 roundamount
                    FROM order_transactions
                    WHERE created BETWEEN '$dayStart' AND '$dayEnd' AND status=2 $cashierFilter AND $noChargeFilter");

                $transactionsnc = $this->Order_transaction->query("SELECT 
                    SUM(total_tax) AS total_tax
                    FROM order_transactions
                    WHERE created BETWEEN '$dayStart' AND '$dayEnd' AND status=2 $cashierFilter AND reference_id IN (SELECT reference_id from order_payments WHERE type=7 and status=2 $cashierFilter)");

                $transactionsubtotal = $this->Order_transaction->query("SELECT SUM(price) AS price,
                    SUM(discount) AS discount FROM order_transactions
                    WHERE created BETWEEN '$dayStart' AND '$dayEnd' AND status=2 $cashierFilter");

                $taxes = $this->Order_tax->query("SELECT tax_id,tax_name,tax_percentage,sum(tax_value) as tax_value FROM `order_tax` WHERE  created BETWEEN '$dayStart' and '$dayEnd' and status=2 $cashierFilter  GROUP by tax_id");

                foreach ($taxes as $t) {
                    $key = $t['order_tax']['tax_name'] . "(" . $t['order_tax']['tax_percentage'] . "%)";
                    $allTaxTypes[$key] = true;
                }

                $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 '$dayStart' and '$dayEnd' and status=2  $cashierFilternewwithoutnochrage $cashierFilter GROUP by kds,tax_id) as sub GROUP by kds,tax_value) as final GROUP by kds,tax_percentage");

                foreach ($sales as $s) {
                    $key = $s['final']['kds_name'] . "(" . $s['final']['tax_percentage'] . "%)";
                    $allSalesTypes[$key] = true;
                }

                $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  '$dayStart' and '$dayEnd' AND status = 2 and tax_percentage!=0  $cashierFilter GROUP BY tax_id ) AS order_tax");
                $taxable_price = 0;
                foreach ($taxablepricess as $taxableprices) {
                    $taxable_price += round($taxableprices['order_tax']['taxable_price'], 2);
                }

                $transactionswithnctax = $this->Order_transaction->query("SELECT SUM(total_tax) AS total_tax  FROM `order_transactions` where  created BETWEEN '$dayStart' and '$dayEnd' and status=2 $cashierFilter");
                $transactionscount = $this->Order_transaction->query("SELECT COUNT(id) as total_count
                    FROM order_transactions
                    WHERE created BETWEEN '$dayStart' AND '$dayEnd' AND status=2 $cashierFilter");

                $datas[] = array(
                    'date' => $day,
                    'cashier' => $storeName,
                    'total_collection' => round($payments[0][0]['total_amount'], 2),
                    'cash' => round($payments[0][0]['cash'], 2),
                    'card' => round($payments[0][0]['card'], 2),
                    'online' => round($payments[0][0]['online'], 2),
                    'upi' => round($payments[0][0]['upi'], 2),
                    'storecard' => round($payments[0][0]['storecard'], 2),
                    'no_charge' => round($payments[0][0]['no_charge_with_tax'] - $transactionsnc[0][0]['total_tax'], 2),
                    'no_charge_with_tax' => round($payments[0][0]['no_charge_with_tax'], 2),
                    'subtotal' => round($transactionsubtotal[0][0]['price'], 2),
                    'discount' => round($transactionsubtotal[0][0]['discount'], 2),
                    'taxable_amount' => round($taxable_price, 2),
                    'service_charge' => round($transactions[0][0]['servicecharge'], 2),
                    'delivery_charge' => round($transactions[0][0]['delivery_charge'], 2),
                    'packing_charge' => round($transactions[0][0]['packing_charge'], 2),
                    'total_tax' => round($transactionswithnctax[0][0]['total_tax'], 2),
                    'bill_count' => round($transactionscount[0][0]['total_count'], 2),
                    'net_amount' => round($transactions[0][0]['amount'] + $payments[0][0]['no_charge_with_tax'], 2),
                    'round' => $transactions[0][0]['roundamount'],
                    'taxes' => $taxes,
                    'sales' => $sales
                );
            } 
            
            $taxColumns = array_keys($allTaxTypes);
            $salesColumns = array_keys($allSalesTypes);
            sort($taxColumns);
            sort($salesColumns);

            $headers = ['Date', 'Store', 'Total Collection', 'Cash', 'Card', 'Online', 'Upi', 'Storecard', 'No Charge With Tax', 'Subtotal', 'Discount', 'No Charge', 'Taxable', 'Service', 'Delivery', 'Packing', 'Total Tax', 'Bill Count', 'Net Amount', 'Round'];
            $headers = array_merge($headers, $taxColumns, $salesColumns);
            $sheet->fromArray($headers, null, 'A1');

            $row = 2;
            foreach ($datas as $data) {
                $sheet->setCellValue("A$row", $data['date']);
                $sheet->setCellValue("B$row", $data['cashier']);
                $sheet->setCellValue("C$row", $data['total_collection']);
                $sheet->setCellValue("D$row", $data['cash']);
                $sheet->setCellValue("E$row", $data['card']);
                $sheet->setCellValue("F$row", $data['online']);
                $sheet->setCellValue("G$row", $data['upi']);
                $sheet->setCellValue("H$row", $data['storecard']);
                $sheet->setCellValue("I$row", $data['no_charge_with_tax']);
                $sheet->setCellValue("J$row", $data['subtotal']);
                $sheet->setCellValue("K$row", $data['discount']);
                $sheet->setCellValue("L$row", $data['no_charge']);
                $sheet->setCellValue("M$row", $data['taxable_amount']);
                $sheet->setCellValue("N$row", $data['service_charge']);
                $sheet->setCellValue("O$row", $data['delivery_charge']);
                $sheet->setCellValue("P$row", $data['packing_charge']);
                $sheet->setCellValue("Q$row", $data['total_tax']);
                $sheet->setCellValue("R$row", $data['bill_count']);
                $sheet->setCellValue("S$row", $data['net_amount']);
                $sheet->setCellValue("T$row", $data['round']);

                $taxValues = array_fill_keys($taxColumns, 0);
                foreach ($data['taxes'] as $t) {
                    $key = $t['order_tax']['tax_name'] . "(" . $t['order_tax']['tax_percentage'] . "%)";
                    $taxValues[$key] = round($t['0']['tax_value'], 2);
                }
                $colIndex = 20;
                foreach ($taxColumns as $taxCol) {
                    $sheet->setCellValueByColumnAndRow($colIndex++, $row, $taxValues[$taxCol]);
                }

                $salesValues = array_fill_keys($salesColumns, 0);
                foreach ($data['sales'] as $s) {
                    $key = $s['final']['kds_name'] . "(" . $s['final']['tax_percentage'] . "%)";
                    $salesValues[$key] = round($s['final']['value'], 2);
                }
                foreach ($salesColumns as $salesCol) {
                    $sheet->setCellValueByColumnAndRow($colIndex++, $row, $salesValues[$salesCol]);
                }

                $row++;
            }

            $sheetIndex++;

        } 

        if ($isHouseOfKebab) {
            $this->Order_payment->setDataSource('default');
            $this->Order_transaction->setDataSource('default');
            $this->Order_tax->setDataSource('default');
        }

        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="DSR_REPORT.xls"');
        header('Cache-Control: max-age=0');
        $writer = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $writer->save('php://output');
        exit;
    }

    private function _dsrCombinedReport($startdate, $enddate, $loc_ids)
    {

        if (!empty($loc_ids)) {
            $cashiernames = $this->Location->find('list', array('fields' => array('name'), 'conditions' => array('id' => $loc_ids)));
            
            $cashiername = implode(', ', $cashiernames);
        }
        
        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;

        $datas = array();
        $allTaxTypes = [];
        $allSalesTypes = [];
    
        $period = new DatePeriod(
            new DateTime($startdate),
            new DateInterval('P1D'),
            (new DateTime($enddate))->modify('+1 day')
        );
    
        foreach ($period as $dateObj) {
            $day = $dateObj->format('Y-m-d');
            $dayStart = "$day 00:00:01";
            $dayEnd = "$day 23:59:59";
            
            if ($userRole != 'admin') {

                if (!empty($loc_ids)) {
                    $cashierFilter = " AND store_id IN (" . implode(',', $loc_ids) . ")";
                    $cashierFilternew = " AND reference_id IN (
                        SELECT reference_id
                        FROM order_orderhistories
                        WHERE reference_id NOT IN (SELECT reference_id from order_payments WHERE type=7 and status=2 AND store_id IN (" . implode(',', $loc_ids) . "))
                        AND store_id IN (" . implode(',', $loc_ids) . ")
                    )";
                    $cashierFilternewwithoutnochrage = " AND reference_id IN (
                        SELECT reference_id
                        FROM order_orderhistories
                        WHERE  store_id IN (" . implode(',', $loc_ids) . ")
                    )";
                } else {
                    $cashierFilter = " AND store_id IN (" . $userLocationId . ")";
                    $cashierFilternew = " AND reference_id IN (
                        SELECT reference_id
                        FROM order_orderhistories
                        WHERE reference_id NOT IN (SELECT reference_id from order_payments WHERE type=7 and status=2 AND store_id IN (" . $userLocationId . "))
                        AND store_id IN (" . $userLocationId . ")
                    )";
                    $cashierFilternewwithoutnochrage = " AND reference_id IN (
                        SELECT reference_id
                        FROM order_orderhistories
                        WHERE store_id IN (" . $userLocationId . ")
                    )";
                }
            
            } else {
            
                if (!empty($loc_ids)) {
                    $cashierFilter = " AND store_id IN (" . implode(',', $loc_ids) . ")";
                    $cashierFilternew = " AND reference_id IN (
                        SELECT reference_id
                        FROM order_orderhistories
                        WHERE reference_id NOT IN (SELECT reference_id from order_payments WHERE type=7 and status=2 AND store_id IN (" . implode(',', $loc_ids) . "))
                        AND store_id IN (" . implode(',', $loc_ids) . ")
                    )";
                    $cashierFilternewwithoutnochrage = " AND reference_id IN (
                        SELECT reference_id
                        FROM order_orderhistories
                        WHERE  store_id IN (" . implode(',', $loc_ids) . ")
                    )";
                } else {
                    $cashierFilter = '';
                    $cashierFilternew = ''; // This matches dsr_report() admin behavior
                    $cashierFilternewwithoutnochrage='';
                }
            }


            $noChargeFilter = "reference_id NOT IN (SELECT reference_id from order_payments WHERE type=7 and status=2 $cashierFilter)";
    
            $payments = $this->Order_payment->query("SELECT SUM(amount) as total_amount,
                SUM(IF(type=1,amount,0)) AS cash,
                SUM(IF(type=2,amount,0)) AS card,
                SUM(IF(type=6,amount,0)) AS upi,
                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 total_tax from order_transactions WHERE reference_id=order_payments.reference_id $cashierFilter limit 1),2),0)) AS no_charge,
                SUM(IF(type=8,amount,0)) AS storecard
                FROM order_payments
                WHERE status=2 and created BETWEEN '$dayStart' AND '$dayEnd' $cashierFilter");
    
            $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 roundamount
                FROM order_transactions
                WHERE created BETWEEN '$dayStart' AND '$dayEnd' AND status=2 $cashierFilter AND $noChargeFilter");
            
            $transactionsnc = $this->Order_transaction->query("SELECT 
                SUM(total_tax) AS total_tax
                FROM order_transactions
                WHERE created BETWEEN '$dayStart' AND '$dayEnd' AND status=2 $cashierFilter AND reference_id IN (SELECT reference_id from order_payments WHERE type=7 and status=2 $cashierFilter)");
     
            $transactionsubtotal = $this->Order_transaction->query("SELECT SUM(price) AS price,
                SUM(discount) AS discount FROM order_transactions
                WHERE created BETWEEN '$dayStart' AND '$dayEnd' AND status=2 $cashierFilter");
            
            $taxes = $this->Order_tax->query("SELECT tax_id,tax_name,tax_percentage,sum(tax_value) as tax_value FROM `order_tax` WHERE  created BETWEEN '$dayStart' and '$dayEnd' and status=2 $cashierFilter  GROUP by tax_id");
    
            foreach ($taxes as $t) {
                $key = $t['order_tax']['tax_name'] . "(" . $t['order_tax']['tax_percentage'] . "%)";
                $allTaxTypes[$key] = true;
            }
    
            $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 '$dayStart' and '$dayEnd' and status=2  $cashierFilternewwithoutnochrage $cashierFilter GROUP by kds,tax_id) as sub GROUP by kds,tax_value) as final GROUP by kds,tax_percentage");
    
            foreach ($sales as $s) {
                $key = $s['final']['kds_name'] . "(" . $s['final']['tax_percentage'] . "%)";
                $allSalesTypes[$key] = true;
            }
    
            $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  '$dayStart' and '$dayEnd' AND status = 2 and tax_percentage!=0  $cashierFilter GROUP BY tax_id ) AS order_tax");
            $taxable_price = 0;
            foreach ($taxablepricess as $taxableprices) {
                $taxable_price += round($taxableprices['order_tax']['taxable_price'], 2);
            }
            
            $transactionswithnctax = $this->Order_transaction->query("SELECT SUM(total_tax) AS total_tax  FROM `order_transactions` where  created BETWEEN '$dayStart' and '$dayEnd' and status=2 $cashierFilter");
            $transactionscount = $this->Order_transaction->query("SELECT COUNT(id) as total_count
                FROM order_transactions
                WHERE created BETWEEN '$dayStart' AND '$dayEnd' AND status=2 $cashierFilter");
    
            $datas[] = array(
                'date' => $day,
                'cashier' => $cashiername,
                'total_collection' => round($payments[0][0]['total_amount'] , 2),
                'cash' => round($payments[0][0]['cash'], 2),
                'card' => round($payments[0][0]['card'], 2),
                'online' => round($payments[0][0]['online'], 2),
                'upi' => round($payments[0][0]['upi'], 2),
                'storecard' => round($payments[0][0]['storecard'], 2),
                'no_charge' => round($payments[0][0]['no_charge_with_tax'] - $transactionsnc[0][0]['total_tax'], 2),
                'no_charge_with_tax' => round($payments[0][0]['no_charge_with_tax'], 2),
                'subtotal' => round($transactionsubtotal[0][0]['price'], 2),
                'discount' => round($transactionsubtotal[0][0]['discount'], 2),
                'taxable_amount' => round($taxable_price, 2),
                'service_charge' => round($transactions[0][0]['servicecharge'], 2),
                'delivery_charge' => round($transactions[0][0]['delivery_charge'], 2),
                'packing_charge' => round($transactions[0][0]['packing_charge'], 2),
                'total_tax' => round($transactionswithnctax[0][0]['total_tax'], 2),
                'bill_count' => round($transactionscount[0][0]['total_count'], 2),
                'net_amount' => round($transactions[0][0]['amount']+$payments[0][0]['no_charge_with_tax'], 2),
                'round' => $transactions[0][0]['roundamount'],
                'taxes' => $taxes,
                'sales' => $sales
            );
        }
        
        App::import('Vendor', 'PHPExcel/PHPExcel');
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()->setCreator("Aether")->setTitle("DSR Report Export");
        $sheet = $objPHPExcel->getActiveSheet();
        $sheet->setTitle('DSR Report');
    
        $taxColumns = array_keys($allTaxTypes);
        $salesColumns = array_keys($allSalesTypes);
        sort($taxColumns);
        sort($salesColumns);
    
        $headers = ['Date', 'Store', 'Total Collection', 'Cash', 'Card', 'Online', 'Upi', 'Storecard', 'No Charge With Tax', 'Subtotal', 'Discount', 'No Charge', 'Taxable', 'Service', 'Delivery', 'Packing', 'Total Tax', 'Bill Count', 'Net Amount', 'Round'];
        $headers = array_merge($headers, $taxColumns, $salesColumns);
        $sheet->fromArray($headers, null, 'A1');
    
        $row = 2;
        foreach ($datas as $data) {
            // print_r($data['round']);exit;
            $sheet->setCellValue("A$row", $data['date']);
            $sheet->setCellValue("B$row", $data['cashier']);
            $sheet->setCellValue("C$row", $data['total_collection']);
            $sheet->setCellValue("D$row", $data['cash']);
            $sheet->setCellValue("E$row", $data['card']);
            $sheet->setCellValue("F$row", $data['online']);
            $sheet->setCellValue("G$row", $data['upi']);
            $sheet->setCellValue("H$row", $data['storecard']);
            $sheet->setCellValue("I$row", $data['no_charge_with_tax']);
            $sheet->setCellValue("J$row", $data['subtotal']);
            $sheet->setCellValue("K$row", $data['discount']);
            $sheet->setCellValue("L$row", $data['no_charge']);
            $sheet->setCellValue("M$row", $data['taxable_amount']);
            $sheet->setCellValue("N$row", $data['service_charge']);
            $sheet->setCellValue("O$row", $data['delivery_charge']);
            $sheet->setCellValue("P$row", $data['packing_charge']);
            $sheet->setCellValue("Q$row", $data['total_tax']);
            $sheet->setCellValue("R$row", $data['bill_count']);
            $sheet->setCellValue("S$row", $data['net_amount']);
            $sheet->setCellValue("T$row", $data['round']);
    
            $taxValues = array_fill_keys($taxColumns, 0);
            foreach ($data['taxes'] as $t) {
                $key = $t['order_tax']['tax_name'] . "(" . $t['order_tax']['tax_percentage'] . "%)";
                $taxValues[$key] = round($t['0']['tax_value'], 2);
            }
            $colIndex = 20;
            foreach ($taxColumns as $taxCol) {
                $sheet->setCellValueByColumnAndRow($colIndex++, $row, $taxValues[$taxCol]);
            }
    
            $salesValues = array_fill_keys($salesColumns, 0);
            foreach ($data['sales'] as $s) {
                $key = $s['final']['kds_name'] . "(" . $s['final']['tax_percentage'] . "%)";
                $salesValues[$key] = round($s['final']['value'], 2);
            }
            foreach ($salesColumns as $salesCol) {
                $sheet->setCellValueByColumnAndRow($colIndex++, $row, $salesValues[$salesCol]);
            }
    
            $row++;
        }
    
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="DSR_REPORT.xls"');
        header('Cache-Control: max-age=0');
        $writer = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $writer->save('php://output');
        exit;
    
    }

    public function dsr_reportpdf()
    {
        if (!$this->Session->check('Auth.User.id')) {
            $this->redirect(array('controller' => 'dashboard', 'action' => 'login'));
        }

        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;

        $this->layout = "login";
        if ($this->request->is('post', 'put')) {
            $date_range = $this->request->data['sdate'];
            $dates = explode(" - ", $date_range);
            $start_date = trim($dates[0]);
            $end_date = trim($dates[1]);
            $startdate = date('Y-m-d', strtotime($start_date));
            $enddate = date('Y-m-d', strtotime($end_date));

            $cashier_id = $this->request->data['cashier'];

            $isHouseOfKebab = false;

            $loc_ids = [];
            if ($cashier_id) {
                $loc_ids = explode(',', $cashier_id);
                $loc_ids = array_filter($loc_ids);

                if (in_array('999', $loc_ids)) {
                    $isHouseOfKebab = true;

                    $loc_ids = array_map(function ($id) {
                        return ($id == '999') ? '2' : $id;
                    }, $loc_ids);
                }
            }

            if ($isHouseOfKebab) {
                App::uses('ConnectionManager', 'Model');

                $db = ConnectionManager::getDataSource('houseofkebab');

                $this->Order_payment->setDataSource('houseofkebab');
                $this->Order_transaction->setDataSource('houseofkebab');
                $this->Order_tax->setDataSource('houseofkebab');
            }

            if (!empty($loc_ids)) {


                $loc_ids = (array) $loc_ids;
                $numericIds = [];
                $grpIds = [];

                foreach ($loc_ids as $id) {
                    if (is_string($id) && strpos($id, 'GRP') === 0) {
                        $grpIds[] = (int) str_replace('GRP', '', $id);
                    } else {
                        $numericIds[] = (int) $id;
                    }
                }

                if (!empty($grpIds)) {

                    $this->loadModel('LocationMapping');
                    $mappedStoreIds = $this->LocationMapping->find('list', [
                        'fields' => ['store_id', 'store_id'],
                        'conditions' => [
                            'location_id' => $grpIds,
                            'status' => 1
                        ]
                    ]);

                    $numericIds = array_merge($numericIds, array_values($mappedStoreIds));
                }

                $loc_ids = array_values(array_unique($numericIds));

                $cashiernames = $this->Location->find('list', array('fields' => array('name'), 'conditions' => array('id' => $loc_ids)));
                $cashiername = implode(', ', $cashiernames);

                if ($isHouseOfKebab) {
                    $cashiername = "HOUSE OF KEBAB, SECTOR - 66, GURUGRAM";
                }

                $where_location = " and store_id IN (" . implode(',', $loc_ids) . ")";

                $payments = $this->Order_payment->query("SELECT SUM(amount) as total_amount,SUM(IF(type=1,amount,0)) AS cash,SUM(IF(type=2,amount,0)) AS card,SUM(IF(type=9,amount,0)) AS online,SUM(IF(type=6,amount,0)) AS upi,SUM(IF(type=7,amount,0)) AS no_charge_with_tax,SUM(IF(type=7,round(amount-(SELECT total_tax from order_transactions WHERE reference_id=order_payments.reference_id $where_location  limit 1),2),0)) AS no_charge,SUM(IF(type=8,amount,0)) AS storecard FROM `order_payments` where status=2 and created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' $where_location");

                $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 00:00:01' and '$enddate 23:59:59' $where_location and status=2 and reference_id NOT IN (SELECT reference_id from order_payments WHERE type=7 and status=2 $where_location)");

                $transactionsnc = $this->Order_transaction->query("SELECT SUM(total_tax) AS total_tax FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' $where_location and status=2 and reference_id IN (SELECT reference_id from order_payments WHERE type=7 and status=2 $where_location)");

                $transactionsubtotal = $this->Order_transaction->query("SELECT SUM(price) AS price,SUM(discount) AS discount  FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' and status=2 $where_location");

                $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 00:00:01' and '$enddate 23:59:59' and status=2 and reference_id IN (SELECT reference_id FROM `order_orderhistories` WHERE status !=0 $where_location) $where_location GROUP by tax_id");

                $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 00:00:01' and '$enddate 23:59:59' and status=2 and reference_id IN (SELECT reference_id FROM `order_orderhistories` WHERE store_id IN (" . implode(',', $loc_ids) . ")) $where_location GROUP by kds,tax_id) as sub GROUP by kds,tax_value) as final GROUP by kds,tax_percentage");


                $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 00:00:01' and '$enddate 23:59:59' and tax_percentage!=0 AND status = 2  and reference_id IN (SELECT reference_id FROM `order_orderhistories` WHERE status !=0 $where_location) $where_location GROUP BY tax_id ) AS order_tax");

                $transactionswithnctax = $this->Order_transaction->query("SELECT SUM(total_tax) AS total_tax  FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' and status=2 $where_location");
                $transactionscount = $this->Order_transaction->query("SELECT COUNT(id) as total_count FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' $where_location and status=2 ");

            } else {
                $cashiername = 'All Stores';
                if ($userRole != 'admin') {
                    $where_location = " AND store_id IN (" . $userLocationId . ")";

                    $payments = $this->Order_payment->query("SELECT SUM(amount) as total_amount,SUM(IF(type=1,amount,0)) AS cash,SUM(IF(type=2,amount,0)) AS card,SUM(IF(type=9,amount,0)) AS online,SUM(IF(type=6,amount,0)) AS upi,SUM(IF(type=7,amount,0)) AS no_charge_with_tax,SUM(IF(type=7,round(amount-(SELECT total_tax from order_transactions WHERE reference_id=order_payments.reference_id $where_location limit 1),2),0)) AS no_charge,SUM(IF(type=8,amount,0)) AS storecard FROM `order_payments` where status=2 and created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' $where_location");

                    $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 00:00:01' and '$enddate 23:59:59' $where_location and status=2 and reference_id NOT IN (SELECT reference_id from order_payments WHERE type=7 and status=2 $where_location)");

                    $transactionsnc = $this->Order_transaction->query("SELECT SUM(total_tax) AS total_tax FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' $where_location and status=2 and reference_id IN (SELECT reference_id from order_payments WHERE type=7 and status=2 $where_location)");

                    $transactionsubtotal = $this->Order_transaction->query("SELECT SUM(price) AS price,SUM(discount) AS discount  FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' and status=2 $where_location");

                    $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 00:00:01' and '$enddate 23:59:59' and status=2 and reference_id IN (SELECT reference_id FROM `order_orderhistories` WHERE status !=0 $where_location) $where_location GROUP by tax_id");
                    $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 00:00:01' and '$enddate 23:59:59' and status=2 and reference_id IN (SELECT reference_id FROM `order_orderhistories` WHERE  status !=0 $where_location) $where_location GROUP by kds,tax_id) as sub GROUP by kds,tax_value) as final GROUP by kds,tax_percentage");

                    $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 00:00:01' and '$enddate 23:59:59' and tax_percentage!=0 AND status = 2  and reference_id IN (SELECT reference_id FROM `order_orderhistories` WHERE status !=0 $where_location) $where_location GROUP BY tax_id ) AS order_tax");

                    $transactionswithnctax = $this->Order_transaction->query("SELECT SUM(total_tax) AS total_tax  FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' and status=2 $where_location");
                    $transactionscount = $this->Order_transaction->query("SELECT COUNT(id) as total_count FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' $where_location and status=2");

                } else {

                    $payments = $this->Order_payment->query("SELECT SUM(amount) as total_amount,SUM(IF(type=1,amount,0)) AS cash,SUM(IF(type=2,amount,0)) AS card,SUM(IF(type=9,amount,0)) AS online,SUM(IF(type=6,amount,0)) AS upi,SUM(IF(type=7,amount,0)) AS no_charge_with_tax,SUM(IF(type=7,round(amount-(SELECT total_tax from order_transactions WHERE reference_id=order_payments.reference_id limit 1),2),0)) AS no_charge,SUM(IF(type=8,amount,0)) AS storecard FROM `order_payments` where status=2 and created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' ");

                    $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(round) AS round,SUM(price) AS price  FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' and status=2 and reference_id NOT IN (SELECT reference_id from order_payments WHERE type=7 and status=2)");

                    $transactionsnc = $this->Order_transaction->query("SELECT SUM(total_tax) AS total_tax  FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' and status=2 and reference_id 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 00:00:01' and '$enddate 23:59:59' and status=2");

                    $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 00:00:01' and '$enddate 23:59:59' and status=2 GROUP by tax_id");

                    $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 00:00:01' and '$enddate 23:59:59' and status=2 GROUP by kds,tax_id) as sub GROUP by kds,tax_value) as final GROUP by kds,tax_percentage");

                    $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 00:00:01' and '$enddate 23:59:59' and tax_percentage!=0 AND status = 2  GROUP BY tax_id ) AS order_tax");

                    $transactionswithnctax = $this->Order_transaction->query("SELECT SUM(total_tax) AS total_tax  FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' and status=2");
                    $transactionscount = $this->Order_transaction->query("SELECT COUNT(id) as total_count  FROM `order_transactions` where  created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' and status=2");

                }
            }

            if ($isHouseOfKebab) {
                $this->Order_payment->setDataSource('default');
                $this->Order_transaction->setDataSource('default');
                $this->Order_tax->setDataSource('default');
            }
            $taxable_price = 0;
            foreach ($taxablepricess as $taxableprices) {
                $taxable_price = round($taxable_price + $taxableprices['order_tax']['taxable_price'], 2);
            }

            $datas = array();
            $taxesarr = array();
            $salesarr = array();

            $datas[] = array(
                'cashier' => $cashiername,
                'total_collection' => round($payments[0][0]['total_amount'], 2),
                'cash' => round($payments[0][0]['cash'], 2),
                'card' => round($payments[0][0]['card'], 2),
                'online' => round($payments[0][0]['online'], 2),
                'upi' => round($payments[0][0]['upi'], 2),
                'storecard' => round($payments[0][0]['storecard'], 2),
                'no_charge' => round($payments[0][0]['no_charge_with_tax'] - $transactionsnc[0][0]['total_tax'], 2),
                'no_charge_with_tax' => round($payments[0][0]['no_charge_with_tax'], 2),
                'subtotal' => round($transactionsubtotal[0][0]['price'], 2),
                'discount' => round($transactionsubtotal[0][0]['discount'], 2),
                'taxable_amount' => round($taxable_price, 2),
                'service_charge' => round($transactions[0][0]['servicecharge'], 2),
                'delivery_charge' => round($transactions[0][0]['delivery_charge'], 2),
                'packing_charge' => round($transactions[0][0]['packing_charge'], 2),
                'total_tax' => round($transactionswithnctax[0][0]['total_tax'], 2),
                'bill_count' => round($transactionscount[0][0]['total_count'], 2),
                'net_amount' => round($transactions[0][0]['amount'], 2),
                'round' => round($transactions[0][0]['round'], 2)
            );

            foreach ($taxes as $tax) {
                $taxesarr[] = array(
                    'tax_name' => $tax['order_tax']['tax_name'] . '(' . $tax['order_tax']['tax_percentage'] . '%)',
                    'tax_value' => $tax[0]['tax_value']
                );
            }

            foreach ($sales as $sale) {
                // print_r($sale);exit;
                $salesarr[] = array(
                    'kds' => $sale['final']['kds_name'],
                    'kds_value' => round($sale['final']['value'], 2),
                    'tax_percentage' => $sale['final']['tax_percentage'],
                );
            }

            $this->set(compact('startdate', 'enddate', 'datas', 'taxesarr', 'salesarr'));
        }
    }

	
	public function card_report() {
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
	
        $startDate = date('m/d/Y');
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }   
            
        $card_no= $this->request->data['Search']['card_no'];
		
		$cards = $this->Cardtracking->query("SELECT txnid,type,amount,created,purpose FROM `cardtracking` WHERE cardnumber='$card_no' and created between '$startdate 00:00:01' and  '$enddate 23:59:59' order by id desc");
	
		
		$yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
    
        $this->set(compact('cards'));
        
	}
	
	public function card_reportexport() {
        $date_range= $_GET['sdate'];
	    $dates = explode(" - ", $date_range);
        $start_date = trim($dates[0]);
        $end_date = trim($dates[1]);
        $startdate= date('Y-m-d', strtotime($start_date));
        $enddate= date('Y-m-d', strtotime($end_date));


        $card_no= $_GET['id'];
        $cards = $this->Cardtracking->query("SELECT txnid,type,amount,created,purpose FROM `cardtracking` WHERE cardnumber='$card_no' and created between '$startdate 00:00:01' and '$enddate 23:59:59' order by id desc");
        
        $datas=array();
    	foreach($cards as $card){
    	    $datas[]=array(
				'txnid'=>$card['cardtracking']['txnid'],
				'type'=>$card['cardtracking']['type'],
				'purpose'=>$card['cardtracking']['purpose'],
				'amount'=>$card['cardtracking']['amount'],
				'created'=>$card['cardtracking']['created']
			);
        }
			 
        App::import('Vendor', 'PHPExcel/PHPExcel');
           error_reporting(0);
           ini_set('display_errors', TRUE);
           ini_set('display_startup_errors', TRUE);
           if (PHP_SAPI == 'cli')
                die('This example should only be run from a Web Browser');
           $objPHPExcel = new PHPExcel();
           // Set document properties
           $objPHPExcel->getProperties()->setCreator("Aether")
           ->setLastModifiedBy("Aether")
           ->setTitle("Office 2007 XLSX Aether Document")
           ->setSubject("Office 2007 XLSX Aether Document")
           ->setDescription("Aether Export Data File.")
           ->setKeywords("office 2007 openxml php")
           ->setCategory("AetherPos Export Data File");
           // Add some data
           $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', '   ' .'CARD REPORT OF '.$card_no);
           
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A3', 'SR. NO.');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B3', 'Txn id');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C3', 'Type');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('D3', 'Purpose');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E3', 'Amount');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('F3', 'Created');
            $objPHPExcel->getActiveSheet()->getStyle("A1:F3")->getFont()->setBold(true);
            $objPHPExcel->getActiveSheet()->mergeCells('A1:F1');
            
            $baseRow = 3;
            $r=1;
            
	        foreach($datas as $dat){
				  
				    if($dat['type']==1){
                        $type='credit';
                    }elseif($dat['type']==2){
                        $type='debit';
                    }elseif($dat['type']==3){
                        $type='security';
                    }else{
                        $type='refund';
                    }
                    
                    if($dat['purpose']=='card_charge'){
                        $purpose='card charge';
                    }elseif($dat['purpose']=='transferfrom'){
                        $purpose='transfer from';
                    }elseif($dat['purpose']=='transferto'){
                        $purpose='transfer to';
                    }else{
                        $purpose=$dat['purpose'];
                    }
                    
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.($baseRow + $r),$r);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.($baseRow + $r),$dat['txnid']);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C'.($baseRow + $r),$type);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('D'.($baseRow + $r),$purpose);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E'.($baseRow + $r),abs($dat['amount']));
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('F'.($baseRow + $r),$dat['created']);
					   			  
						   $r++;
				   
				}
				
				  //$r++;
				 
               
               //$objPHPExcel->getActiveSheet()->removeRow($baseRow-1,1);
               //$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', 'Hello');
               // Miscellaneous glyphs, UTF-8
               // Rename worksheet
               $objPHPExcel->getActiveSheet()->setTitle('Export Data');
               // Set active sheet index to the first sheet, so Excel opens this as the first sheet
               $objPHPExcel->setActiveSheetIndex(0);
               // Redirect output to a client’s web browser (Excel5)
               header('Content-Type: application/vnd.ms-excel');
               header('Content-Disposition: attachment;filename="'.'CARD REPORT.xls"');
               header('Cache-Control: max-age=0');
               // If you're serving to IE 9, then the following may be needed
               header('Cache-Control: max-age=1');
               // If you're serving to IE over SSL, then the following may be needed
               header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
               header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
               header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
               header ('Pragma: public'); // HTTP/1.0
               $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
               $objWriter->save('php://output');
               exit;
               
	}
	
	public function card_reportpdf()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "login";
	    if($this->request->is('post', 'put'))
        {
            $card_no= $this->request->data['cardno'];
		    $date_range= $this->request->data['sdate'];
		    
    	    $dates = explode(" - ", $date_range);
            $start_date = trim($dates[0]);
            $end_date = trim($dates[1]);
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));



		    $cards = $this->Cardtracking->query("SELECT cardnumber,txnid,purpose,type,amount,created FROM `cardtracking` WHERE cardnumber='$card_no' and created between '$startdate 00:00:01' and '$enddate 23:59:59' order by id desc");
            $datas=array();
        	foreach($cards as $card){
        	    $datas[]=array(
    				'card_no'=>$card['cardtracking']['cardnumber'],
    				'txnid'=>$card['cardtracking']['txnid'],
    				'purpose'=>$card['cardtracking']['purpose'],
    				'type'=>$card['cardtracking']['type'],
    				'amount'=>$card['cardtracking']['amount'],
    				'created'=>$card['cardtracking']['created']
    			);
            }
		      $this->set(compact('card_no','datas'));
        }
    }
    
	public function cashier_list() {
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
          
	    $this->layout = "users";
		
		$startDate = date('m/d/Y', strtotime('-12 months'));
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }   
        
        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;
        
        $locationCondition = '';
        if ($userRole !== 'admin') {
            $locationCondition = "AND id IN (SELECT user_id from user_locations WHERE status=1 and location_id IN (" . $userLocationId . "))";
        }
		$users = $this->User->query("SELECT *,(SELECT GROUP_CONCAT(name) FROM `user_modules` WHERE user_id=users.id) as module,(SELECT GROUP_CONCAT(location_name) FROM `user_locations` WHERE user_id=users.id and status=1) as locations FROM `users` WHERE role IN ('cashier','manager') and created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' $locationCondition order by id desc");
		
        $moduleLabels=moduleswithlabel;
        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        
		$this->set(compact('users'));
		$this->set(compact('moduleLabels'));

	}
    	
    public function subadmin_list() {
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
          
	    $this->layout = "users";
		
		$startDate = date('m/d/Y', strtotime('-12 months'));
        $endDate = date('m/d/Y');
        
        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;

        $locationCondition = '';
        if ($userRole !== 'admin') {
            $locationCondition = "AND id IN (SELECT user_id from user_locations WHERE status=1 and location_id IN (" . $userLocationId . "))";
        }

        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }   
        
		$users = $this->User->query("SELECT *,(SELECT GROUP_CONCAT(name) FROM `user_modules` WHERE user_id=users.id) as module,(SELECT GROUP_CONCAT(location_name) FROM `user_locations` WHERE user_id=users.id and status=1) as locations FROM `users` WHERE role IN ('subadmin','kitchen') $locationCondition and created BETWEEN '$startdate 00:00:01' and '$enddate 23:59:59' order by id desc");
		
		$moduleLabels=subadminmoduleswithlabel;
        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        
		$this->set(compact('users'));
		$this->set(compact('moduleLabels'));

	}
    	
    public function cashier_change_status() {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $userId = $this->request->data['user_id'];
    
            // Update user status
            $this->User->id = $userId;
            $newStatus = $this->User->field('status') == 1 ? 0 : 1;
            if ($this->User->save(['status' => $newStatus,'sync' => 0])) {
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }

    public function cancel_booking() {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $id = $this->request->data['_id'];
    
            // Update user status
            $this->Online_booking->id = $id;
            if ($this->Online_booking->save(['status' => 0,'sync' => 0])) {
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }

    public function subadmin_change_status() {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $userId = $this->request->data['user_id'];
    
            // Update user status
            $this->User->id = $userId;
            $newStatus = $this->User->field('status') == 1 ? 0 : 1;
            if ($this->User->save(['status' => $newStatus,'sync' => 0])) {
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }

    public function card_change_status() {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $Id = $this->request->data['_id'];
            

            $currentStatus = $this->Card->field('status', ['id' => $Id]);
            $newStatus = in_array($currentStatus, [1, 2]) ? 0 : 1;
            
            $this->Card->id = $Id;
            
            if ($this->Card->save(['status' => $newStatus,'sync' => 0])) {
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }

	public function category_change_status() {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $Id = $this->request->data['_id'];
            
            $this->Catalog_category->id = $Id;
            $newStatus = $this->Catalog_category->field('status') == 1 ? 0 : 1;
            
            if ($this->Catalog_category->save(['status' => $newStatus,'sync' => 0])) {
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }

    public function subcategory_change_status() {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $Id = $this->request->data['_id'];
            
            $this->Catalog_subcategory->id = $Id;
            $newStatus = $this->Catalog_subcategory->field('status') == 1 ? 0 : 1;
            
            if ($this->Catalog_subcategory->save(['status' => $newStatus,'sync' => 0])) {
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }

    public function tax_change_status() {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $Id = $this->request->data['_id'];
            
            $this->Catalog_tax->id = $Id;
            $newStatus = $this->Catalog_tax->field('status') == 1 ? 0 : 1;
            
            if ($this->Catalog_tax->save(['status' => $newStatus,'sync' => 0])) {
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }

    public function unit_change_status() {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $Id = $this->request->data['_id'];
            
            $this->Catalog_unit->id = $Id;
            $newStatus = $this->Catalog_unit->field('status') == 1 ? 0 : 1;
            
            if ($this->Catalog_unit->save(['status' => $newStatus,'sync' => 0])) {
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }

    public function product_change_status() {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $Id = $this->request->data['_id'];
            
            $this->Catalog_product->id = $Id;
            $newStatus = $this->Catalog_product->field('status') == 1 ? 0 : 1;
            
            if ($this->Catalog_product->save(['status' => $newStatus,'sync' => 0])) {
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }

    public function sku_change_status() {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $Id = $this->request->data['_id'];
            
            $this->Inventory_sku->id = $Id;
            $newStatus = $this->Inventory_sku->field('status') == 1 ? 0 : 1;
            
            if ($this->Inventory_sku->save(['status' => $newStatus,'sync' => 0])) {
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }
    
    public function semifinished_change_status() {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $Id = $this->request->data['_id'];
            
            $this->Inventory_semifinished->id = $Id;
            $newStatus = $this->Inventory_semifinished->field('status') == 1 ? 0 : 1;
            
            if ($this->Inventory_semifinished->save(['status' => $newStatus,'sync' => 0])) {
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }
    
    public function vendor_change_status() {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $userId = $this->request->data['_id'];
    
            // Update user status
            $this->Inventory_vendor->id = $userId;
            $newStatus = $this->Inventory_vendor->field('status') == 1 ? 0 : 1;
            if ($this->Inventory_vendor->save(['status' => $newStatus,'sync' => 0])) {
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }

    public function indent_change_status() {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $userId = $this->request->data['_id'];
    
            // Update user status
            $this->Inventory_internal_indent->id = $userId;
            $newStatus = $this->Inventory_internal_indent->field('status') == 1 ? 0 : 1;
            if ($this->Inventory_internal_indent->save(['status' => $newStatus,'sync' => 0])) {
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }
    
    public function location_change_status() {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $Id = $this->request->data['_id'];
            
            $this->Location->id = $Id;
            $newStatus = $this->Location->field('status') == 1 ? 0 : 1;
            
            if ($this->Location->save(['status' => $newStatus,'sync' => 0])) {
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }

    public function table_change_status() {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $Id = $this->request->data['_id'];
            
            $this->Order_table->id = $Id;
            
            $currentStatus = $this->Order_table->field('status', ['id' => $Id]);
            $newStatus = in_array($currentStatus, [1, 2,3]) ? 0 : 1;
            

            if ($this->Order_table->save(['status' => $newStatus,'sync' => 0])) {
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }

    public function coupon_change_status() {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $Id = $this->request->data['_id'];
            
            $this->Coupon->id = $Id;
            
            $newStatus = $this->Coupon->field('status') == 1 ? 0 : 1;
            if ($this->Coupon->save(['status' => $newStatus,'sync' => 0])) {
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }

    public function remove_subcategory() {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $Id = $this->request->data['_id'];
            
            $this->Catalog_subcategory->id = $Id;
            if ($this->Catalog_subcategory->save(['status' => 0,'sync' => 0])) {
                
                $categoryid = $this->Catalog_subcategory->query("SELECT cat_id FROM catalog_subcategory where id=$Id");
                $cat_id=$categoryid['0']['catalog_subcategory']['cat_id'];
                
                $subcategorychk=$this->Catalog_subcategory->query("SELECT * FROM catalog_subcategory where cat_id=$cat_id and status=1");
                if($subcategorychk){
                    $this->Catalog_category->query("UPDATE catalog_category SET is_subcategory=1,sync = 0 WHERE id=$cat_id");
                }else{
                    $this->Catalog_category->query("UPDATE catalog_category SET is_subcategory=0,sync = 0 WHERE id=$cat_id");
                }
    		    
    		    echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }

    public function category_list() {
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		$startDate = date('m/d/Y', strtotime('-12 months'));
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }   
        
		$users = $this->Catalog_category->find('all', array(
            'conditions' => array('created BETWEEN ? AND ?' => array($startdate.' 00:00:01', $enddate.' 23:59:59')
            ),
            'order' => array(
                'id' => 'DESC' // Order by the 'created' field in ascending order
            )
        ));
        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        
		$this->set(compact('users'));

	}
	
	public function subcategory_list() {
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		$startDate = date('m/d/Y', strtotime('-12 months'));
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }   
        
		$users = $this->Catalog_subcategory->query("SELECT *,(SELECT name FROM catalog_category where id=catalog_subcategory.cat_id) as cat_name FROM catalog_subcategory where created between '$startdate 00:00:01' and  '$enddate 23:59:59' ORDER BY id desc");
        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        
		$this->set(compact('users'));

	}
	
	public function card_list()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		$startDate = date('m/d/Y', strtotime('-12 months'));
        $endDate = date('m/d/Y');
        
		if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }   
        
		
		$users = $this->Card->find('all', array(
            'conditions' => array(
                'Card.created BETWEEN ? AND ?' => array($startdate.' 00:00:01', $enddate.' 23:59:59')
            ),
            'order' => array(
                'Card.id' => 'DESC' // Order by the 'created' field in ascending order
            )
        ));
        
        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        $this->set(compact('users'));

	}   
	
	public function card_listexport()
	{
	    $date_range= $_GET['sdate'];
	    $dates = explode(" - ", $date_range);
        $start_date = trim($dates[0]);
        $end_date = trim($dates[1]);
        $startdate= date('Y-m-d', strtotime($start_date));
        $enddate= date('Y-m-d', strtotime($end_date));

        $cards = $this->Card->find('all', array(
            'conditions' => array(
                'Card.created BETWEEN ? AND ?' => array($startdate.' 00:00:01', $enddate.' 23:59:59')
            ),
            'order' => array(
                'Card.id' => 'DESC' // Order by the 'created' field in ascending order
            )
        ));
        
	    $datas=array();
	    
    	foreach($cards as $card){
    	    $datas[]=array(
				'cardnumber'=>$card['Card']['cardnumber'],
				'cardbalance'=>$card['Card']['cardbalance'],
				'name'=>$card['Card']['name'],
				'mobile'=>$card['Card']['mobile'],
				'status'=>$card['Card']['status'],
				'created'=>$card['Card']['created']
			);
        }
			 
        App::import('Vendor', 'PHPExcel/PHPExcel');
           error_reporting(0);
           ini_set('display_errors', TRUE);
           ini_set('display_startup_errors', TRUE);
           if (PHP_SAPI == 'cli')
                die('This example should only be run from a Web Browser');
           $objPHPExcel = new PHPExcel();
           // Set document properties
           $objPHPExcel->getProperties()->setCreator("Aether")
           ->setLastModifiedBy("Aether")
           ->setTitle("Office 2007 XLSX Aether Document")
           ->setSubject("Office 2007 XLSX Aether Document")
           ->setDescription("Aether Export Data File.")
           ->setKeywords("office 2007 openxml php")
           ->setCategory("AetherPos Export Data File");
           // Add some data
           $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', '   ' .'CARD LIST FROM '.$startdate.' TO '.$enddate);
           
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A3', 'SR. NO.');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B3', 'Card No.');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C3', 'Card Balance');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('D3', 'Name');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E3', 'Mobile');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('F3', 'Status');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('G3', 'Created');
            $objPHPExcel->getActiveSheet()->getStyle("A1:G3")->getFont()->setBold(true);
            $objPHPExcel->getActiveSheet()->mergeCells('A1:G1');
            
            $baseRow = 3;
            $r=1;
            
	        foreach($datas as $dat){

                  if($dat['status']==0){
                      $status='InActive';
                  }else{
                      $status='Active';
                  }
                  
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.($baseRow + $r),$r);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.($baseRow + $r),$dat['cardnumber']);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C'.($baseRow + $r),$dat['cardbalance']);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('D'.($baseRow + $r),$dat['name']);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E'.($baseRow + $r),$dat['mobile']);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('F'.($baseRow + $r),$status);
				  $objPHPExcel->setActiveSheetIndex(0)->setCellValue('G'.($baseRow + $r),$dat['created']);
					   			  
						   $r++;
				   
				}
				
				  //$r++;
				 
               
               //$objPHPExcel->getActiveSheet()->removeRow($baseRow-1,1);
               //$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', 'Hello');
               // Miscellaneous glyphs, UTF-8
               // Rename worksheet
               $objPHPExcel->getActiveSheet()->setTitle('Export Data');
               // Set active sheet index to the first sheet, so Excel opens this as the first sheet
               $objPHPExcel->setActiveSheetIndex(0);
               // Redirect output to a client’s web browser (Excel5)
               header('Content-Type: application/vnd.ms-excel');
               header('Content-Disposition: attachment;filename="'.'CARD LIST.xls"');
               header('Cache-Control: max-age=0');
               // If you're serving to IE 9, then the following may be needed
               header('Cache-Control: max-age=1');
               // If you're serving to IE over SSL, then the following may be needed
               header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
               header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
               header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
               header ('Pragma: public'); // HTTP/1.0
               $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
               $objWriter->save('php://output');
               exit;
               
	    
		

	}   
	
	public function profile()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		$id=$this->Session->read('Auth.User.empID');
		$userdetail=$this->Employee->find('first',array('conditions'=>array('Employee.empID'=>$id)));
	    $this->set('userdetail', $userdetail);
	}   
	
    public function create_cashier()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		$authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? '';
        
        $conditions = ['status' => 1];
        
        if ($userRole !== 'admin' && !empty($userLocationId)) {
            $ids = array_filter(array_map('trim', explode(',', $userLocationId))); // clean IDs
            if (!empty($ids)) {
                $conditions['id IN'] = $ids;
            }
        }
        
        $modules=moduleswithlabel;
        $this->set(compact('modules'));
	    
	    $locations=$this->Location->find('all',['conditions' => $conditions]);
	    $this->set(compact('locations'));
	    
	    
		if ($this->request->is(array('post', 'put'))) {
            
            $name = $this->data['User']['name'];
            if($name==''){
                $this->Flash->error(__('The Name could not be Blank'));
                return $this->redirect(array('action' => 'create_cashier'));
            }
            
            $mobile = $this->data['User']['mobile'];
            $username = $this->data['User']['username'];
        
            $userdetail=$this->User->find('first',array('conditions'=>array('User.username'=>$username)));
	        if($userdetail){
	            $this->Flash->error(__('Username already exist'));
                return $this->redirect(array('action' => 'create_cashier'));
	        }
            $password =$this->data['User']['password'];
            $password = AuthComponent::password($password);
            
            $modules=moduleswithlabel;
            $checkedModules = [];
            
            $bill_location =$this->data['User']['bill_location'];
            $loc_type =$this->data['User']['loc_type'];
            
            $role =$this->data['User']['role'];
            $settlement =$this->data['User']['settlement'];
            
            if($role=='manager'){
                $pin =$this->data['User']['pin'] ?? 0;
            }else{
                $pin = 0;
            }
            
            if($loc_type==0){
                $location_ids =[];
            }else{
                $location_ids =$this->data['User']['location'];
            }

            $locationdetail = $this->Location->find('first', array(
                                'conditions' => array('Location.id' => $bill_location)
                            ));
                
            if (!empty($locationdetail)) {
                $locationnamee = $locationdetail['Location']['name'];
            }
            
            $data['User']=array(
    			'name'=>$name,
    			'username'=>$username,
    			'password'=>$password,
    			'mobile'=>$mobile,
    			'can_settlement'=>$settlement,
    	    	'role'=>$role,
    	    	'pin'=>$pin,
    			'location_id'=>$bill_location,
    			'location_name'=>$locationnamee
    	    );
    	    
    	    
    	    if($this->User->saveAll($data['User']))
    		{
    		    $lastInsertedID = $this->User->id;
    		    foreach($location_ids as $location_id){
                    $locationdetail=$this->Location->find('first',array('conditions'=>array('Location.id'=>$location_id)));
                    $locationname=$locationdetail['Location']['name'];
                    
                    $isBill = (!empty($bill_location) && (
                        (is_array($bill_location) && in_array($location_id, $bill_location)) ||
                        (!is_array($bill_location) && $bill_location == $location_id)
                   )) ? 1 : 0;
                   
                    $data['User_location']=array(
            			'user_id'=>$lastInsertedID,
            			'user_name'=>$username,
            			'location_id'=>$location_id,
            			'location_name'=>$locationname,
            			'billing_location'=>$isBill
            		);
                
            		if($this->User_location->saveAll($data['User_location']))
		            {

		            }else{
		                $this->Flash->error(__('The user Locations could not be saved. Please, try again.'));
		            }
                }
                
                if (!empty($bill_location)) {
                    $billLocations = is_array($bill_location) ? $bill_location : array($bill_location);
                
                    foreach ($billLocations as $billLoc) {
                        if (!in_array($billLoc, $location_ids)) {
                            $locationdetail = $this->Location->find('first', array(
                                'conditions' => array('Location.id' => $billLoc)
                            ));
                
                            if (!empty($locationdetail)) {
                                $locationname = $locationdetail['Location']['name'];
                
                                $data['User_location'] = array(
                                    'user_id'       => $lastInsertedID,
                                    'user_name'     => $username,
                                    'location_id'   => $billLoc,
                                    'location_name' => $locationname,
                                    'billing_location' => 1
                                );
                
                                $this->User_location->create();
                                if (!$this->User_location->save($data['User_location'])) {
                                    $this->Flash->error(__('The extra bill Location could not be saved. Please, try again.'));
                                }
                            }
                        }
                    }
                }
                
    		    foreach ($modules as $moduleKey => $moduleLabel) {
                    if (isset($this->data['User'][$moduleKey]) && $this->data['User'][$moduleKey]) {
                        $checkedModules[$moduleKey] = $this->data['User'][$moduleKey];
                        $data['User_module']=array(
                			'name'=>$moduleKey,
                			'user_id'=>$lastInsertedID
                		);
                		if($this->User_module->saveAll($data['User_module']))
    		            {
    		            }else{
    		                $this->Flash->error(__('The user modules could not be saved. Please, try again.'));
    		            }
                    }
                }
                
                $this->Flash->success(__('The User has been saved.'));
				return $this->redirect(array('action' => 'cashier_list'));
			} else {
				$this->Flash->error(__('The user could not be saved. Please, try again.'));
			}
		}
		
		
	}
	
	public function create_booking()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        $this->layout = "users";
		
		if ($_POST['bookdate']) {
	        $bookdate=$_POST['bookdate'];
            $booktime=$_POST['booktime'];
	    }else{
	        $bookdate= date('Y-m-d');
            $currentHour = date('H');
            $defaultTime = '22';
            $booktime=($currentHour < 22) ? $defaultTime : $currentHour;
	    }
	    $newbookdate= date('d-m-Y', strtotime($bookdate));
	    $this->set('bookdate', $newbookdate);
	    $this->set('booktime', $booktime);
        $booking_time=$bookdate.' '.$booktime.':00:00';
        
        $adddatetime = new DateTime($booking_time);
        $adddatetime->modify('+4 hours');
        $add_booking_time = $adddatetime->format('Y-m-d H:i:s');
        
        $subdatetime = new DateTime($booking_time);
        $subdatetime->modify('-4 hours');
        $sub_booking_time = $subdatetime->format('Y-m-d H:i:s');
        
        $tables=$this->Order_table->query("SELECT *,(SELECT id FROM `online_bookings` WHERE booking_time BETWEEN '$sub_booking_time' and '$add_booking_time' and status=1 and table_number=order_tables.number) as bookstatus FROM `order_tables`");
        $this->set(compact('tables'));

	}
	
	public function book_now()
    {
        $this->layout = false;
        $id = $this->data['User']['id'];
        if ($id) {
            
            $bookdate = $this->data['User']['bookdate'];
            $booktime = $this->data['User']['booktime'];
            
            if($booktime==10){
                $booktime=22;    
            }
            if($booktime==11){
                $booktime=23;    
            }
            
            $booking_time=$bookdate.' '.$booktime.':00:00';
            
            $adddatetime = new DateTime($booking_time);
            $adddatetime->modify('+4 hours');
            $add_booking_time = $adddatetime->format('Y-m-d H:i:s');
            
            $subdatetime = new DateTime($booking_time);
            $subdatetime->modify('-4 hours');
            $sub_booking_time = $subdatetime->format('Y-m-d H:i:s');
            
            $table = $this->Online_booking->query("SELECT * FROM `online_bookings` WHERE booking_time BETWEEN '$sub_booking_time' and '$add_booking_time' and status=1 and table_number=$id");
            
            if(!$table){
                $ref_id = $this->data['User']['ref_id'];
                $pax = $this->data['User']['pax'];
                $cover_charge=$this->data['User']['cover_charge'];
                $name = $this->data['User']['name'];
                $mobile = $this->data['User']['phone'];
                $remarks = $this->data['User']['remarks'];
                $prepaid=$this->data['User']['prepaid'];
                $payment_type=1;
                if($prepaid==1){
                    $payment_type=2;
                }
                if($_POST['pay_type']){
                    $pay_type=$_POST['pay_type'];
                    if($pay_type==1){
                        $pay_type_value='cash';
                    }
                    if($pay_type==2){
                        $pay_type_value='card';
                    }
                    if($pay_type==6){
                        $pay_type_value='upi';
                    }
                }else{
                    $pay_type=0;
                    $pay_type_value='';
                }
                
                $booking_time=$bookdate.' '.$booktime.':00:00';
                $booking_time= date('Y-m-d H:i:s', strtotime($booking_time));
	            $usrid = $this->Session->read('Auth.User.id');
        
                $data['Online_booking']=array(
        			'table_number'=>$id,
        			'reference_id'=>$ref_id,
        			'pax'=>$pax,
        			'cover_charge'=>$cover_charge,
        			'user_id'=>$usrid,
        			'name'=>$name,
        			'phone'=>$mobile,
        			'booking_time'=>$booking_time,
        			'payment_type'=>$payment_type,
        			'pay_option'=>$pay_type,
        			'pay_option_value'=>$pay_type_value,
        			'remarks'=>$remarks
        	    );
        	    
        	    if($this->Online_booking->saveAll($data['Online_booking']))
        		{
        		  //  $this->Order_table->query("UPDATE order_tables SET status='2' WHERE id =". $id);
            
        		    $this->Flash->success(__('The Booking has been saved.'));
    				return $this->redirect(array('action' => 'create_booking'));
        		}else{
        		    $this->Flash->error(__('Table not booked,try again'));
                    return $this->redirect(array('action' => 'create_booking'));
        		}
            }else{
                $this->Flash->error(__('Table Already Booked!! kindly try again with another table !'));
                return $this->redirect(array('action' => 'create_booking'));
            }
        }else{
            if($this->request->is('ajax'))
            {
                $bookdate = $this->request->data['bookdate'];
                $booktime = $this->request->data['booktime'];
                $number=$this->request->data['number'];
                // $this->set(compact('bookdate'));
                // $this->set(compact('booktime'));
                
                $newbookdate= date('d-m-Y', strtotime($bookdate));
        	    $this->set('bookdate', $newbookdate);
        	    $this->set('booktime', $booktime);
                $booking_time=$bookdate.' '.$booktime.':00:00';
                // print_r($booktime);exit;
                $adddatetime = new DateTime($booking_time);
                $adddatetime->modify('+4 hours');
                $add_booking_time = $adddatetime->format('Y-m-d H:i:s');
                
                $subdatetime = new DateTime($booking_time);
                $subdatetime->modify('-4 hours');
                $sub_booking_time = $subdatetime->format('Y-m-d H:i:s');
                
                $tablesdata=$this->Order_table->query("SELECT *,(SELECT id FROM `online_bookings` WHERE booking_time BETWEEN '$sub_booking_time' and '$add_booking_time' and status=1 and table_number=$number) as bookstatus FROM `order_tables` where number=$number");
                if(!isset($tablesdata[0]['bookstatus'])){
                    $this->set(compact('tablesdata'));
                } else {
                    echo 'Table not Vacant!! Kindly refresh again';
                }
            } else {
                $this->Flash->error(__('Invalid Request'));
                return $this->redirect(array('action' => 'create_booking'));
            }
        }
   }
    
    public function edit_booking()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        $this->layout = "users";
		
		if ($_REQUEST['id']) {
		    $id=$_REQUEST['id'];
		    $tabledetails=$this->Online_booking->query("SELECT * FROM `online_bookings` WHERE id=$id");
            $booking_time=$tabledetails[0]['online_bookings']['booking_time'];
		    $table_number=$tabledetails[0]['online_bookings']['table_number'];
		    $name=$tabledetails[0]['online_bookings']['name'];
		    $phone=$tabledetails[0]['online_bookings']['phone'];
		    $cover_charge=$tabledetails[0]['online_bookings']['cover_charge'];
		    $pax=$tabledetails[0]['online_bookings']['pax'];
		    $booking_date= date('Y-m-d', strtotime($booking_time));
	        $booking_times= date('H', strtotime($booking_time));
	    
	        $bookdate=$booking_date;
            $booktime=$booking_times;
            
            $payment_type=$tabledetails[0]['online_bookings']['payment_type'];
		    $pay_option=$tabledetails[0]['online_bookings']['pay_option'];
		    $pay_option_value=$tabledetails[0]['online_bookings']['pay_option_value'];
		    $remarks=$tabledetails[0]['online_bookings']['remarks'];
		    $usrid = $this->Session->read('Auth.User.id');
        
            $newbookdate= date('d-m-Y', strtotime($bookdate));
    	    $this->set('bookdate', $newbookdate);
    	    $this->set('booktime', $booktime);
    	    $this->set('table_number', $table_number);
    	    $this->set('user_id', $usrid);
    	    $this->set('name', $name);
    	    $this->set('phone', $phone);
    	    $this->set('cover_charge', $cover_charge);
    	    $this->set('pax', $pax);
    	    $this->set('booking_id', $id);
    	    $this->set('payment_type', $payment_type);
    	    $this->set('pay_option', $pay_option);
    	    $this->set('pay_option_value', $pay_option_value);
    	    $this->set('remarks', $remarks);
    	 
	    
            $booking_time=$bookdate.' '.$booktime.':00:00';
            
            $adddatetime = new DateTime($booking_time);
            $adddatetime->modify('+4 hours');
            $add_booking_time = $adddatetime->format('Y-m-d H:i:s');
            
            $subdatetime = new DateTime($booking_time);
            $subdatetime->modify('-4 hours');
            $sub_booking_time = $subdatetime->format('Y-m-d H:i:s');
            
            $tables=$this->Order_table->query("SELECT *,(SELECT id FROM `online_bookings` WHERE booking_time BETWEEN '$sub_booking_time' and '$add_booking_time' and status=1 and table_number=order_tables.number) as bookstatus FROM `order_tables` where number!=$table_number");
            $this->set(compact('tables'));
		}else{
		    $this->Flash->error(__('Invalid Request'));
            return $this->redirect(array('action' => 'create_booking'));
		}
	}
	
	public function edit_book_now()
    {
        $this->layout = false;
        $id = $this->data['User']['id'];
        if ($id) {
            $bookdate = $this->data['User']['bookdate'];
            $booktime = $this->data['User']['booktime'];
            
            if($booktime==10){
                $booktime=22;    
            }
            if($booktime==11){
                $booktime=23;    
            }
            
            $booking_time=$bookdate.' '.$booktime.':00:00';
            
            $adddatetime = new DateTime($booking_time);
            $adddatetime->modify('+4 hours');
            $add_booking_time = $adddatetime->format('Y-m-d H:i:s');
            
            $subdatetime = new DateTime($booking_time);
            $subdatetime->modify('-4 hours');
            $sub_booking_time = $subdatetime->format('Y-m-d H:i:s');
            
            $table = $this->Online_booking->query("SELECT * FROM `online_bookings` WHERE booking_time BETWEEN '$sub_booking_time' and '$add_booking_time' and status=1 and table_number=$id");
            
            if(!$table){
                $ref_id = $this->data['User']['ref_id'];
                $pax = $this->data['User']['pax'];
                $cover_charge=$this->data['User']['cover_charge'];
                $name = $this->data['User']['name'];
                $mobile = $this->data['User']['phone'];
                $remarks = $this->data['User']['remarks'];
                $payment_type=$this->data['User']['payment_type'];
                $pay_type=$this->data['User']['pay_option'];
                $pay_type_value=$this->data['User']['pay_option_value'];
                $booking_id=$this->data['User']['booking_id'];
                // print_r($this->data['User']);exit;
                $booking_time= date('Y-m-d H:i:s', strtotime($booking_time));
	    
                $data['Online_booking']=array(
        			'table_number'=>$id,
        			'reference_id'=>$ref_id,
        			'pax'=>$pax,
        			'cover_charge'=>$cover_charge,
        			'name'=>$name,
        			'phone'=>$mobile,
        			'booking_time'=>$booking_time,
        			'payment_type'=>$payment_type,
        			'pay_option'=>$pay_type,
        			'pay_option_value'=>$pay_type_value,
        			'remarks'=>$remarks
        		);
        	    
        	    if($this->Online_booking->saveAll($data['Online_booking']))
        		{
        		    $lastInsertedID = $this->Online_booking->id;
    		        $this->Online_booking->query("UPDATE online_bookings SET status='2',switch_to='$lastInsertedID',sync = 0 WHERE id =". $booking_id);
            
        		    $this->Flash->success(__('The Booking has been Updated.'));
    				return $this->redirect(array('action' => 'booking_list'));
        		}else{
        		    $this->Flash->error(__('Table not booked,try again'));
                    return $this->redirect(array('action' => 'booking_list'));
        		}
            }else{
                $this->Flash->error(__('Table Already Booked!! kindly try again with another table !'));
                return $this->redirect(array('action' => 'edit_booking?id='.$booking_id));
            }
        }else{
            if($this->request->is('ajax'))
            {
                $booking_id = $this->request->data['booking_id'];
                $cover_charge = $this->request->data['cover_charge'];
                $pax = $this->request->data['pax'];
                $bookdate = $this->request->data['bookdate'];
                $booktime = $this->request->data['booktime'];
                $name = $this->request->data['name'];
                $phone = $this->request->data['phone'];
                $number=$this->request->data['number'];
                $payment_type=$this->request->data['payment_type'];
                $pay_option=$this->request->data['pay_option'];
                $pay_option_value=$this->request->data['pay_option_value'];
                $remarks=$this->request->data['remarks'];
                $prev_table_number=$this->request->data['prev_table_number'];
                $booking_id=$this->request->data['booking_id'];
                $newbookdate= date('d-m-Y', strtotime($bookdate));
        	    
        	    $this->set('bookdate', $newbookdate);
        	    $this->set('booktime', $booktime);
                $this->set('name', $name);
        	    $this->set('phone', $phone);
                $this->set('booking_id', $booking_id);
                $this->set('prev_table_number', $prev_table_number);
                $this->set('payment_type', $payment_type);
                $this->set('pay_option', $pay_option);
                $this->set('pay_option_value', $pay_option_value);
                $this->set('remarks', $remarks);
                
                $booking_time=$bookdate.' '.$booktime.':00:00';
                // print_r($booking_time);exit;
                $adddatetime = new DateTime($booking_time);
                $adddatetime->modify('+4 hours');
                $add_booking_time = $adddatetime->format('Y-m-d H:i:s');
                
                $subdatetime = new DateTime($booking_time);
                $subdatetime->modify('-4 hours');
                $sub_booking_time = $subdatetime->format('Y-m-d H:i:s');
                
                $tablesdata=$this->Order_table->query("SELECT *,(SELECT id FROM `online_bookings` WHERE booking_time BETWEEN '$sub_booking_time' and '$add_booking_time' and status=1 and table_number=$number) as bookstatus FROM `order_tables` where number=$number");
                
                if(!isset($tablesdata[0]['bookstatus'])){
                    $this->set(compact('tablesdata'));
                } else {
                    echo 'Table not Vacant!! Kindly refresh again';
                }
            } else {
                $this->Flash->error(__('Invalid Request'));
                return $this->redirect(array('action' => 'booking_list'));
            }
        }
   }
	public function create_subadmin()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		$authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? '';
        
        $conditions = ['status' => 1];
        
        if ($userRole !== 'admin' && !empty($userLocationId)) {
            $ids = array_filter(array_map('trim', explode(',', $userLocationId))); // clean IDs
            if (!empty($ids)) {
                $conditions['id IN'] = $ids;
            }
        }
        
        $modules=subadminmoduleswithlabel;
        $this->set(compact('modules'));
	    
	    $locations=$this->Location->find('all',['conditions' => $conditions]);
	    $this->set(compact('locations'));
	    
		if ($this->request->is(array('post', 'put'))) {
            
            $name = $this->data['User']['name'];
            if($name==''){
                $this->Flash->error(__('The Name could not be Blank'));
                return $this->redirect(array('action' => 'create_cashier'));
            }
            
            $mobile = $this->data['User']['mobile'];
            $username = $this->data['User']['username'];
        
            $userdetail=$this->User->find('first',array('conditions'=>array('User.username'=>$username)));
	        if($userdetail){
	            $this->Flash->error(__('Username already exist'));
                return $this->redirect(array('action' => 'create_subadmin'));
	        }
            $password =$this->data['User']['password'];
            $password = AuthComponent::password($password);
            
            $modules=subadminmoduleswithlabel;
            $checkedModules = [];
            
            $location_ids =$this->data['User']['location'];
            
            $role =$this->data['User']['role'];
            
            $data['User']=array(
    			'name'=>$name,
    			'username'=>$username,
    			'password'=>$password,
    			'mobile'=>$mobile,
    			'role'=>$role
    	    );
    	    
    	    if($this->User->saveAll($data['User']))
    		{
    		    $lastInsertedID = $this->User->id;
    		    foreach($location_ids as $location_id){
                    $locationdetail=$this->Location->find('first',array('conditions'=>array('Location.id'=>$location_id)));
                    $locationname=$locationdetail['Location']['name'];
                    
                    $data['User_location']=array(
            			'user_id'=>$lastInsertedID,
            			'user_name'=>$username,
            			'location_id'=>$location_id,
            			'location_name'=>$locationname
            		);
            		if($this->User_location->saveAll($data['User_location']))
    	            {
    	                $this->User->query("UPDATE users SET location_id ='$location_id',location_name='$locationname',sync = 0 WHERE id =". $lastInsertedID);
                    }else{
    	                $this->Flash->error(__('The user Locations could not be saved. Please, try again.'));
    	            }
                }
                
    		    foreach ($modules as $moduleKey => $moduleLabel) {
                    if (isset($this->data['User'][$moduleKey]) && $this->data['User'][$moduleKey]) {
                        $checkedModules[$moduleKey] = $this->data['User'][$moduleKey];
                        $data['User_module']=array(
                			'name'=>$moduleKey,
                			'user_id'=>$lastInsertedID
                		);
                		if($this->User_module->saveAll($data['User_module']))
    		            {
    		            }else{
    		                $this->Flash->error(__('The user modules could not be saved. Please, try again.'));
    		            }
                    }
                }
                
                $this->Flash->success(__('The User has been saved.'));
				return $this->redirect(array('action' => 'subadmin_list'));
			} else {
				$this->Flash->error(__('The user could not be saved. Please, try again.'));
			}
		}
		
	}
	
	public function edit_cashier()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		
		if ($this->data['User']['id']!='') {
		  //  print_r($this->data['User']);exit;
            $id=$this->data['User']['id'];
            $name = $this->data['User']['name'];
            if($name==''){
                $this->Flash->error(__('The Name could not be Blank'));
                return $this->redirect(array('action' => 'edit_cashier?id='.$id));
            }
            
            $mobile = $this->data['User']['mobile'];
            $password = $this->data['User']['password'];
        //     $location = $this->data['User']['location'];
            $userdetails=$this->User->find('first',array('conditions'=>array('User.id'=>$id)));
	        $username=$userdetails['User']['username'];
            
            
            $location_ids =$this->data['User']['location'];
            
            $role =$this->data['User']['role'];
            $settlement=$this->data['User']['settlement'];
            
            $bill_location =$this->data['User']['bill_location'];
            $loc_type =$this->data['User']['loc_type'];
            
            if($role=='manager'){
                $pin =$this->data['User']['pin'] ?? 0;
            }else{
                $pin = 0;
            }
            if($loc_type==0){
                $location_ids =[];
            }else{
                $location_ids =$this->data['User']['location'];
            }
            
            $locationdetail = $this->Location->find('first', array(
                                'conditions' => array('Location.id' => $bill_location)
                            ));
                
            if (!empty($locationdetail)) {
                $locationnamee = $locationdetail['Location']['name'];
            }
            
            // print_r($settlement);exit;
            $this->User->query("UPDATE users SET name ='$name',mobile='$mobile',role='$role',pin='$pin',can_settlement='$settlement',location_id='$bill_location',location_name='$locationnamee',sync = 0 WHERE id =". $id);
            if($password){
                $password = AuthComponent::password($password);
                $this->User->query("UPDATE users SET password ='$password',sync = 0 WHERE id =". $id);
            }
            
            $this->User_location->query("UPDATE user_locations SET status=0 WHERE user_id =". $id);
            
            /*
            foreach($location_ids as $location_id){
                $locationdetail=$this->Location->find('first',array('conditions'=>array('Location.id'=>$location_id)));
                $locationname=$locationdetail['Location']['name'];
                
                $data['User_location']=array(
        			'user_id'=>$id,
        			'user_name'=>$username,
        			'location_id'=>$location_id,
        			'location_name'=>$locationname
        		);
            
        		if($this->User_location->saveAll($data['User_location']))
	            {
	            }else{
	                $this->Flash->error(__('The user Locations could not be saved. Please, try again.'));
	            }
            }
            */
            
            foreach($location_ids as $location_id){
                $locationdetail=$this->Location->find('first',array('conditions'=>array('Location.id'=>$location_id)));
                $locationname=$locationdetail['Location']['name'];
                
                $isBill = (!empty($bill_location) && (
                    (is_array($bill_location) && in_array($location_id, $bill_location)) ||
                    (!is_array($bill_location) && $bill_location == $location_id)
               )) ? 1 : 0;
               
                $data['User_location']=array(
        			'user_id'=>$id,
        			'user_name'=>$username,
        			'location_id'=>$location_id,
        			'location_name'=>$locationname,
        			'billing_location'=>$isBill
        		);
            
        		if($this->User_location->saveAll($data['User_location']))
	            {
	            }else{
	                $this->Flash->error(__('The user Locations could not be saved. Please, try again.'));
	            }
            }
            
            if (!empty($bill_location)) {
                $billLocations = is_array($bill_location) ? $bill_location : array($bill_location);
            
                foreach ($billLocations as $billLoc) {
                    if (!in_array($billLoc, $location_ids)) {
                        $locationdetail = $this->Location->find('first', array(
                            'conditions' => array('Location.id' => $billLoc)
                        ));
            
                        if (!empty($locationdetail)) {
                            $locationname = $locationdetail['Location']['name'];
            
                            $data['User_location'] = array(
                                'user_id'       => $id,
                                'user_name'     => $username,
                                'location_id'   => $billLoc,
                                'location_name' => $locationname,
                                'billing_location' => 1
                            );
            
                            $this->User_location->create();
                            if (!$this->User_location->save($data['User_location'])) {
                                $this->Flash->error(__('The extra bill Location could not be saved. Please, try again.'));
                            }
                        }
                    }
                }
            }
            
            $modules=moduleswithlabel;
            $checkedModules = [];
            $this->User->query("DELETE FROM user_modules WHERE user_id =". $id);
            
            foreach ($modules as $moduleKey => $moduleLabel) {
                
                if (isset($this->data['User'][$moduleKey]) && $this->data['User'][$moduleKey]) {
                    $checkedModules[$moduleKey] = $this->data['User'][$moduleKey];
                    // print_r($moduleKey);
                     $data['User_module']=array(
                			'name'=>$moduleKey,
                			'user_id'=>$id
                		);
                		if($this->User_module->saveAll($data['User_module']))
    		            {
    		            }else{
    		                $this->Flash->error(__('The user modules could not be saved. Please, try again.'));
    		            }
                }
            }
            
            $this->Flash->success(__('User has been Updated.'));
            return $this->redirect(array('action' => 'cashier_list'));
		}else{
		    $id=$_REQUEST['id'];
		
		    $userdetail=$this->User->find('first',array('conditions'=>array('User.id'=>$id)));
	        $this->set(compact('userdetail'));
	        
	        $locations=$this->Location->find('all',array('conditions'=>array('status'=>1)));
	        $this->set(compact('locations'));
	        
	        // Get selected location IDs
            $selectedlocationss = $this->User_location->find('list', [
                'conditions' => ['User_location.status' => 1, 'User_location.user_id' => $id],
                'fields' => ['User_location.location_id', 'User_location.location_id']
            ]);
            
            $selectedLocationIds = array_keys($selectedlocationss);
            $hasMultiple = (count($selectedLocationIds) > 1) ? 1 : 0;
            
            // Get selected Billing location IDs
            $selectedbillinglocationss = $this->User_location->find('first', [
                'conditions' => ['User_location.status' => 1,'User_location.billing_location' => 1, 'User_location.user_id' => $id],
                'fields' => ['User_location.location_id', 'User_location.location_id']
            ]);
            
            $billing_location=$selectedbillinglocationss['User_location']['location_id'];
            
            $this->set(compact('selectedLocationIds','hasMultiple','billing_location'));
	        
	        $selectemodule="SELECT name FROM user_modules where user_id=$id"; 
            $selectemodules=$this->User_module->query($selectemodule);
            $this->set(compact('selectemodules'));
	        
	        $modules=moduleswithlabel;
            $this->set(compact('modules'));
	        
            
		}
		
    }
	
	public function edit_subadmin()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		
		if ($this->data['User']['id']!='') {
		  //  print_r($this->data['User']);exit;
            $id=$this->data['User']['id'];
            $name = $this->data['User']['name'];
            if($name==''){
                $this->Flash->error(__('The Name could not be Blank'));
                return $this->redirect(array('action' => 'edit_subadmin?id='.$id));
            }
            
            $mobile = $this->data['User']['mobile'];
            $password = $this->data['User']['password'];
            $location_ids = $this->data['User']['location'];
            $role =$this->data['User']['role'];
            $userdetails=$this->User->find('first',array('conditions'=>array('User.id'=>$id)));
	        $username=$userdetails['User']['username'];
	        
	        $this->User->query("UPDATE users SET name ='$name',mobile='$mobile',sync = 0,role='$role' WHERE id =". $id);
            if($password){
                $password = AuthComponent::password($password);
                $this->User->query("UPDATE users SET password ='$password',sync = 0 WHERE id =". $id);
            }
            
            $this->User_location->query("UPDATE user_locations SET status=0 WHERE user_id =". $id);
            foreach($location_ids as $location_id){
                $locationdetail=$this->Location->find('first',array('conditions'=>array('Location.id'=>$location_id)));
                $locationname=$locationdetail['Location']['name'];
                
                $data['User_location']=array(
        			'user_id'=>$id,
        			'user_name'=>$username,
        			'location_id'=>$location_id,
        			'location_name'=>$locationname
        		);
            
        		if($this->User_location->saveAll($data['User_location']))
	            {
                    $this->User->query("UPDATE users SET location_id ='$location_id',location_name='$locationname',sync = 0 WHERE id =". $id);
	            }else{
	                $this->Flash->error(__('The user Locations could not be saved. Please, try again.'));
	            }
            }
            $modules=subadminmoduleswithlabel;
            $checkedModules = [];
            $this->User->query("DELETE FROM user_modules WHERE user_id =". $id);
        
            foreach ($modules as $moduleKey => $moduleLabel) {
                
                if (isset($this->data['User'][$moduleKey]) && $this->data['User'][$moduleKey]) {
                    $checkedModules[$moduleKey] = $this->data['User'][$moduleKey];
                    // print_r($moduleKey);
                     $data['User_module']=array(
                			'name'=>$moduleKey,
                			'user_id'=>$id
                		);
                		if($this->User_module->saveAll($data['User_module']))
    		            {
    		            }else{
    		                $this->Flash->error(__('The user modules could not be saved. Please, try again.'));
    		            }
                }
            }
            
            $this->Flash->success(__('Sub admin has been Updated.'));
            return $this->redirect(array('action' => 'subadmin_list'));
		}else{
		    $id=$_REQUEST['id'];
		
		    $userdetail=$this->User->find('first',array('conditions'=>array('User.id'=>$id)));
	        $this->set(compact('userdetail'));
	        
	        $locations=$this->Location->find('all',array('conditions'=>array('status'=>1)));
	        $this->set(compact('locations'));
	        
	        // Get selected location IDs
            $selectedlocationss = $this->User_location->find('list', [
                'conditions' => ['User_location.status' => 1, 'User_location.user_id' => $id],
                'fields' => ['User_location.location_id', 'User_location.location_id']
            ]);
            $selectedLocationIds = array_keys($selectedlocationss);
            $this->set(compact('selectedLocationIds'));
	        
	        
	        $selectemodule="SELECT name FROM user_modules where user_id=$id"; 
            $selectemodules=$this->User_module->query($selectemodule);
            $this->set(compact('selectemodules'));
	        
	        $modules=subadminmoduleswithlabel;
            $this->set(compact('modules'));
	        
            
		}
		
    }
	
	public function create_category()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		if ($this->request->is(array('post', 'put'))) {
            
            $name = $this->data['User']['name'];
            if($name==''){
                $this->Flash->error(__('The Name could not be Blank'));
                return $this->redirect(array('action' => 'create_category'));
            }
            
            if(isset($_POST['subcat'])){
                $is_subcat=1;
            }else{
                $is_subcat=0;
            }
            
            $image=$this->data['User']['image'];
            if (!empty($image['name'])) {
                $uploadPath = WWW_ROOT . 'uploads' . DS . 'category_images' . DS;
                $file=basename(time().$image['name']);
                $file = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', $file);
                $uploadFile = $uploadPath . $file;
                
                if (move_uploaded_file($image['tmp_name'], $uploadFile)) {
                    $filename=$file;
                }else{
                    $filename='';
                }
            }
            // print_r($this->data);exit;
            
            $data['Catalog_category']=array(
    			'name'=>$name,
    			'is_subcategory'=>$is_subcat,
    			'image'=>$filename
    	    );
    	    
    	    if($this->Catalog_category->saveAll($data['Catalog_category']))
    		{
    		    $lastInsertedID = $this->Catalog_category->id;
    		    if(isset($_POST['subcat'])){
                    $subcats = $_POST['subcat'];
                    foreach ($subcats as $subcat) {
                        $data['Catalog_subcategory']=array(
                			'cat_id'=>$lastInsertedID,
                			'name'=>$subcat
                		);
                	    
                	    if($this->Catalog_subcategory->saveAll($data['Catalog_subcategory']))
                		{
                		    
                		}else{
                		    $this->Flash->error(__('Sub category could not be saved. Please, try again.'));
                		}
                    }
                }
        	    
    		    
                $this->Flash->success(__('Category has been saved.'));
				return $this->redirect(array('action' => 'category_list'));
			} else {
				$this->Flash->error(__('Category could not be saved. Please, try again.'));
			}
		}
	}
	
	public function edit_category()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		$id=$_REQUEST['id'];
		
		$categories = $this->Catalog_category->query("SELECT * FROM catalog_category where id=$id");
        $this->set(compact('categories'));
        
        $subcategories=$this->Catalog_subcategory->query("SELECT * FROM catalog_subcategory where cat_id=$id and status=1");
        $this->set(compact('subcategories')); 
        
        if ($this->request->is(array('post', 'put'))) {
            // print_r($this->data);exit;
            $id = $this->data['User']['id'];
            $name = $this->data['User']['name'];
            if($name==''){
                $this->Flash->error(__('The Name could not be Blank'));
                return $this->redirect(array('action' => 'edit_category?id='.$id));
            }
            
            $image=$this->data['User']['image'];
            if (!empty($image['name'])) {
                $uploadPath = WWW_ROOT . 'uploads' . DS . 'category_images' . DS;
                $file=basename(time().$image['name']);
                $file = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', $file);
                $uploadFile = $uploadPath . $file;
                
                if (move_uploaded_file($image['tmp_name'], $uploadFile)) {
                    $filename=$file;
                }else{
                    $filename='';
                }
                $this->Catalog_category->query("UPDATE `catalog_category` SET image='$filename',sync = 0 WHERE id=$id");
            }
            $this->Catalog_category->query("UPDATE `catalog_category` SET name='$name',sync = 0 WHERE id=$id");
            
	        $lastInsertedID = $id;
		    if(isset($_POST['subcat'])){
                $subcats = $_POST['subcat'];
                foreach ($subcats as $subcat) {
                    $data['Catalog_subcategory']=array(
            			'cat_id'=>$lastInsertedID,
            			'name'=>$subcat
            		);
            	    
            	    if($this->Catalog_subcategory->saveAll($data['Catalog_subcategory']))
            		{
            		    
            		}else{
            		    $this->Flash->error(__('Sub category could not be saved. Please, try again.'));
            		}
                }
            }
    	    
    	    $subcategorychk=$this->Catalog_subcategory->query("SELECT * FROM catalog_subcategory where cat_id=$id and status=1");
            if($subcategorychk){
                $this->Catalog_category->query("UPDATE `catalog_category` SET is_subcategory='1',sync = 0 WHERE id=$id");
            }else{
                $this->Catalog_category->query("UPDATE `catalog_category` SET is_subcategory='0',sync = 0 WHERE id=$id");
            }
		    
            $this->Flash->success(__('Category has been Updated.'));
			return $this->redirect(array('action' => 'category_list'));
		
		}
	}
	
    public function create_subcategory()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		if ($this->request->is(array('post', 'put'))) {
            $subcategoriesname=$_POST['subcat'];
            $categoryid = $this->data['User']['category'];
            if($categoryid==''){
                $this->Flash->error(__('Select Category'));
                return $this->redirect(array('action' => 'create_subcategory'));
            }
            
            $image=$this->data['User']['image'];
            if (!empty($image['name'])) {
                $uploadPath = WWW_ROOT . 'uploads' . DS . 'category_images' . DS;
                $file=basename(time().$image['name']);
                $file = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', $file);
                $uploadFile = $uploadPath . $file;
                
                if (move_uploaded_file($image['tmp_name'], $uploadFile)) {
                    $filename=$file;
                }else{
                    $filename='';
                }
            }
            
            foreach($subcategoriesname as $subcategory){
                $data['Catalog_subcategory']=array(
        			'name'=>$subcategory,
        			'cat_id'=>$categoryid,
        			'image'=>$filename
        	    );
                
                if($this->Catalog_subcategory->saveAll($data['Catalog_subcategory']))
    		    {
    		        $savechk=true;
    		        
                }else{
                    $savechk=false;
                }
        	    
            }    
            
            if($savechk){
                $this->Catalog_category->query("UPDATE `catalog_category` SET is_subcategory='1',sync = 0 WHERE id=$categoryid");
            
    		        
                $this->Flash->success(__('Sub Category has been saved.'));
				return $this->redirect(array('action' => 'subcategory_list'));
			} else {
				$this->Flash->error(__('Some sub Category could not be saved. Please, try again.'));
				return $this->redirect(array('action' => 'subcategory_list'));
			}
		}
		
		$categories=$this->Catalog_category->find('all',array('conditions'=>array('status'=>1)));
	    $this->set(compact('categories'));
	
	}
	
	public function create_tax()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		if ($this->request->is(array('post', 'put'))) {
            
            $name = $this->data['User']['name'];
            if($name==''){
                $this->Flash->error(__('The Name could not be Blank'));
                return $this->redirect(array('action' => 'create_tax'));
            }
            $tax = $this->data['User']['tax'];
            if($tax==''){
                $this->Flash->error(__('Tax Percentage could not be Blank'));
                return $this->redirect(array('action' => 'create_tax'));
            }
            
            $data['Catalog_tax']=array(
    			'name'=>$name,
    			'percentage'=>$tax
    	    );
    	    
    	    if($this->Catalog_tax->saveAll($data['Catalog_tax']))
    		{
    		    $this->Flash->success(__('Tax has been saved.'));
				return $this->redirect(array('action' => 'tax_list'));
			} else {
				$this->Flash->error(__('Tax could not be saved. Please, try again.'));
			}
		}
	}
	
	public function edit_tax()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
	    
	    $id=$_REQUEST['id'];
		$taxes=$this->Catalog_tax->find('all',array('conditions'=>array('id'=>$id)));
	    $this->set(compact('taxes'));
	    
		if ($this->request->is(array('post', 'put'))) {
            
            $id = $this->data['User']['id'];
            $name = $this->data['User']['name'];
            if($name==''){
                $this->Flash->error(__('The Name could not be Blank'));
                return $this->redirect(array('action' => 'create_tax'));
            }
            $tax = $this->data['User']['tax'];
            if($tax==''){
                $this->Flash->error(__('Tax Percentage could not be Blank'));
                return $this->redirect(array('action' => 'create_tax'));
            }
            
            $this->Catalog_tax->query("UPDATE `catalog_tax` SET name='$name',percentage='$tax',sync = 0 WHERE id=$id");
            
		    $this->Flash->success(__('Tax has been updated.'));
			return $this->redirect(array('action' => 'tax_list'));
		}
	}
	
	public function create_location()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		if ($this->request->is(array('post', 'put'))) {
            
            $name = $this->data['User']['name'];
            if($name==''){
                $this->Flash->error(__('The Name could not be Blank'));
                return $this->redirect(array('action' => 'create_location'));
            }
            
            $username = $this->data['User']['username'];
            $userdetail=$this->Location->find('first',array('conditions'=>array('Location.username'=>$username)));
	        if($userdetail){
	            $this->Flash->error(__('Username already exist'));
                return $this->redirect(array('action' => 'create_location'));
	        }
            $password = $this->data['User']['password'];
            $password = AuthComponent::password($password);
            $type = $this->data['User']['type'];
            $print_line1 = $this->data['User']['print_line1'];
            $print_line2 = $this->data['User']['print_line2'];
            $print_line3 = $this->data['User']['print_line3'];
            $print_line4 = $this->data['User']['print_line4'];
            $print_line5 = $this->data['User']['print_line5'];
            $print_line6 = $this->data['User']['print_line6'];
            $print_line7 = $this->data['User']['print_line7'];
            $print_line8 = $this->data['User']['print_line8'];
            $print_line9 = $this->data['User']['print_line9'];
            $print_line10 = $this->data['User']['print_line10'];
            $footer_msg = $this->data['User']['footer_msg'];
            $currency_symbol = $this->data['User']['currency_symbol'];
            
            $data['Location']=array(
    			'name'=>$name,
    			'username'=>$username,
    			'password'=>$password,
    			'type'=>$type,
    			'print_line1'=>$print_line1,
    			'print_line2'=>$print_line2,
    			'print_line3'=>$print_line3,
    			'print_line4'=>$print_line4,
    			'print_line5'=>$print_line5,
    			'print_line6'=>$print_line6,
    			'print_line7'=>$print_line7,
    			'print_line8'=>$print_line8,
    			'print_line9'=>$print_line9,
    			'print_line10'=>$print_line10,
    			'footer_msg'=>$footer_msg,
    			'currency_symbol'=>$currency_symbol
    	    );
    	    
    	    if($this->Location->saveAll($data['Location']))
    		{
    		    $this->Flash->success(__('Location has been saved.'));
				return $this->redirect(array('action' => 'location_list'));
			} else {
				$this->Flash->error(__('Location could not be saved. Please, try again.'));
			}
		}
	}
	
	public function create_coupon()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		if ($this->request->is(array('post', 'put'))) {
            
            $code = $this->data['User']['code'];
            if($code==''){
                $this->Flash->error(__('Coupon Code could not be Blank'));
                return $this->redirect(array('action' => 'create_coupon'));
            }
            $coupon_value = $this->data['User']['coupon_value'];
            $month=$this->data['User']['expiry_date']['month'];
            $day=$this->data['User']['expiry_date']['day'];
            $year=$this->data['User']['expiry_date']['year'];
            
            $date=$year.'-'.$month.'-'.$day;

            $data['Coupon']=array(
    			'code'=>$code,
    			'value'=>$coupon_value,
    			'expiry_date'=>$date
    	    );
    	    
    	    if($this->Coupon->saveAll($data['Coupon']))
    		{
    		    $this->Flash->success(__('Coupon has been saved.'));
				return $this->redirect(array('action' => 'coupon_list'));
			} else {
				$this->Flash->error(__('Coupon could not be saved. Please, try again.'));
			}
		}
	}
	
	public function edit_coupon()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		
		if ($this->data['User']['id']!='') {
            $id=$this->data['User']['id'];
            $value = $this->data['User']['value'];
            if($value==''){
                $this->Flash->error(__('Coupon Value could not be Blank'));
                return $this->redirect(array('action' => 'edit_coupon?id='.$id));
            }
            
            $month=$this->data['User']['expiry']['month'];
            $day=$this->data['User']['expiry']['day'];
            $year=$this->data['User']['expiry']['year'];
            
            $date=$year.'-'.$month.'-'.$day;
            
            $this->Coupon->query("UPDATE coupons SET value ='$value',expiry_date='$date',sync = 0 WHERE id =". $id);
            $this->Flash->success(__('Coupon has been Updated.'));
            return $this->redirect(array('action' => 'coupon_list'));
		}else{
		    $id=$_REQUEST['id'];
		
		    $coupons = $this->Coupon->query("SELECT * FROM coupons where id=$id");
            $this->set(compact('coupons'));
		}
		
    }
	
	public function create_table()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		$authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;
        
        $conditions = ['status' => 1]; // always filter by active
        
        if ($userRole !== 'admin') {
            // normalize to array
            $userLocationIds = is_array($userLocationId) ? $userLocationId : [$userLocationId];
            $conditions['id IN'] = $userLocationIds;
        }
        
        $locations = $this->Location->find('all', [
            'conditions' => $conditions
        ]);
        
	    $this->set(compact('locations'));
		if ($this->request->is(array('post', 'put'))) {
            
            $number = $this->data['User']['number'];
            if($number==''){
                $this->Flash->error(__('Table Number could not be Blank'));
                return $this->redirect(array('action' => 'create_table'));
            }
            $cover_charge = $this->data['User']['cover_charge'];
            $weekend_charge=$this->data['User']['weekend_charge'];
            $pax = $this->data['User']['pax'];
            $waiter = $this->data['User']['waiter'];
            $customer = $this->data['User']['customer'];
            
            $location_id =$this->data['User']['location'];
            $locationdetail=$this->Location->find('first',array('conditions'=>array('Location.id'=>$location_id)));
	        $locationname=$locationdetail['Location']['name'];
            
            
            $tables=$this->Order_table->find('all',array('conditions'=>array('number'=>$number)));
            if(!empty($tables)){
	            $this->Flash->error(__('Table already exist.'));
	            return $this->redirect(array('action' => 'table_list'));
	        }
	        do {
                $pin = uniqid();
            } while ($this->Order_table->find('first', array('fields' => 'Order_table.id', 'conditions' => array('Order_table.reference_id' => $pin))));
            
            
            $data['Order_table']=array(
    			'number'=>$number,
    			'reference_id'=>$pin,
    			'cover_charge'=>$cover_charge,
    			'weekend_charge'=>$weekend_charge,
    			'pax'=>$pax,
    			'is_waiter_required'=>$waiter,
    			'is_customer_detail_required'=>$customer,
    			'location_id'=>$location_id,
    			'location_name'=>$locationname
    		);
    	    
    	    if($this->Order_table->saveAll($data['Order_table']))
    		{
    		    $this->Flash->success(__('Table has been saved.'));
				return $this->redirect(array('action' => 'table_list'));
			} else {
				$this->Flash->error(__('Table could not be saved. Please, try again.'));
			}
		}
	}
	
	public function edit_table()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;
        
        // $locationCondition = '';
        $conditions = ['status' => 1]; // always filter active locations

        if ($userRole !== 'admin') {
            // normalize to array for safety
            $userLocationIds = is_array($userLocationId) ? $userLocationId : [$userLocationId];
            $conditions['id IN'] = $userLocationIds; // CakePHP will handle IN automatically
        }
        // if ($userRole !== 'admin') {
        //     $locationCondition = "id = " . (int)$userLocationId;
        // }
        
		if ($this->data['User']['id']!='') {
		  
		    $id = $this->data['User']['id'];
            $cover_charge = $this->data['User']['cover_charge'];
            $pax = $this->data['User']['pax'];
            $weekend_charge = $this->data['User']['weekend_charge'];
            $waiter = $this->data['User']['waiter'];
            $customer = $this->data['User']['customer'];
            $location = $this->data['User']['location'];
            $locationdetail=$this->Location->find('first',array('conditions'=>array('Location.id'=>$location)));
	        $locationname=$locationdetail['Location']['name'];
            
            $this->Order_table->query("UPDATE order_tables SET cover_charge ='$cover_charge',pax='$pax',weekend_charge='$weekend_charge',is_waiter_required='$waiter',is_customer_detail_required='$customer',location_id='$location',location_name='$locationname',sync = 0 WHERE id =". $id);
            $this->Flash->success(__('Table has been Updated.'));
            return $this->redirect(array('action' => 'table_list'));
		}else{
		    $id=$_REQUEST['id'];
		
		    $userdetail=$this->Order_table->find('first',array('conditions'=>array('Order_table.id'=>$id)));
	        $this->set(compact('userdetail'));
	        
	        $locations=$this->Location->find('all',array('conditions'=>$conditions));
	        $this->set(compact('locations'));
	        
	  	}
		
    }
	
	public function tax_list() 
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		$startDate = date('m/d/Y', strtotime('-12 months'));
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }   
        
		
		$users = $this->Catalog_tax->query("SELECT * FROM catalog_tax where created between '$startdate 00:00:01' and  '$enddate 23:59:59' ORDER BY id desc");
        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        
		$this->set(compact('users'));

	}
	
	public function unit_list() 
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		$startDate = date('m/d/Y', strtotime('-12 months'));
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }   
        
		
		$users = $this->Catalog_unit->query("SELECT * FROM catalog_units where created between '$startdate 00:00:01' and  '$enddate 23:59:59' ORDER BY id desc");
        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        
		$this->set(compact('users'));

	}
	
	public function create_unit()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		if ($this->request->is(array('post', 'put'))) {
            
            $name = $this->data['User']['name'];
            if($name==''){
                $this->Flash->error(__('The Name could not be Blank'));
                return $this->redirect(array('action' => 'create_unit'));
            }
            $unit=$this->Catalog_unit->find('all',array('conditions'=>array('name'=>$name)));
	        if($unit){
	            $this->Flash->error(__('Unit Name already exist'));
                return $this->redirect(array('action' => 'unit_list'));
	        }
            $data['Catalog_unit']=array(
    			'name'=>$name
    	    );
    	    
    	    if($this->Catalog_unit->saveAll($data['Catalog_unit']))
    		{
		        $unit_id = $this->Catalog_unit->id;

    		    $data['Catalog_unit_mapping']=array(
        			'unit_id'=>$unit_id,
        			'unit_name'=>$name,
        			'mapped_unit_id'=>$unit_id,
        			'mapped_unit_name'=>$name,
        			'conversion_factor'=>1
        	    );
        	    if(!$this->Catalog_unit_mapping->saveAll($data['Catalog_unit_mapping']))
    		    {
    		        $this->Flash->error(__('Unit could not be Mapped.'));
    		    }
    		    $this->Flash->success(__('Unit has been saved.'));
				return $this->redirect(array('action' => 'unit_list'));
			} else {
				$this->Flash->error(__('Unit could not be saved. Please, try again.'));
			}
		}
	}
	
	public function edit_unit()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
	    
	    $id=$_REQUEST['id'];
		$taxes=$this->Catalog_unit->find('all',array('conditions'=>array('id'=>$id)));
	    $this->set(compact('taxes'));
	    
		if ($this->request->is(array('post', 'put'))) {
            
            $id = $this->data['User']['id'];
            $name = $this->data['User']['name'];
            if($name==''){
                $this->Flash->error(__('The Name could not be Blank'));
                return $this->redirect(array('action' => 'edit_unit'));
            }
            $this->Catalog_unit->query("UPDATE `catalog_units` SET name='$name',sync = 0 WHERE id=$id");
            // Update unit_name where unit_id = $id
            $this->Catalog_unit_mapping->updateAll(
                ['unit_name' => "'$name'"],
                ['unit_id' => $id]
            );
            
            // Update mapped_unit_name where mapped_unit_id = $id
            $this->Catalog_unit_mapping->updateAll(
                ['mapped_unit_name' => "'$name'"],
                ['mapped_unit_id' => $id]
            );

            $this->Flash->success(__('Unit has been updated.'));
			return $this->redirect(array('action' => 'unit_list'));
		}
	}
	
	public function location_list() {
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;
	    $this->layout = "users";
		$startDate = date('m/d/Y', strtotime('-12 months'));
        $endDate = date('m/d/Y');
        if($userRole == 'subadmin'){
            $id = $authUser['id'];                      
            $locations = $this->User_location->find('list', [
                'conditions' => ['status' => 1, 'user_id' => $id],
                'fields' => ['location_id']
            ]);
            $userLocationId = implode(',', array_values($locations));
        }
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }   
        
		$locationCondition = '';
        if ($userRole !== 'admin') {
                $locationCondition = "AND id IN (" . $userLocationId .")";
        }
        
        $users = $this->Location->query("SELECT * FROM locations where created between '$startdate 00:00:01' and  '$enddate 23:59:59' $locationCondition ORDER BY id desc");
        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        
		$this->set(compact('users'));

	}
	
	public function coupon_list() {
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		$startDate = date('m/d/Y', strtotime('-12 months'));
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }   
        
		
		$users = $this->Coupon->query("SELECT * FROM coupons where created between '$startdate 00:00:01' and  '$enddate 23:59:59' ORDER BY id desc");
        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        
		$this->set(compact('users'));

	}
	
	public function table_list() {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);		
        }
    
        $this->layout = "users";
    
        $users = [];
    
        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;

        $userLocationIds = is_array($userLocationId) ? $userLocationId : [$userLocationId];
        
        $placeholders = implode(',', array_fill(0, count($userLocationIds), '?'));
        $conditions = "1=1";
        
        if ($userRole !== 'admin' && !empty($userLocationIds)) {
            $conditions .= " AND location_id IN ($placeholders)";
        }
        
        $users = $this->Catalog_tax->query(
            "SELECT * FROM order_tables WHERE $conditions ORDER BY id DESC",
            $userLocationIds
        );
    
    
        $this->set(compact('users'));
    }

	public function booking_list() {
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		$startDate = date('m/d/Y', strtotime('-7 days'));
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }   
        
		
		$users = $this->Online_booking->query("SELECT * FROM online_bookings where created between '$startdate 00:00:01' and  '$enddate 23:59:59' and status=1 ORDER BY id desc");
        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        
		$this->set(compact('users'));

	}
	
	public function create_product() {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "users";
    
        // Load categories and subcategories into grouped select options
        $categorys = $this->Catalog_category->find('all', ['conditions' => ['status' => 1]]);
        $options = [];
    
        foreach ($categorys as $category) {
            $cat_id = $category['Catalog_category']['id'];
            $cat_name = $category['Catalog_category']['name'];
    
            $subcategorys = $this->Catalog_subcategory->find('all', [
                'conditions' => ['cat_id' => $cat_id, 'status' => 1]
            ]);
    
            if ($subcategorys) {
                $options[$cat_name] = [];
                foreach ($subcategorys as $sub) {
                    // $options[$cat_name][$sub['Catalog_subcategory']['id']] = $sub['Catalog_subcategory']['name'];
                    $sub_id = $sub['Catalog_subcategory']['id'];
                    $sub_name = $sub['Catalog_subcategory']['name'];
                    $options[$cat_name]["sub_$sub_id"] = $sub_name;
                }
            } else {
                $options["cat_$cat_id"] = $cat_name;
            }
        }
        $locations=$this->Location->find('all',array('conditions'=>array('status'=>1)));
	    $this->set(compact('locations'));
		
        $taxes = $this->Catalog_tax->find('all', array('conditions' => array('status' => 1)));
        
        $linkedGroupIds = $this->Inventory_linking->find('list', [
            'fields' => ['Inventory_linking.parent_id'],
            'conditions' => [
                'Inventory_linking.status' => 1,
                'Inventory_linking.parent_type' => 'Modifier_group',
                'Inventory_linking.component_type' => 'Modifier'
            ],
            'recursive' => -1
        ]);
        // print_r($linkedGroupIds);exit;
        $modifiers = $this->Catalog_modifier_group->find('all', [
            'conditions' => [
                'Catalog_modifier_group.status' => 1,
                'Catalog_modifier_group.id' => array_values($linkedGroupIds)
            ],
            'recursive' => -1
        ]);
        // $taxes = $this->Catalog_tax->find('all');
        $units = $this->Catalog_unit->find('all', ['conditions' => ['status' => 1]]);
        $kdss = $this->Pos_printer->find('all', ['conditions' => ['status' => 1]]);
        
        $this->set(compact('categorys', 'subcategorys', 'taxes', 'units', 'options', 'kdss','modifiers'));
    
        if ($this->request->is(['post', 'put'])) {
            $form = $this->request->data['Product'];
            // print_r($form);exit;
            if (empty($form['name'])) {
                $this->Flash->error(__('The product name cannot be blank.'));
                return $this->redirect(['action' => 'create_product']);
            }
        
            // CATEGORY
            $category_id = null;
            $category_name = '';
            $subcategory_id = '';
            $subcategory_name = '';
            
            $categoryInput = $form['category'] ?? '';
            
            if (strpos($categoryInput, 'cat_') === 0) {
                // Existing category (ID)
                // $category_id = (int)$categoryInput;
                // $catData = $this->Catalog_category->findById($category_id);
                // if ($catData) {
                //     $category_name = $catData['Catalog_category']['name'];
                // }
                
                $category_id = (int) str_replace('cat_', '', $categoryInput);
                $catData = $this->Catalog_category->findById($category_id);
                if ($catData) {
                    $category_name = $catData['Catalog_category']['name'];
                }
                
            } elseif (strpos($categoryInput, 'sub_') === 0) {

                // New category name
                // $newcat = trim($categoryInput);
                // $this->Catalog_category->create();
                // if ($this->Catalog_category->save(['name' => $newcat])) {
                //     $category_id = $this->Catalog_category->id;
                //     $category_name = $newcat;
                // } else {
                //     $this->Flash->error(__('New category could not be saved. Please try again.'));
                //     return;
                // }
                
                $subcategory_id = (int) str_replace('sub_', '', $categoryInput);
                $subcatData = $this->Catalog_subcategory->findById($subcategory_id);
                if ($subcatData) {
                    $subcategory_name = $subcatData['Catalog_subcategory']['name'];
                    $category_id = $subcatData['Catalog_subcategory']['cat_id'];
                    $category_name = $this->Catalog_category->field('name', ['id' => $category_id]);
                }
            } else {
                // Treat as new category name
                $newcat = trim($categoryInput);
                $this->Catalog_category->create();
                if ($this->Catalog_category->save(['name' => $newcat])) {
                    $category_id = $this->Catalog_category->id;
                    $category_name = $newcat;
                } else {
                    $this->Flash->error(__('New category could not be saved. Please try again.'));
                    return;
                }
            }
        
            //Unit
            $unit_id = null;
            $unit_name = '';
            
            $unitInput = $form['unit'] ?? '';
            
            if (is_numeric($unitInput)) {
                // Existing unit
                $unit_id = (int)$unitInput;
                $unitData = $this->Catalog_unit->findById($unit_id);
                $unit_name = $unitData['Catalog_unit']['name'] ?? '';
            } else {
                // New unit name
                $newunit = trim($unitInput);
                $this->Catalog_unit->create();
                if ($this->Catalog_unit->save(['name' => $newunit])) {
                    $unit_id = $this->Catalog_unit->id;
                    $unit_name = $newunit;
                } else {
                    $this->Flash->error(__('New unit could not be saved. Please try again.'));
                    return;
                }
            }
            
            
            $kds_id = null;
            $kds_name = '';
            $kds_input = $form['kds'] ?? '';
            $customKds = $_POST['custom_kds'] ?? [];
            
            if (is_numeric($kds_input)) {
                // Existing KDS selected
                $kds_id = (int)$kds_input;
                $existing = $this->Pos_printer->findById($kds_id);
                $kds_name = $existing['Pos_printer']['name'] ?? '';
            } elseif (!empty($customKds)) {
                // Custom KDS submitted via modal
                $firstKds = reset($customKds); // Get first added custom KDS
                
                $locationdetail = $this->Location->find('first', [
                    'conditions' => ['Location.id' => $firstKds['location']]
                ]);
                $locationname = $locationdetail['Location']['name'] ?? '';
                
                $kdsData = [
                    'name' => $firstKds['name'] ?? '',
                    'ip' => $firstKds['ip'] ?? '',
                    'store_id' => $firstKds['location'] ?? 0,
                    'store_name' => $locationname, // fixed
                ];

                $this->Pos_printer->create();
                if ($this->Pos_printer->save($kdsData)) {
                    $kds_id = $this->Pos_printer->id;
                    $kds_name = $kdsData['name'];
                    
                    $this->Pos_printer->id = $kds_id;
                    $this->Pos_printer->saveField('kds', $kds_id);              
                } else {
                    $this->Flash->error(__('New KDS could not be saved.'));
                    return;
                }
            }
            
            // IMAGE
            $filename = '';
            if (!empty($form['image']['name'])) {
                $uploadPath = WWW_ROOT . 'uploads' . DS . 'product_images' . DS;
                $filename = time() . '_' . preg_replace('/[^A-Za-z0-9_\-\.]/', '_', $form['image']['name']);
                $uploadFile = $uploadPath . $filename;
                if (!move_uploaded_file($form['image']['tmp_name'], $uploadFile)) {
                    $filename = '';
                }
            }
            
            // PRODUCT MAIN DATA
            $data = [
                'Catalog_product' => [
                    'name' => $form['name'],
                    'cat_id' => $category_id,
                    'cat_name' => $category_name,
                    'subcat_id' => $subcategory_id,
                    'subcat_name' => $subcategory_name,
                    'unit' => $unit_id,
                    'unit_name' => $unit_name,
                    'description' => $form['description'] ?? '',
                    'dish_type' => $form['dish_type'] ?? 0,
                    'food_type' => $form['food_type'] ?? 0,
                    'package' => $form['package'] ?? 0,
                    'preparation_time' => $form['preparation'] ?? 0,
                    'serve_time' => $form['serve_time'] ?? 0,
                    'moq' => $form['moq'] ?? 0,
                    'sort_order' => $form['sort_order'] ?? 0,
                    'recommended' => $form['recommended'] ?? '',
                    'variation' => $form['variation'] ?? '',
                    'price' => $form['price'] ?? 0,
                    'markup_price' => $form['markup_price'] ?? 0,
                    'allergy_tags' => $form['allergy_tags'] ?? '',
                    'weight' => $form['weight'] ?? 0,
                    'serves_people' => $form['serves_people'] ?? 0,
                    'kds' => $kds_id,
                    'image' => $filename
                ]
            ];
            
            if ($this->Catalog_product->save($data)) {
                $productId = $this->Catalog_product->id;
                
                // ✅ TAXES (dynamic + static)
                $finalTaxIds = [];
        
                if (!empty($form['custom_taxes'])) {
                    foreach ($form['custom_taxes'] as $customKey => $taxData) {
                        $name = trim($taxData['name'] ?? '');
                        $percentage = floatval($taxData['percentage'] ?? 0);
                        $isChecked = !empty($form['tax_ids'][$customKey]);
        
                        if ($name && $percentage && $isChecked) {
                            $existing = $this->Catalog_tax->find('first', ['conditions' => ['name' => $name, 'percentage' => $percentage]]);
                            $taxId = $existing['Catalog_tax']['id'] ?? null;
        
                            if (!$taxId) {
                                $this->Catalog_tax->create();
                                if ($this->Catalog_tax->save(['name' => $name, 'percentage' => $percentage])) {
                                    $taxId = $this->Catalog_tax->id;
                                }
                            }
        
                            if ($taxId) {
                                $finalTaxIds[$taxId] = ['name' => $name, 'percentage' => $percentage];
                            }
                        }
                    }
                }
                
                if (!empty($form['tax_ids'])) {
                    foreach ($form['tax_ids'] as $taxId => $selected) {
                        if (is_numeric($taxId) && $selected) {
                            $tax = $this->Catalog_tax->findById($taxId);
                            if ($tax) {
                                $finalTaxIds[$taxId] = [
                                    'name' => $tax['Catalog_tax']['name'],
                                    'percentage' => $tax['Catalog_tax']['percentage']
                                ];
                            }
                        }
                    }
                }
                
                if (!empty($finalTaxIds)) {
                    foreach ($finalTaxIds as $taxId => $tdata) {
                        $this->Catalog_product_tax->create();
                        $this->Catalog_product_tax->save([
                            'product_id' => $productId,
                            'product_name' => $form['name'],
                            'tax_id' => $taxId,
                            'tax_name' => $tdata['name'],
                            'tax_percentage' => $tdata['percentage']
                        ]);
                    }
                }
                
                //modifier group
                if (!empty($form['modifiers'])) {
                    foreach ($form['modifiers'] as $modifierId => $selected) {
                        if ($selected) {
                            $modifier_id = $this->Catalog_modifier_group->findById($modifierId);
                            if ($modifier_id) {
                                $finalModifierIds[$modifierId] = [
                                    'id' => $modifier_id['Catalog_modifier_group']['id'],
                                    'name' => $modifier_id['Catalog_modifier_group']['name']
                                ];
                            }
                        }
                    }
                }
                
                if (!empty($finalModifierIds)) {
                    foreach ($finalModifierIds as $modifierId => $tdata) {
                        $this->Inventory_linking->create();
                        $this->Inventory_linking->save([
                            'parent_type'=>'Product',
                			'parent_id'=>$productId,
                			'parent_name'=>$form['name'],
                			'component_type'=>'Modifier_group',
                			'component_id'=>$modifierId,
                			'component_name'=>$tdata['name'],
                			'quantity'=>1
                        ]);
                    }
                }
                
                // ✅ ATTRIBUTES
                if (!empty($_POST['custom_attributes'])) {
                    foreach ($_POST['custom_attributes'] as $attr) {
                        $attrName = trim($attr['name'] ?? '');
                        $attrValue = trim($attr['value'] ?? '');
                        if ($attrName && $attrValue) {
                            $this->Catalog_product_attribute->create();
                            $this->Catalog_product_attribute->saveAll([
                                'product_id' => $productId,
                                'name' => $attrName,
                                'value' => $attrValue
                            ]);
                        }
                    }
                }
                
                $this->Flash->success(__('Product has been saved successfully.'));
                return $this->redirect(['action' => 'product_list']);
            } else {
                $this->Flash->error(__('Product could not be saved. Please try again.'));
            }
        }

    }

	public function product_list() {
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		$startDate = date('m/d/Y', strtotime('-12 months'));
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
		}else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }   
        
		
		$users = $this->Catalog_product->query("SELECT * FROM catalog_product where created between '$startdate 00:00:01' and  '$enddate 23:59:59' ORDER BY id desc");
        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        
		$this->set(compact('users'));

	}
	
	public function view_product()
    {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = 'users';
    
        $id = $_REQUEST['id'] ?? null;
        if (empty($id)) {
            $this->Flash->error('Invalid product ID.');
            return $this->redirect(['action' => 'product_list']);
        }
    
        // Get product with related fields
        $product = $this->Catalog_product->find('first', [
            'conditions' => ['Catalog_product.id' => $id],
            'joins' => [
                [
                    'table' => 'pos_printers',
                    'alias' => 'Kds',
                    'type' => 'LEFT',
                    'conditions' => ['Kds.kds = Catalog_product.kds']
                ]
            ],
            'fields' => [
                'Catalog_product.*',
                'Kds.name as kds_name'
            ]
        ]);
        if (empty($product)) {
            $this->Flash->error('Product not found.');
            return $this->redirect(['action' => 'product_list']);
        }
        
        $product = array_merge($product['Catalog_product'], [
            'kds_name'    => $product['Kds']['kds_name'] ?? ''
        ]);
        // Get selected tax IDs for the product
        $productTaxData = $this->Catalog_product_tax->find('list', [
            'fields' => ['Catalog_product_tax.id', 'Catalog_product_tax.tax_id'],
            'conditions' => ['Catalog_product_tax.product_id' => $id]
        ]);
        $selectedTaxIds = array_values($productTaxData);
    
        // Get all tax options (with name and percentage)
        $taxes = $this->Catalog_product_tax->query("
            SELECT cpt.tax_id, CONCAT(ct.name, '(', ct.percentage, '%)') as taxname
            FROM catalog_product_tax cpt
            JOIN catalog_tax ct ON ct.id = cpt.tax_id
            WHERE cpt.product_id = $id
        ");
        
        $modifiers = $this->Inventory_linking->query("
            SELECT *
            FROM inventory_linking
            WHERE parent_id = $id and parent_type='Product' and component_type='Modifier_group'
        ");
        
        $attributes = $this->Catalog_product_attribute->query("
            SELECT name,value
            FROM catalog_product_attribute 
            WHERE catalog_product_attribute.product_id = $id
        ");
        
        // Send to view
        $this->set(compact('product', 'taxes', 'selectedTaxIds','attributes','modifiers'));
    }

	public function view_category()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		$id=$_REQUEST['id'];
		
		$categories = $this->Catalog_category->query("SELECT * FROM catalog_category where id=$id");
        $this->set(compact('categories'));
        
        $subcategories=$this->Catalog_subcategory->query("SELECT * FROM catalog_subcategory where cat_id=$id and status=1");
        $this->set(compact('subcategories')); 
	}
	
	public function view_location()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		$id=$_REQUEST['id'];
		
		$locations = $this->Location->query("SELECT * FROM locations where id=$id");
        $this->set(compact('locations'));
        
	}
	
	public function edit_location()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		
		if ($this->data['User']['id']!='') {
            $id=$this->data['User']['id'];
            $name = $this->data['User']['name'];
            if($name==''){
                $this->Flash->error(__('The Name could not be Blank'));
                return $this->redirect(array('action' => 'edit_location?id='.$id));
            }
            $username = $this->data['User']['username'];
            $password = $this->data['User']['password'];
            $type = $this->data['User']['type'];
            $print_line1 = $this->data['User']['print_line1'];
            $print_line2 = $this->data['User']['print_line2'];
            $print_line3 = $this->data['User']['print_line3'];
            $print_line4 = $this->data['User']['print_line4'];
            $print_line5 = $this->data['User']['print_line5'];
            $print_line6 = $this->data['User']['print_line6'];
            $print_line7 = $this->data['User']['print_line7'];
            $print_line8 = $this->data['User']['print_line8'];
            $print_line9 = $this->data['User']['print_line9'];
            $print_line10 = $this->data['User']['print_line10'];
            $footer_msg = $this->data['User']['footer_msg'];
            $currency_symbol = $this->data['User']['currency_symbol'];
            
            if($password!=''){
                $password = AuthComponent::password($password);
                $this->Location->query("UPDATE locations SET password='$password',sync = 0 WHERE id =". $id);
            }
            $this->Location->query("UPDATE locations SET username ='$username',type='$type',name ='$name',print_line1='$print_line1',print_line2='$print_line2',print_line3='$print_line3',print_line4='$print_line4',print_line5='$print_line5',print_line6='$print_line6',print_line7='$print_line7',print_line8='$print_line8',print_line9='$print_line9',print_line10='$print_line10',footer_msg='$footer_msg',currency_symbol='$currency_symbol',sync = 0 WHERE id =". $id);
            
            $this->Kds_user->query("UPDATE kds_users SET location_name ='$name' WHERE location_id =". $id);
            $this->Kds_users_station_mapping->query("UPDATE kds_users_station_mapping SET station_store_name ='$name' WHERE station_store_id =". $id);
            $this->Pos_printer->query("UPDATE pos_printers SET store_name ='$name' WHERE store_id =". $id);
            $this->User_location->query("UPDATE user_locations SET location_name ='$name' WHERE status=1 and location_id =". $id);
            $this->Inventory_vendor_service_area->query("UPDATE inventory_vendor_service_areas SET area_name ='$name' WHERE is_deleted=0 and area_id =". $id);
            $this->Catalog_category_branches->query("UPDATE catalog_category_branches SET location_name ='$name' WHERE location_id =". $id);
            $this->Catalog_product_branches->query("UPDATE catalog_product_branches SET location_name ='$name' WHERE location_id =". $id);
            $this->Order_table->query("UPDATE order_tables SET location_name ='$name' WHERE location_id =". $id);
            $this->Order_waiter->query("UPDATE order_waiters SET location_name ='$name' WHERE location_id =". $id);
            
            $this->Flash->success(__('Location has been Updated.'));
            return $this->redirect(array('action' => 'location_list'));
		}else{
		    $id=$_REQUEST['id'];
		
		    $locations = $this->Location->query("SELECT * FROM locations where id=$id");
            $this->set(compact('locations'));
		}
		
    }
	
	public function edit_product()
    {
        if (!$this->Session->check('Auth.User.id')) {
            $this->redirect(array('controller' => 'dashboard', 'action' => 'login'));
        }
    
        $this->layout = "users";
        $id = $_REQUEST['id'];
    
        // Fetch the selected product's details
        $products = $this->Catalog_product->query("SELECT * FROM catalog_product WHERE id = $id");
        $categories = $this->Catalog_category->find('all', array('conditions' => array('status' => 1), 'order' => array('name' => 'asc')));
    
        $options = [];
        if (!empty($products[0]['catalog_product']['subcat_id'])) {
            $selectedcatId = $products[0]['catalog_product']['subcat_id'];
            $selectedType = 'sub';
        } else {
            $selectedcatId = $products[0]['catalog_product']['cat_id'];
            $selectedType = 'cat';
        }
        
        foreach ($categories as $category) {
            $cat_id = $category['Catalog_category']['id'];
            $cat_name = $category['Catalog_category']['name'];
    
            $subcategories = $this->Catalog_subcategory->find('all', array(
                'conditions' => array('cat_id' => $cat_id, 'status' => 1),
                'order' => array('name' => 'asc')
            ));
    
            if (!empty($subcategories)) {
                $options[$cat_name] = [];
                foreach ($subcategories as $subcategory) {
                    $subcat_id = $subcategory['Catalog_subcategory']['id'];
                    $subcat_name = $subcategory['Catalog_subcategory']['name'];
                    if ($subcat_id == $selectedcatId  && $selectedType == 'sub') {
                        $selectedcategory = $subcategory['Catalog_subcategory'];
                        $selectedcategory['_type'] = 'sub';
                    }
                    $options[$cat_name]["sub_$subcat_id"] = $subcat_name;
                    
                }
            } else {
                if ($cat_id == $selectedcatId  && $selectedType == 'cat') {
                    $selectedcategory = $category['Catalog_category'];
                    $selectedcategory['_type'] = 'cat';
                }
                $options["cat_$cat_id"] = $cat_name;
            }
        }
    
        if (!empty($selectedcategory)) {
            $key_prefix = ($selectedcategory['_type'] == 'sub') ? 'sub_' : 'cat_';
            $options = array($key_prefix . $selectedcategory['id'] => $selectedcategory['name']) + $options;
        }
    
        $taxes = $this->Catalog_tax->find('all', array('conditions' => array('status' => 1)));
        $units = $this->Catalog_unit->find('all', array('conditions' => array('status' => 1)));
        $kdss = $this->Pos_printer->find('all', array('conditions' => array('status' => 1)));
        $locations=$this->Location->find('all',array('conditions'=>array('status'=>1)));
	    $this->set(compact('locations'));
		
        $this->set(compact('categories', 'subcategories', 'taxes', 'units', 'options', 'selectedcatId', 'kdss'));
        $this->set(compact('products'));
    
        $product_taxes = $this->Catalog_product_tax->find('all', array('conditions' => array('product_id' => $id), 'order' => array('id' => 'desc')));
        $this->set(compact('product_taxes'));
    
        $attributes = $this->Catalog_product_attribute->find('all', [
            'conditions' => ['product_id' => $id],
            'order' => ['id' => 'desc']
        ]);
        
        $customAttributes = array_map(function($attr) {
            return [
                'name' => $attr['Catalog_product_attribute']['name'],
                'value' => $attr['Catalog_product_attribute']['value']
            ];
        }, $attributes);
        $this->set(compact('customAttributes'));

        
        if (!empty($this->data['User']['id'])) {
            $form = $this->data['User'];
            $id = $form['id'];
            $name = trim($form['name']);
    
            if ($name == '') {
                $this->Flash->error(__('The Name could not be blank.'));
                return $this->redirect(['action' => 'edit_product', '?' => ['id' => $id]]);
            }
            
            // CATEGORY
            $category_id = null;
            $category_name = '';
            $subcategory_id = '';
            $subcategory_name = '';
            
            $categoryInput = $form['category'] ?? '';
            
            if (strpos($categoryInput, 'cat_') === 0) {
                $category_id = (int) str_replace('cat_', '', $categoryInput);
                $catData = $this->Catalog_category->findById($category_id);
                if ($catData) {
                    $category_name = $catData['Catalog_category']['name'];
                }
            }elseif (strpos($categoryInput, 'sub_') === 0) {
                $subcategory_id = (int) str_replace('sub_', '', $categoryInput);
                $subcatData = $this->Catalog_subcategory->findById($subcategory_id);
                if ($subcatData) {
                    $subcategory_name = $subcatData['Catalog_subcategory']['name'];
                    $category_id = $subcatData['Catalog_subcategory']['cat_id'];
                    $category_name = $this->Catalog_category->field('name', ['id' => $category_id]);
                }
            }else {
                // Treat as new category name
                $newcat = trim($categoryInput);
                $this->Catalog_category->create();
                if ($this->Catalog_category->save(['name' => $newcat])) {
                    $category_id = $this->Catalog_category->id;
                    $category_name = $newcat;
                } else {
                    $this->Flash->error(__('New category could not be saved. Please try again.'));
                    return;
                }
            }
            
            // if (is_numeric($categoryInput)) {
            //     $category_id = (int)$categoryInput;
            //     $catData = $this->Catalog_category->findById($category_id);
            //     $category_name = $catData['Catalog_category']['name'] ?? '';
            // } else {
            //     $newcat = trim($categoryInput);
            //     $this->Catalog_category->create();
            //     if ($this->Catalog_category->save(['name' => $newcat])) {
            //         $category_id = $this->Catalog_category->id;
            //         $category_name = $newcat;
            //     } else {
            //         $this->Flash->error(__('New category could not be saved.'));
            //         return;
            //     }
            // }
            
            // UNIT
            $unit_id = null;
            $unit_name = '';
            
            $unitInput = $form['unit'] ?? '';
            
            if (is_numeric($unitInput)) {
                $unit_id = (int)$unitInput;
                $unitData = $this->Catalog_unit->findById($unit_id);
                $unit_name = $unitData['Catalog_unit']['name'] ?? '';
            } else {
                $newunit = trim($unitInput);
                $this->Catalog_unit->create();
                if ($this->Catalog_unit->save(['name' => $newunit])) {
                    $unit_id = $this->Catalog_unit->id;
                    $unit_name = $newunit;
                } else {
                    $this->Flash->error(__('New unit could not be saved.'));
                    return;
                }
            }
            
            // KDS
            $kds_id = null;
            $kds_name = '';
            $kds_input = $form['kds'] ?? '';
            $customKds = $_POST['custom_kds'] ?? [];
            
            if (is_numeric($kds_input)) {
                $kds_id = (int)$kds_input;
                $existing = $this->Pos_printer->findById($kds_id);
                $kds_name = $existing['Pos_printer']['name'] ?? '';
            } elseif (!empty($customKds)) {
                $firstKds = reset($customKds);
                $locationdetail = $this->Location->findById($firstKds['location']);
                $locationname = $locationdetail['Location']['name'] ?? '';
            
                $kdsData = [
                    'name' => $firstKds['name'],
                    'ip' => $firstKds['ip'],
                    'store_id' => $firstKds['location'],
                    'store_name' => $locationname,
                ];
            
                $this->Pos_printer->create();
                if ($this->Pos_printer->save($kdsData)) {
                    $kds_id = $this->Pos_printer->id;
                    $kds_name = $kdsData['name'];
                    $this->Pos_printer->id = $kds_id;
                    $this->Pos_printer->saveField('kds', $kds_id);
                } else {
                    $this->Flash->error(__('New KDS could not be saved.'));
                    return;
                }
            }
            
            // IMAGE
            $filename = '';
            if (!empty($form['image']['name'])) {
                $uploadPath = WWW_ROOT . 'uploads' . DS . 'product_images' . DS;
                $filename = time() . '_' . preg_replace('/[^A-Za-z0-9_\-\.]/', '_', $form['image']['name']);
                $uploadFile = $uploadPath . $filename;
                if (!move_uploaded_file($form['image']['tmp_name'], $uploadFile)) {
                    $filename = '';
                }
            }
            
            $productData = [
                'id' => $id,
                'name' => $name,
                'description' => $form['description'],
                'dish_type' => $form['dish_type'],
                'food_type' => $form['food_type'],
                'package' => $form['package'],
                'sort_order' => $form['sort_order'],
                'recommended' => $form['recommended'],
                'variation' => $form['variation'],
                'price' => $form['price'],
                'preparation_time' => $form['preparation'] ?? 0,
                'serve_time' => $form['serve_time'] ?? 0,
                'moq' => $form['moq'] ?? 0,
                'allergy_tags' => $form['allergy_tags'],
                'weight' => $form['weight'],
                'serves_people' => $form['serves_people'],
                'unit' => $unit_id,
                'unit_name' => $unit_name,
                'cat_id' => $category_id,
                'cat_name' => $category_name,
                'subcat_id' => $subcategory_id,
                'subcat_name' => $subcategory_name,
                'kds' => $kds_id,
                'sync' => 0
            ];
            
            if ($filename != '') {
                $productData['image'] = $filename;
            }
            
            $this->Catalog_product->save($productData);
            
            $package = $form['package'];
            if ($package == 0) {
                // Deactivate all package mappings for this product
                $this->Catalog_package->updateAll(
                    ['status' => 0],
                    ['main_product_id' => $id]
                );
            }
            
            // ✅ TAXES (dynamic + static)
            
            $this->Catalog_product_tax->query("DELETE FROM catalog_product_tax WHERE product_id =" . $id);
            $finalTaxIds = [];
            if (!empty($_POST['User']['custom_taxes'])) {
                foreach ($_POST['User']['custom_taxes'] as $customKey => $taxData) {
                    $name = trim($taxData['name'] ?? '');
                    $percentage = floatval($taxData['percentage'] ?? 0);
                    $isChecked = !empty($_POST['User']['tax_ids'][$customKey]);
                    
                    if ($name && $percentage && $isChecked) {
                        $existing = $this->Catalog_tax->find('first', ['conditions' => ['name' => $name, 'percentage' => $percentage]]);
                        $taxId = $existing['Catalog_tax']['id'] ?? null;
                        
                        if (!$taxId) {
                            $this->Catalog_tax->create();
                            if ($this->Catalog_tax->save(['name' => $name, 'percentage' => $percentage])) {
                                $taxId = $this->Catalog_tax->id;
                            }
                        }
    
                        if ($taxId) {
                            $finalTaxIds[$taxId] = ['name' => $name, 'percentage' => $percentage];
                        }
                    }
                }
            }
                    
            if (!empty($_POST['data']['tax_ids'])) {
                foreach ($_POST['data']['tax_ids'] as $taxId => $selected) {
                    if (is_numeric($taxId) && $selected) {
                        $tax = $this->Catalog_tax->findById($taxId);
                        if ($tax) {
                            $finalTaxIds[$taxId] = [
                                'name' => $tax['Catalog_tax']['name'],
                                'percentage' => $tax['Catalog_tax']['percentage']
                            ];
                        }
                    }
                }
            }
            foreach ($finalTaxIds as $taxId => $tdata) {
                $this->Catalog_product_tax->create();
                $this->Catalog_product_tax->save([
                    'product_id' => $id,
                    'product_name' => $form['name'],
                    'tax_id' => $taxId,
                    'tax_name' => $tdata['name'],
                    'tax_percentage' => $tdata['percentage']
                ]);
            }
            
            // ✅ ATTRIBUTES
            
            $this->Catalog_product_attribute->query("DELETE FROM catalog_product_attribute WHERE product_id =" . $id);
            
            if (!empty($_POST['custom_attributes'])) {
                foreach ($_POST['custom_attributes'] as $attr) {
                    $attrName = trim($attr['name'] ?? '');
                    $attrValue = trim($attr['value'] ?? '');
                    if ($attrName && $attrValue) {
                        $this->Catalog_product_attribute->create();
                        $this->Catalog_product_attribute->saveAll([
                            'product_id' => $id,
                            'name' => $attrName,
                            'value' => $attrValue
                        ]);
                    }
                }
            }
            
            $this->Flash->success(__('Product has been Updated.'));
            return $this->redirect(array('action' => 'product_list'));
        }
    }


	public function view_subcategory()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		$id=$_REQUEST['id'];
		
		$categories=$this->Catalog_subcategory->query("SELECT *,(SELECT name FROM `catalog_category` WHERE id=catalog_subcategory.cat_id) as catname FROM catalog_subcategory where id=$id");
        $this->set(compact('categories')); 
	}
	
	public function edit_subcategory()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		$id=$_REQUEST['id'];
		
		$subcategories=$this->Catalog_subcategory->query("SELECT *,(SELECT name FROM `catalog_category` WHERE id=catalog_subcategory.cat_id) as catname FROM catalog_subcategory where id=$id");
        $this->set(compact('subcategories')); 
        
        $categories=$this->Catalog_category->find('all',array('conditions'=>array('status'=>1),'order' => array(
                'name' => 'asc' // Order by the 'created' field in ascending order
            )));
	    $this->set(compact('categories'));
	    
	    if ($this->request->is(array('post', 'put'))) {
            // print_r($this->data);exit;
            $id = $this->data['User']['id'];
            $name = $this->data['User']['name'];
            if($name==''){
                $this->Flash->error(__('The Name could not be Blank'));
                return $this->redirect(array('action' => 'edit_subcategory?id='.$id));
            }
            
            $image=$this->data['User']['image'];
            if (!empty($image['name'])) {
                $uploadPath = WWW_ROOT . 'uploads' . DS . 'category_images' . DS;
                $file=basename(time().$image['name']);
                $file = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', $file);
                $uploadFile = $uploadPath . $file;
                
                if (move_uploaded_file($image['tmp_name'], $uploadFile)) {
                    $filename=$file;
                }else{
                    $filename='';
                }
                $this->Catalog_subcategory->query("UPDATE `catalog_subcategory` SET image='$filename',sync = 0 WHERE id=$id");
            }
            $category=$this->data['User']['category'];
        
            $categoryid = $this->Catalog_subcategory->query("SELECT cat_id FROM catalog_subcategory where id=$id");
            $cat_id=$categoryid['0']['catalog_subcategory']['cat_id'];
        
            $this->Catalog_subcategory->query("UPDATE `catalog_subcategory` SET name='$name',cat_id=$category,sync = 0 WHERE id=$id");
            $this->Catalog_category->query("UPDATE `catalog_category` SET is_subcategory=1,sync = 0 WHERE id=$category");
            
            $subcategorychk=$this->Catalog_subcategory->query("SELECT * FROM catalog_subcategory where cat_id=$cat_id and status=1");
            if($subcategorychk){
                $this->Catalog_category->query("UPDATE catalog_category SET is_subcategory=1,sync = 0 WHERE id=$cat_id");
            }else{
                $this->Catalog_category->query("UPDATE catalog_category SET is_subcategory=0,sync = 0 WHERE id=$cat_id");
            }
            
            $this->Flash->success(__('Sub Category has been Updated.'));
			return $this->redirect(array('action' => 'subcategory_list'));
		
		}
	
	}
	
	public function create_sku()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		$units=$this->Catalog_unit->find('all',array('conditions'=>array('status'=>1)));
	    
	    $taxes=$this->Inventory_tax->find('all',array('conditions'=>array('status'=>1)));
	    
	    $categorys = $this->Inventory_category->find('all', ['conditions' => ['status' => 1]]);
        
        $options = [];
        foreach ($categorys as $category) {
            $cat_id = $category['Inventory_category']['id'];
            $cat_name = $category['Inventory_category']['name'];
        
            $subcategorys = $this->Inventory_subcategory->find('all', [
                'conditions' => ['cat_id' => $cat_id, 'status' => 1]
            ]);
        
            if (!empty($subcategorys)) {
                foreach ($subcategorys as $sub) {
                    $sub_id = $sub['Inventory_subcategory']['id'];
                    $sub_name = $sub['Inventory_subcategory']['name'];
                    $options[$cat_name]["sub_$sub_id"] = $sub_name;
                }
            } else {
                $options["cat_$cat_id"] = $cat_name;
            }
        }
        $this->set(compact('categorys', 'subcategorys', 'units', 'taxes', 'options'));

		if ($this->request->is(array('post', 'put'))) {
            
            $name = $this->data['User']['name'];
            if($name==''){
                $this->Flash->error(__('The Name could not be Blank'));
                return $this->redirect(array('action' => 'create_sku'));
            }
            
            $name = $this->data['User']['name'];
            $brand = $this->data['User']['brand'];
            $unit = $this->data['User']['unit'];
            $price = $this->data['User']['price'];
            $remarks = $this->data['User']['remarks'];
            $conunit = $this->data['User']['conunit'];
            $factor = $this->data['User']['factor'];
            $conprice = $this->data['User']['conprice'];
            
            // CATEGORY
            $category_id = null;
            $category_name = '';
            $subcategory_id = '';
            $subcategory_name = '';
            
            $categoryInput = $this->data['User']['category'] ?? '';
            
            if (strpos($categoryInput, 'cat_') === 0) {
                $category_id = (int) str_replace('cat_', '', $categoryInput);
                $catData = $this->Inventory_category->findById($category_id);
                if ($catData) {
                    $category_name = $catData['Inventory_category']['name'];
                }
                
            } elseif (strpos($categoryInput, 'sub_') === 0) {

                $subcategory_id = (int) str_replace('sub_', '', $categoryInput);
                $subcatData = $this->Inventory_subcategory->findById($subcategory_id);
                if ($subcatData) {
                    $subcategory_name = $subcatData['Inventory_subcategory']['name'];
                    $category_id = $subcatData['Inventory_subcategory']['cat_id'];
                    $category_name = $this->Inventory_category->field('name', ['id' => $category_id]);
                }
            } else {
                // Treat as new category name
                $newcat = trim($categoryInput);
                $this->Inventory_category->create();
                if ($this->Inventory_category->save(['name' => $newcat])) {
                    $category_id = $this->Inventory_category->id;
                    $category_name = $newcat;
                } else {
                    $this->Flash->error(__('New category could not be saved. Please try again.'));
                    return;
                }
            }
            
            $unitname=$this->Catalog_unit->find('first',array('conditions'=>array('id'=>$unit)));
	        $conunitname=$this->Catalog_unit->find('first',array('conditions'=>array('id'=>$conunit)));
	        
	        $data['Inventory_sku']=array(
    			'name'=>$name,
    			'brand'=>$brand,
    			'cat_id' => $category_id,
                'cat_name' => $category_name,
                'subcat_id' => $subcategory_id,
                'subcat_name' => $subcategory_name,
                'unit'=>$unit,
    			'unit_name'=>$unitname['Catalog_unit']['name'],
    			'consumption_unit_id'=>$conunit,
    			'consumption_unit_name'=>$conunitname['Catalog_unit']['name'],
    			'consumption_factor'=>$factor,
    			'consumption_unit_price'=>$conprice,
    			'price'=>$price,
    			'remarks'=>$remarks,
    			'moq' => $this->data['User']['moq'] ?? 0
            );
    	    
    	    if($this->Inventory_sku->saveAll($data['Inventory_sku']))
    		{
    		    $lastInsertedID = $this->Inventory_sku->id;
    		    
    		    $taxes=$this->Inventory_tax->find('all',array('conditions'=>array('status'=>1)));
    	        foreach ($taxes as $taxess) {
                    $taxID = $taxess['Inventory_tax']['id'];
                    if (!empty($this->request->data['User']['tax_' . $taxID])) {
                        $selectedTaxes[] = $this->request->data['User']['tax_' . $taxID];
                        $taxdetail=$this->Inventory_tax->find('first',array('conditions'=>array('id'=>$taxID)));
            	        if($taxdetail){
            	            $data['Inventory_sku_tax']=array(
                    			'product_id'=>$lastInsertedID,
                    			'product_name'=>$name,
                    			'tax_id'=>$taxID,
                    			'tax_name'=>$taxdetail['Inventory_tax']['name'],
                    			'tax_percentage'=>$taxdetail['Inventory_tax']['percentage']
                    		);
                    	    
                    	    if($this->Inventory_sku_tax->saveAll($data['Inventory_sku_tax']))
                    		{
                    		    
                    		}else{
                    		    $this->Flash->error(__('SKU tax could not be saved. Please, try again.'));
                    		}
            	        }
                    }
                }
                
                if(isset($_POST['custom_tax_name'])){
                
                    $taxnames=$_POST['custom_tax_name'];
        	        $taxvalues=$_POST['custom_tax_value'];
        	           
                    for ($i = 0; $i < count($taxnames); $i++) {
                        $taxname = $taxnames[$i];
                        $percentage = $taxvalues[$i];
                        
                        $newtaxdetail=$this->Inventory_tax->find('first',array('conditions'=>array('name'=>$taxname,'percentage'=>$percentage)));
            	        if(empty($newtaxdetail)){
            	            $data['Inventory_tax']=array(
                    			'name'=>$taxname,
                    			'percentage'=>$percentage
                    	    );
                    	    
                    	    if($this->Inventory_tax->saveAll($data['Inventory_tax']))
                    		{
                    		    $taxlastInsertedID = $this->Inventory_tax->id;
            		    
                    		} else {
                				$this->Flash->error(__('New Tax could not be saved. Please, try again.'));
                			}
            	        }
            	        
            	        $data['Inventory_sku_tax']=array(
                			'product_id'=>$lastInsertedID,
                			'product_name'=>$name,
                			'tax_id'=>$taxlastInsertedID,
                			'tax_name'=>$taxname,
                			'tax_percentage'=>$percentage
                		);
                	    
                	    if($this->Inventory_sku_tax->saveAll($data['Inventory_sku_tax']))
                		{
                		    
                		}else{
                		    $this->Flash->error(__('Sku New tax could not be saved. Please, try again.'));
                		}
                        
                    }
                }
                $this->Flash->success(__('Sku has been saved.'));
				return $this->redirect(array('action' => 'sku_list'));
			} else {
				$this->Flash->error(__('Sku could not be saved. Please, try again.'));
			}
		}
		
	}
	
	public function sku_list()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		$startDate = date('m/d/Y', strtotime('-12 months'));
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
		}else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }   
        
		
		$users = $this->Inventory_sku->query("SELECT * FROM inventory_skus where created between '$startdate 00:00:01' and  '$enddate 23:59:59' ORDER BY id desc");
        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        
		$this->set(compact('users'));

	}
	
	public function edit_sku()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
	    
	    $id=$_REQUEST['id'];
    
        $products = $this->Inventory_sku->query("SELECT * FROM inventory_skus where id=$id");
        $this->set(compact('products'));
        
        $product_taxes=$this->Inventory_sku_tax->find('all',array('conditions'=>array('product_id'=>$id),'order'=>array('id'=>'desc')));
        $this->set(compact('product_taxes'));
		
	    $categories = $this->Inventory_category->find('all', array('conditions' => array('status' => 1), 'order' => array('name' => 'asc')));
        
		$units=$this->Catalog_unit->find('all',array('conditions'=>array('status'=>1)));
		
		$unit=$products[0]['inventory_skus']['unit'];
		$conunits=$this->Catalog_unit_mapping->find('all',array('conditions'=>array('status'=>1,'unit_id'=>$unit)));
	    
	    $taxes=$this->Inventory_tax->find('all',array('conditions'=>array('status'=>1)));
	    $options = [];
	    if (!empty($products[0]['inventory_skus']['subcat_id'])) {
            $selectedcatId = $products[0]['inventory_skus']['subcat_id'];
            $selectedType = 'sub';
        } else {
            $selectedcatId = $products[0]['inventory_skus']['cat_id'];
            $selectedType = 'cat';
        }
        
        $selectedcategory = null;
        foreach ($categories as $category) {
            $cat_id = $category['Inventory_category']['id'];
            $cat_name = $category['Inventory_category']['name'];
    
            $subcategories = $this->Inventory_subcategory->find('all', array(
                'conditions' => array('cat_id' => $cat_id, 'status' => 1),
                'order' => array('name' => 'asc')
            ));
            if (!empty($subcategories)) {
                $options[$cat_name] = [];
                foreach ($subcategories as $subcategory) {
                    $subcat_id = $subcategory['Inventory_subcategory']['id'];
                    $subcat_name = $subcategory['Inventory_subcategory']['name'];
                    if ($subcat_id == $selectedcatId  && $selectedType == 'sub') {
                        $selectedcategory = $subcategory['Inventory_subcategory'];
                        $selectedcategory['_type'] = 'sub';
                    }
                    $options[$cat_name]["sub_$subcat_id"] = $subcat_name;
                    
                }
            } else {
                if ($cat_id == $selectedcatId && $selectedType == 'cat') {
                    $selectedcategory = $category['Inventory_category'];
                    $selectedcategory['_type'] = 'cat';
                }
                $options["cat_$cat_id"] = $cat_name;
            }
        }
        
        if (!empty($selectedcategory)) {
            $key_prefix = ($selectedcategory['_type'] == 'sub') ? 'sub_' : 'cat_';
            $options = array($key_prefix . $selectedcategory['id'] => $selectedcategory['name']) + $options;
        }
// print_r($options);exit;
        $this->set(compact('categories', 'subcategories', 'taxes', 'units', 'options', 'selectedcatId','conunits'));
        

	    
		if ($this->data['User']['id']!='') {
		    
		    $id=$this->data['User']['id'];
            $name = $this->data['User']['name'];
            if($name==''){
                $this->Flash->error(__('The Name could not be Blank'));
                return $this->redirect(array('action' => 'edit_sku?id='.$id));
            }
            $brand = $this->data['User']['brand'];
            $unit = $this->data['User']['unit'];
            $price = $this->data['User']['price'];
            $remarks = $this->data['User']['remarks'];
            
            $conunit = $this->data['User']['conunit'];
            $factor = $this->data['User']['factor'];
            $conprice = $this->data['User']['conprice'];
            
            // CATEGORY
            $category_id = null;
            $category_name = '';
            $subcategory_id = '';
            $subcategory_name = '';
            
            $categoryInput = $this->data['User']['category'] ?? '';
            if (strpos($categoryInput, 'cat_') === 0) {
                $category_id = (int) str_replace('cat_', '', $categoryInput);
                $catData = $this->Inventory_category->findById($category_id);
                if ($catData) {
                    $category_name = $catData['Inventory_category']['name'];
                }
            }elseif (strpos($categoryInput, 'sub_') === 0) {
                $subcategory_id = (int) str_replace('sub_', '', $categoryInput);
                $subcatData = $this->Inventory_subcategory->findById($subcategory_id);
                if ($subcatData) {
                    $subcategory_name = $subcatData['Inventory_subcategory']['name'];
                    $category_id = $subcatData['Inventory_subcategory']['cat_id'];
                    $category_name = $this->Inventory_category->field('name', ['id' => $category_id]);
                }
            }else {
                // Treat as new category name
                $newcat = trim($categoryInput);
                $this->Inventory_category->create();
                if ($this->Inventory_category->save(['name' => $newcat])) {
                    $category_id = $this->Inventory_category->id;
                    $category_name = $newcat;
                } else {
                    $this->Flash->error(__('New category could not be saved. Please try again.'));
                    return;
                }
            }
            
            $unitname=$this->Catalog_unit->find('first',array('conditions'=>array('id'=>$unit)));
	        $unit_name=$unitname['Catalog_unit']['name'];
	        $moq=$this->data['User']['moq'];
            
            if($conunit){
                $conunitnames=$this->Catalog_unit->find('first',array('conditions'=>array('id'=>$conunit)));
                $conunitname=$conunitnames['Catalog_unit']['name'];
            }else{
                $conunit=0;
                $factor=0;
                $conprice=0;
                $conunitname='';
            }
	        $this->Inventory_sku->query("UPDATE inventory_skus SET consumption_unit_id='$conunit',consumption_unit_name='$conunitname',consumption_factor='$factor',consumption_unit_price='$conprice',moq='$moq', cat_id='$category_id',cat_name='$category_name',subcat_id='$subcategory_id',subcat_name='$subcategory_name',name ='$name',brand='$brand',unit='$unit',unit_name='$unit_name',price='$price',remarks='$remarks',sync = 0 WHERE id =". $id);
            //tax Update
            $this->Inventory_sku_tax->query("DELETE FROM inventory_sku_tax  WHERE product_id =". $id);
            $taxes=$this->Inventory_tax->find('all',array('conditions'=>array('status'=>1)));
	        foreach ($taxes as $taxess) {
                $taxID = $taxess['Inventory_tax']['id'];
                if (!empty($this->request->data['User']['tax_' . $taxID])) {
                    $selectedTaxes[] = $this->request->data['User']['tax_' . $taxID];
                    $taxdetail=$this->Inventory_tax->find('first',array('conditions'=>array('id'=>$taxID)));
        	        if($taxdetail){
        	            $data['Inventory_sku_tax']=array(
                			'product_id'=>$id,
                			'product_name'=>$name,
                			'tax_id'=>$taxID,
                			'tax_name'=>$taxdetail['Inventory_tax']['name'],
                			'tax_percentage'=>$taxdetail['Inventory_tax']['percentage']
                		);
                	    
                	    if($this->Inventory_sku_tax->saveAll($data['Inventory_sku_tax']))
                		{
                		    
                		}else{
                		    $this->Flash->error(__('SKU tax could not be saved. Please, try again.'));
                		}
        	        }
                }
            }
            
            if(isset($_POST['tax_name'])){
                
                $taxnames=$_POST['tax_name'];
    	        $taxvalues=$_POST['tax_value'];
    	           
                for ($i = 0; $i < count($taxnames); $i++) {
                    $taxname = $taxnames[$i];
                    $percentage = $taxvalues[$i];
                    
                    $newtaxdetail=$this->Inventory_tax->find('first',array('conditions'=>array('name'=>$taxname,'percentage'=>$percentage)));
        	        if(empty($newtaxdetail)){
        	            $data['Inventory_tax']=array(
                			'name'=>$taxname,
                			'percentage'=>$percentage
                	    );
                	    
                	    if($this->Inventory_tax->saveAll($data['Inventory_tax']))
                		{
                		    $taxlastInsertedID = $this->Inventory_tax->id;
        		    
                		} else {
            				$this->Flash->error(__('New Tax could not be saved. Please, try again.'));
            			}
        	        }
        	        
        	        $data['Inventory_sku_tax']=array(
            			'product_id'=>$id,
            			'product_name'=>$name,
            			'tax_id'=>$taxlastInsertedID,
            			'tax_name'=>$taxname,
            			'tax_percentage'=>$percentage
            		);
            	    
            	    if($this->Inventory_sku_tax->saveAll($data['Inventory_sku_tax']))
            		{
            		    
            		}else{
            		    $this->Flash->error(__('SKU New tax could not be saved. Please, try again.'));
            		}
                    
                }
            }
            
            $this->Flash->success(__('Sku has been Updated.'));
            return $this->redirect(array('action' => 'sku_list'));
		}
		
    }
	
	public function view_sku()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        $this->layout = "users";
	    $id=$_REQUEST['id'];
		
		$products = $this->Inventory_sku->query("SELECT * FROM inventory_skus where id=$id");
        $this->set(compact('products'));
        
        $taxes=$this->Inventory_sku_tax->query("SELECT CONCAT(tax_name, '(', tax_percentage, '%)') as taxname ,id FROM inventory_sku_tax where product_id=$id");
        $this->set(compact('taxes'));    	        
    }
	
	public function create_vendor()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;

		$locationCondition = ['status' => 1]; // always filter by active locations
        
        if ($userRole !== 'admin') {
            // If $userLocationId is a single ID, make it an array
            $userLocationIds = is_array($userLocationId) ? $userLocationId : [$userLocationId];
            $locationCondition['id'] = $userLocationIds; // CakePHP automatically handles IN
        }

		$areas=$this->Location->find('all',array('conditions'=>$locationCondition));
	    $this->set(compact('areas'));
	
		if ($this->request->is(array('post', 'put'))) {
            
            $name = $this->data['User']['name'];
            if($name==''){
                $this->Flash->error(__('The Name could not be Blank'));
                return $this->redirect(array('action' => 'create_vendor'));
            }
            
            $office_address = $this->data['User']['office_address'];
            $email = $this->data['User']['email'];
            $company = $this->data['User']['company'];
            $gst = $this->data['User']['gst'];
            $bank_ac = $this->data['User']['bank_ac'];
            $bank_name = $this->data['User']['bank_name'];
            $advance_percentage = $this->data['User']['advance_percentage'];
            $mobile = $this->data['User']['mobile'];
            $landline = $this->data['User']['landline'];
            $state = $this->data['User']['state'];
            $pan = $this->data['User']['pan'];
            $tan = $this->data['User']['tan'];
            $ifsc = $this->data['User']['ifsc'];
            $payment_days = $this->data['User']['payment_days'];
            $approval = $this->data['User']['approval'];
            
            $gstfilename='';
	        $gst_image=$this->data['User']['gst_image'];
            if (!empty($gst_image['name'])) {
                $uploadPath = WWW_ROOT . 'uploads' . DS . 'vendor_images' . DS;
                $file=basename(time().$gst_image['name']);
                $file = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', $file);
                $uploadFile = $uploadPath . $file;
                
                if (move_uploaded_file($gst_image['tmp_name'], $uploadFile)) {
                    $gstfilename=$file;
                }
            }
            
            $agreementfilename='';
            $agreement_image=$this->data['User']['agreement_image'];
            if (!empty($agreement_image['name'])) {
                $uploadPath = WWW_ROOT . 'uploads' . DS . 'vendor_images' . DS;
                $file=basename(time().$agreement_image['name']);
                $file = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', $file);
                $uploadFile = $uploadPath . $file;
                
                if (move_uploaded_file($agreement_image['tmp_name'], $uploadFile)) {
                    $agreementfilename=$file;
                }
            }
            
            $panfilename='';
            $pan_image=$this->data['User']['pan_image'];
            if (!empty($pan_image['name'])) {
                $uploadPath = WWW_ROOT . 'uploads' . DS . 'vendor_images' . DS;
                $file=basename(time().$pan_image['name']);
                $file = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', $file);
                $uploadFile = $uploadPath . $file;
                
                if (move_uploaded_file($pan_image['tmp_name'], $uploadFile)) {
                    $panfilename=$file;
                }
            }
            
            $tanfilename='';
            $tan_image=$this->data['User']['tan_image'];
            if (!empty($tan_image['name'])) {
                $uploadPath = WWW_ROOT . 'uploads' . DS . 'vendor_images' . DS;
                $file=basename(time().$tan_image['name']);
                $file = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', $file);
                $uploadFile = $uploadPath . $file;
                
                if (move_uploaded_file($tan_image['tmp_name'], $uploadFile)) {
                    $tanfilename=$file;
                }
            }
            
            
            $data['Inventory_vendor']=array(
    			'name'=>$name,
    			'mobile'=>$mobile,
    			'landline'=>$landline,
    			'email'=>$email,
    			'office_address'=>$office_address,
    			'state'=>$state,
    			'company'=>$company,
    			'pan'=>$pan,
    			'gst'=>$gst,
    			'tan'=>$tan,
    			'bank_ac'=>$bank_ac,
    			'ifsc'=>$ifsc,
    			'bank_name'=>$bank_name,
    			'advance_percentage'=>$advance_percentage,
    			'payment_days'=>$payment_days,
    			'pan_image'=>$panfilename,
    			'gst_image'=>$gstfilename,
    			'tan_image'=>$tanfilename,
    			'agreement_image'=>$agreementfilename,
    			'po_approval_required'=>$approval
    		);
    	    
    	    if($this->Inventory_vendor->saveAll($data['Inventory_vendor']))
    		{
    		    $lastInsertedID = $this->Inventory_vendor->id;
    		    
    		    $areas=$this->Location->find('all',array('conditions'=>array('status'=>1)));
	            foreach ($areas as $area) {
                    $ID = $area['Location']['id'];
                    if (!empty($this->request->data['User']['area_' . $ID])) {
                        $selectedarea[] = $this->request->data['User']['area_' . $ID];
                        $areadetail=$this->Location->find('first',array('conditions'=>array('id'=>$ID)));
            	        if($areadetail){
            	            $data['Inventory_vendor_service_area']=array(
                    			'vendor_id'=>$lastInsertedID,
                    			'area_id'=>$ID,
                    			'area_name'=>$areadetail['Location']['name']
                    		);
                    	    
                    	    if($this->Inventory_vendor_service_area->saveAll($data['Inventory_vendor_service_area']))
                    		{
                    		    
                    		}else{
                    		    $this->Flash->error(__('area could not be saved. Please, try again.'));
                    		}
            	        }
                    }
                }
                
                $this->Flash->success(__('Vendor has been saved.'));
				return $this->redirect(array('action' => 'map_vendor_with_sku?id='.$lastInsertedID));
			} else {
				$this->Flash->error(__('Sku could not be saved. Please, try again.'));
			}
		}
		
	}
	
	public function vendor_list()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		
        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;


		$startDate = date('m/d/Y', strtotime('-12 months'));
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
		}else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }   
        
		$locationCondition = '';
        if ($userRole !== 'admin') {
            $locationCondition = "and id IN (SELECT vendor_id FROM `inventory_vendor_service_areas` WHERE is_deleted=0 and area_id IN (" . $userLocationId . "))";
        }
        
		$users = $this->Inventory_vendor->query("SELECT * FROM inventory_vendors where status=1 and created between '$startdate 00:00:01' and  '$enddate 23:59:59' $locationCondition ORDER BY id desc");
        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        
		$this->set(compact('users'));

	}
	
	public function edit_vendor()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
	    
	    $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;

        $locationCondition = ['status' => 1]; // always filter by active locations
        
        if ($userRole !== 'admin') {
            // If $userLocationId is a single ID, make it an array
            $userLocationIds = is_array($userLocationId) ? $userLocationId : [$userLocationId];
            $locationCondition['id'] = $userLocationIds; // CakePHP automatically handles IN
        }

		$areas=$this->Location->find('all',array('conditions'=>$locationCondition));
	    $this->set(compact('areas'));
	    $id=$_REQUEST['id'];
    
        $products = $this->Inventory_vendor->query("SELECT * FROM inventory_vendors where id=$id");
        $this->set(compact('products'));
        
        $vendor_areas=$this->Inventory_vendor_service_area->find('all',array('conditions'=>array('vendor_id'=>$id),'order'=>array('id'=>'desc')));
        $this->set(compact('vendor_areas'));
        
		if ($this->data['User']['id']!='') {
		    
		    $id=$this->data['User']['id'];
            $name = $this->data['User']['name'];
            if($name==''){
                $this->Flash->error(__('The Name could not be Blank'));
                return $this->redirect(array('action' => 'edit_vendor?id='.$id));
            }
            $email = $this->data['User']['email'];
            $office_address = $this->data['User']['office_address'];
            $company = $this->data['User']['company'];
            $gst = $this->data['User']['gst'];
            $bank_ac = $this->data['User']['bank_ac'];
            $bank_name = $this->data['User']['bank_name'];
            $advance_percentage = $this->data['User']['advance_percentage'];
            $mobile = $this->data['User']['mobile'];
            $landline = $this->data['User']['landline'];
            $state = $this->data['User']['state'];
            $pan = $this->data['User']['pan'];
            $tan = $this->data['User']['tan'];
            $ifsc = $this->data['User']['ifsc'];
            $payment_days = $this->data['User']['payment_days'];
            $approval=$this->data['User']['approval'];
            
            $gst_image=$this->data['User']['gst_image'];
            if (!empty($gst_image['name'])) {
                $uploadPath = WWW_ROOT . 'uploads' . DS . 'vendor_images' . DS;
                $file=basename(time().$gst_image['name']);
                $file = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', $file);
                $uploadFile = $uploadPath . $file;
                
                if (move_uploaded_file($gst_image['tmp_name'], $uploadFile)) {
                    $gstfilename=$file;
                    $this->Inventory_vendor->query("UPDATE inventory_vendors SET gst_image='$gstfilename',sync = 0 WHERE id =". $id);
                }
            }
            
            $agreement_image=$this->data['User']['agreement_image'];
            if (!empty($agreement_image['name'])) {
                $uploadPath = WWW_ROOT . 'uploads' . DS . 'vendor_images' . DS;
                $file=basename(time().$agreement_image['name']);
                $file = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', $file);
                $uploadFile = $uploadPath . $file;
                
                if (move_uploaded_file($agreement_image['tmp_name'], $uploadFile)) {
                    $agreementfilename=$file;
                    $this->Inventory_vendor->query("UPDATE inventory_vendors SET agreement_image='$agreementfilename',sync = 0 WHERE id =". $id);
                }
            }
            
            $pan_image=$this->data['User']['pan_image'];
            if (!empty($pan_image['name'])) {
                $uploadPath = WWW_ROOT . 'uploads' . DS . 'vendor_images' . DS;
                $file=basename(time().$pan_image['name']);
                $file = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', $file);
                $uploadFile = $uploadPath . $file;
                
                if (move_uploaded_file($pan_image['tmp_name'], $uploadFile)) {
                    $panfilename=$file;
                    $this->Inventory_vendor->query("UPDATE inventory_vendors SET pan_image='$panfilename',sync = 0 WHERE id =". $id);
                }
            }
            
            $tan_image=$this->data['User']['tan_image'];
            if (!empty($tan_image['name'])) {
                $uploadPath = WWW_ROOT . 'uploads' . DS . 'vendor_images' . DS;
                $file=basename(time().$tan_image['name']);
                $file = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', $file);
                $uploadFile = $uploadPath . $file;
                
                if (move_uploaded_file($tan_image['tmp_name'], $uploadFile)) {
                    $tanfilename=$file;
                    $this->Inventory_vendor->query("UPDATE inventory_vendors SET tan_image='$tanfilename',sync = 0 WHERE id =". $id);
                }
            }
            
            $this->Inventory_vendor->query("UPDATE inventory_vendors SET po_approval_required='$approval',name ='$name',mobile='$mobile',landline='$landline',email='$email',office_address='$office_address',state='$state',company='$company',pan='$pan',gst='$gst',tan='$tan',bank_ac='$bank_ac',ifsc='$ifsc',bank_name='$bank_name',advance_percentage='$advance_percentage',payment_days='$payment_days',sync = 0 WHERE id =". $id);
            
            $prevareas=$this->Inventory_vendor_service_area->query("DELETE FROM inventory_vendor_service_areas where vendor_id=$id");
            $areas=$this->Location->find('all',array('conditions'=>array('status'=>1)));
            foreach ($areas as $area) {
                $ID = $area['Location']['id'];
                if (!empty($this->request->data['User']['area_' . $ID])) {
                    $selectedarea[] = $this->request->data['User']['area_' . $ID];
                    $areadetail=$this->Location->find('first',array('conditions'=>array('id'=>$ID)));
        	        if($areadetail){
        	            $data['Inventory_vendor_service_area']=array(
                			'vendor_id'=>$id,
                			'area_id'=>$ID,
                			'area_name'=>$areadetail['Location']['name']
                		);
                	    
                	    if($this->Inventory_vendor_service_area->saveAll($data['Inventory_vendor_service_area']))
                		{
                		    
                		}else{
                		    $this->Flash->error(__('area could not be saved. Please, try again.'));
                		}
        	        }
                }
            }
            
            $this->Flash->success(__('Vendor has been Updated.'));
            return $this->redirect(array('action' => 'vendor_list'));
		}
		
    }
	
	public function view_vendor()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        $this->layout = "users";
	    $id=$_REQUEST['id'];
		
		$products = $this->Inventory_vendor->query("SELECT * FROM inventory_vendors where id=$id");
        $this->set(compact('products'));
        
        $areas=$this->Inventory_vendor_service_area->query("SELECT area_name,id FROM inventory_vendor_service_areas where vendor_id=$id");
        $this->set(compact('areas'));    	        
    }
	
	public function map_vendor_with_sku() {
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        $this->layout = "users";
	    
	    if(isset($_POST['checkedData'])){
    	    $checkeddatas=JSON_decode($_POST['checkedData'],true);
    	    foreach($checkeddatas as $checkeddata){
    	        $vendor_id=$checkeddata['vendor_id'];
    	        $this->Inventory_vendor_sku_served->query("DELETE FROM inventory_vendor_sku_served WHERE vendor_id =". $vendor_id);
            
    	    }
    	     
    	    foreach($checkeddatas as $checkeddata){
    	        $skuid=$checkeddata['id'];
    	        $price=$checkeddata['price'];
    	        $sku_name=$checkeddata['sku_name'];
    	        $sku_brand=$checkeddata['sku_brand'];
    	        $unit_name=$checkeddata['unit_name'];
    	        $unit_id=$checkeddata['unit_id'];
    	        $vendor_id=$checkeddata['vendor_id'];
    	        
    	        
    	        $data['Inventory_vendor_sku_served']=array(
        			'sku_name'=>$sku_name,
        			'sku_brand'=>$sku_brand,
        			'sku_unit_name'=>$unit_name,
        			'sku_unit'=>$unit_id,
        			'vendor_id'=>$vendor_id,
        			'skus_id'=>$skuid,
        			'sku_price'=>$price
        		);
        	    
        	    if($this->Inventory_vendor_sku_served->saveAll($data['Inventory_vendor_sku_served']))
        		{
        		    
        		}else{
        		    $this->Flash->error(__('sku could not be saved. Please, try again.'));
        		}
    	    }
    	    $this->Flash->success(__('Skus Mapped Successfully'));
			return $this->redirect(array('action' => 'vendor_list'));
    	}else{
    	    $id=$_REQUEST['id'];
    	    $user="SELECT *,(SELECT sku_price FROM `inventory_vendor_sku_served` WHERE vendor_id=$id and skus_id=inventory_skus.id limit 1) AS vendor_price FROM `inventory_skus`  where inventory_skus.status=1 order by inventory_skus.name desc"; 
            $users=$this->Inventory_sku->query($user);
            $this->set(compact('users'));
            $this->set(compact('id'));
        }
    	
	

	}
	
	public function create_semifinished()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		$units=$this->Catalog_unit->find('all',array('conditions'=>array('status'=>1)));
	    $taxes=$this->Inventory_tax->find('all',array('conditions'=>array('status'=>1)));
	    
	    $categorys = $this->Inventory_category->find('all', ['conditions' => ['status' => 1]]);
        
        $options = [];
        foreach ($categorys as $category) {
            $cat_id = $category['Inventory_category']['id'];
            $cat_name = $category['Inventory_category']['name'];
        
            $subcategorys = $this->Inventory_subcategory->find('all', [
                'conditions' => ['cat_id' => $cat_id, 'status' => 1]
            ]);
        
            if (!empty($subcategorys)) {
                foreach ($subcategorys as $sub) {
                    $sub_id = $sub['Inventory_subcategory']['id'];
                    $sub_name = $sub['Inventory_subcategory']['name'];
                    $options[$cat_name]["sub_$sub_id"] = $sub_name;
                }
            } else {
                $options["cat_$cat_id"] = $cat_name;
            }
        }
        $this->set(compact('categorys', 'subcategorys', 'units', 'taxes', 'options'));

	
		if ($this->request->is(array('post', 'put'))) {
            
            $name = $this->data['User']['name'];
            if($name==''){
                $this->Flash->error(__('The Name could not be Blank'));
                return $this->redirect(array('action' => 'create_semifinished'));
            }
            
            $name = $this->data['User']['name'];
            $unit = $this->data['User']['unit'];
            $price = $this->data['User']['price'];
            $remarks = $this->data['User']['remarks'];
            
            $conunit = $this->data['User']['conunit'];
            $factor = $this->data['User']['factor'];
            $conprice = $this->data['User']['conprice'];
            
            // CATEGORY
            $category_id = null;
            $category_name = '';
            $subcategory_id = '';
            $subcategory_name = '';
            
            $categoryInput = $this->data['User']['category'] ?? '';
            
            if (strpos($categoryInput, 'cat_') === 0) {
                $category_id = (int) str_replace('cat_', '', $categoryInput);
                $catData = $this->Inventory_category->findById($category_id);
                if ($catData) {
                    $category_name = $catData['Inventory_category']['name'];
                }
                
            } elseif (strpos($categoryInput, 'sub_') === 0) {

                $subcategory_id = (int) str_replace('sub_', '', $categoryInput);
                $subcatData = $this->Inventory_subcategory->findById($subcategory_id);
                if ($subcatData) {
                    $subcategory_name = $subcatData['Inventory_subcategory']['name'];
                    $category_id = $subcatData['Inventory_subcategory']['cat_id'];
                    $category_name = $this->Inventory_category->field('name', ['id' => $category_id]);
                }
            } else {
                // Treat as new category name
                $newcat = trim($categoryInput);
                $this->Inventory_category->create();
                if ($this->Inventory_category->save(['name' => $newcat])) {
                    $category_id = $this->Inventory_category->id;
                    $category_name = $newcat;
                } else {
                    $this->Flash->error(__('New category could not be saved. Please try again.'));
                    return;
                }
            }
            
            $unitname=$this->Catalog_unit->find('first',array('conditions'=>array('id'=>$unit)));
            $conunitname=$this->Catalog_unit->find('first',array('conditions'=>array('id'=>$conunit)));

	        $data['Inventory_semifinished']=array(
    			'name'=>$name,
    			'unit'=>$unit,
    			'cat_id' => $category_id,
                'cat_name' => $category_name,
                'subcat_id' => $subcategory_id,
                'subcat_name' => $subcategory_name,
                'unit_name'=>$unitname['Catalog_unit']['name'],
    			'price'=>$price,
    			'consumption_unit_id'=>$conunit,
                'consumption_unit_name'=>$conunitname['Catalog_unit']['name'],
                'consumption_factor'=>$factor,
                'consumption_unit_price'=>$conprice,
                'remarks'=>$remarks,
    			'moq' => $this->data['User']['moq'] ?? 0
    		);
    	    
    	    if($this->Inventory_semifinished->saveAll($data['Inventory_semifinished']))
    		{
    		    $lastInsertedID = $this->Inventory_semifinished->id;
    		    
    		    $taxes=$this->Inventory_tax->find('all',array('conditions'=>array('status'=>1)));
    	        foreach ($taxes as $taxess) {
                    $taxID = $taxess['Inventory_tax']['id'];
                    if (!empty($this->request->data['User']['tax_' . $taxID])) {
                        $selectedTaxes[] = $this->request->data['User']['tax_' . $taxID];
                        $taxdetail=$this->Inventory_tax->find('first',array('conditions'=>array('id'=>$taxID)));
            	        if($taxdetail){
            	            $data['Inventory_semifinished_tax']=array(
                    			'product_id'=>$lastInsertedID,
                    			'product_name'=>$name,
                    			'tax_id'=>$taxID,
                    			'tax_name'=>$taxdetail['Inventory_tax']['name'],
                    			'tax_percentage'=>$taxdetail['Inventory_tax']['percentage']
                    		);
                    	    
                    	    if($this->Inventory_semifinished_tax->saveAll($data['Inventory_semifinished_tax']))
                    		{
                    		    
                    		}else{
                    		    $this->Flash->error(__('Semi-Finished tax could not be saved. Please, try again.'));
                    		}
            	        }
                    }
                }
                
                if(isset($_POST['custom_tax_name'])){
                
                    $taxnames=$_POST['custom_tax_name'];
        	        $taxvalues=$_POST['custom_tax_value'];
        	           
                    for ($i = 0; $i < count($taxnames); $i++) {
                        $taxname = $taxnames[$i];
                        $percentage = $taxvalues[$i];
                        
                        $newtaxdetail=$this->Inventory_tax->find('first',array('conditions'=>array('name'=>$taxname,'percentage'=>$percentage)));
            	        if(empty($newtaxdetail)){
            	            $data['Inventory_tax']=array(
                    			'name'=>$taxname,
                    			'percentage'=>$percentage
                    	    );
                    	    
                    	    if($this->Inventory_tax->saveAll($data['Inventory_tax']))
                    		{
                    		    $taxlastInsertedID = $this->Inventory_tax->id;
            		    
                    		} else {
                				$this->Flash->error(__('New Tax could not be saved. Please, try again.'));
                			}
            	        }
            	        
            	        $data['Inventory_semifinished_tax']=array(
                			'product_id'=>$lastInsertedID,
                			'product_name'=>$name,
                			'tax_id'=>$taxlastInsertedID,
                			'tax_name'=>$taxname,
                			'tax_percentage'=>$percentage
                		);
                	    
                	    if($this->Inventory_semifinished_tax->saveAll($data['Inventory_semifinished_tax']))
                		{
                		    
                		}else{
                		    $this->Flash->error(__('Semi-Finished New tax could not be saved. Please, try again.'));
                		}
                        
                    }
                }
                $this->Flash->success(__('Semi-Finished has been saved.'));
				return $this->redirect(array('action' => 'semifinished_list'));
			} else {
				$this->Flash->error(__('Semi-Finished could not be saved. Please, try again.'));
			}
		}
		
	}
	
	public function semifinished_list()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		$startDate = date('m/d/Y', strtotime('-12 months'));
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
		}else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }   
        
		
		$users = $this->Inventory_semifinished->query("SELECT * FROM inventory_semifinished where created between '$startdate 00:00:01' and  '$enddate 23:59:59' ORDER BY id desc");
        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        
		$this->set(compact('users'));

	}
	
	public function edit_semifinished()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
	    
		$units=$this->Catalog_unit->find('all',array('conditions'=>array('status'=>1)));
	    $taxes=$this->Inventory_tax->find('all',array('conditions'=>array('status'=>1)));
	    
	   // $this->set(compact('units','taxes'));
	    
	    $id=$_REQUEST['id'];
    
        $products = $this->Inventory_semifinished->query("SELECT * FROM inventory_semifinished where id=$id");
        $this->set(compact('products'));
        
        $product_taxes=$this->Inventory_semifinished_tax->find('all',array('conditions'=>array('product_id'=>$id),'order'=>array('id'=>'desc')));
        $this->set(compact('product_taxes'));
		
		
		$categories = $this->Inventory_category->find('all', array('conditions' => array('status' => 1), 'order' => array('name' => 'asc')));

        $unit=$products[0]['inventory_semifinished']['unit'];
        $conunits=$this->Catalog_unit_mapping->find('all',array('conditions'=>array('status'=>1,'unit_id'=>$unit)));
        

		$options = [];
		if (!empty($products[0]['inventory_semifinished']['subcat_id'])) {
            $selectedcatId = $products[0]['inventory_semifinished']['subcat_id'];
            $selectedType = 'sub';
            } else {
            $selectedcatId = $products[0]['inventory_semifinished']['cat_id'];
            $selectedType = 'cat';
            }
        // $selectedcatId = !empty($products[0]['inventory_semifinished']['subcat_id']) ? $products[0]['inventory_semifinished']['subcat_id'] : $products[0]['inventory_semifinished']['cat_id'];
        $selectedcategory = null;
    
        foreach ($categories as $category) {
            $cat_id = $category['Inventory_category']['id'];
            $cat_name = $category['Inventory_category']['name'];
            $subcategories = $this->Inventory_subcategory->find('all', array(
                'conditions' => array('cat_id' => $cat_id, 'status' => 1),
                'order' => array('name' => 'asc')
            ));
            if (!empty($subcategories)) {
                $options[$cat_name] = [];
                foreach ($subcategories as $subcategory) {
                    $subcat_id = $subcategory['Inventory_subcategory']['id'];
                    $subcat_name = $subcategory['Inventory_subcategory']['name'];
                    if ($subcat_id == $selectedcatId  && $selectedType == 'sub') {
                        $selectedcategory = $subcategory['Inventory_subcategory'];
                        $selectedcategory['_type'] = 'sub';
                    }
                    $options[$cat_name]["sub_$subcat_id"] = $subcat_name;
                }
            } else {
                if ($cat_id == $selectedcatId  && $selectedType == 'cat') {
                    $selectedcategory = $category['Inventory_category'];
                    $selectedcategory['_type'] = 'cat';
                }
                $options["cat_$cat_id"] = $cat_name;
            }
        }
        if (!empty($selectedcategory)) {
            $key_prefix = ($selectedcategory['_type'] == 'sub') ? 'sub_' : 'cat_';
            $options = array($key_prefix . $selectedcategory['id'] => $selectedcategory['name']) + $options;
        }

        $this->set(compact('categories', 'subcategories', 'taxes', 'units', 'options', 'selectedcatId','conunits'));
        
		if ($this->data['User']['id']!='') {
		    
		    $id=$this->data['User']['id'];
            $name = $this->data['User']['name'];
            if($name==''){
                $this->Flash->error(__('The Name could not be Blank'));
                return $this->redirect(array('action' => 'edit_semifinished?id='.$id));
            }
            $unit = $this->data['User']['unit'];
            $price = $this->data['User']['price'];
            $remarks = $this->data['User']['remarks'];
            $moq= $this->data['User']['moq'];
            
            $conunit = $this->data['User']['conunit'];
            $factor = $this->data['User']['factor'];
            $conprice = $this->data['User']['conprice'];
        
            // CATEGORY
            $category_id = null;
            $category_name = '';
            $subcategory_id = '';
            $subcategory_name = '';
            
            $categoryInput = $this->data['User']['category'] ?? '';
            
            if (strpos($categoryInput, 'cat_') === 0) {
                $category_id = (int) str_replace('cat_', '', $categoryInput);
                $catData = $this->Inventory_category->findById($category_id);
                if ($catData) {
                    $category_name = $catData['Inventory_category']['name'];
                }
            }elseif (strpos($categoryInput, 'sub_') === 0) {
                $subcategory_id = (int) str_replace('sub_', '', $categoryInput);
                $subcatData = $this->Inventory_subcategory->findById($subcategory_id);
                if ($subcatData) {
                    $subcategory_name = $subcatData['Inventory_subcategory']['name'];
                    $category_id = $subcatData['Inventory_subcategory']['cat_id'];
                    $category_name = $this->Inventory_category->field('name', ['id' => $category_id]);
                }
            }else {
                // Treat as new category name
                $newcat = trim($categoryInput);
                $this->Inventory_category->create();
                if ($this->Inventory_category->save(['name' => $newcat])) {
                    $category_id = $this->Inventory_category->id;
                    $category_name = $newcat;
                } else {
                    $this->Flash->error(__('New category could not be saved. Please try again.'));
                    return;
                }
            }
            
            $unitname=$this->Catalog_unit->find('first',array('conditions'=>array('id'=>$unit)));
	        $unit_name=$unitname['Catalog_unit']['name'];
	        
	        if($conunit){
                $conunitnames=$this->Catalog_unit->find('first',array('conditions'=>array('id'=>$conunit)));
                $conunitname=$conunitnames['Catalog_unit']['name'];
            }else{
                $conunit=0;
                $factor=0;
                $conprice=0;
                $conunitname='';
            }
            
            $this->Inventory_semifinished->query("UPDATE inventory_semifinished SET consumption_unit_id='$conunit',consumption_unit_name='$conunitname',consumption_factor='$factor',consumption_unit_price='$conprice' ,moq='$moq', cat_id='$category_id',cat_name='$category_name',subcat_id='$subcategory_id',subcat_name='$subcategory_name',name ='$name',unit='$unit',unit_name='$unit_name',price='$price',remarks='$remarks',sync = 0 WHERE id =". $id);
            
            //tax Update
            $this->Inventory_semifinished_tax->query("DELETE FROM inventory_semifinished_tax  WHERE product_id =". $id);
            $taxes=$this->Inventory_tax->find('all',array('conditions'=>array('status'=>1)));
	        foreach ($taxes as $taxess) {
                $taxID = $taxess['Inventory_tax']['id'];
                if (!empty($this->request->data['User']['tax_' . $taxID])) {
                    $selectedTaxes[] = $this->request->data['User']['tax_' . $taxID];
                    $taxdetail=$this->Inventory_tax->find('first',array('conditions'=>array('id'=>$taxID)));
        	        if($taxdetail){
        	            $data['Inventory_semifinished_tax']=array(
                			'product_id'=>$id,
                			'product_name'=>$name,
                			'tax_id'=>$taxID,
                			'tax_name'=>$taxdetail['Inventory_tax']['name'],
                			'tax_percentage'=>$taxdetail['Inventory_tax']['percentage']
                		);
                	    
                	    if($this->Inventory_semifinished_tax->saveAll($data['Inventory_semifinished_tax']))
                		{
                		    
                		}else{
                		    $this->Flash->error(__('Semi-finished tax could not be saved. Please, try again.'));
                		}
        	        }
                }
            }
            
            if(isset($_POST['tax_name'])){
                
                $taxnames=$_POST['tax_name'];
    	        $taxvalues=$_POST['tax_value'];
    	           
                for ($i = 0; $i < count($taxnames); $i++) {
                    $taxname = $taxnames[$i];
                    $percentage = $taxvalues[$i];
                    
                    $newtaxdetail=$this->Inventory_tax->find('first',array('conditions'=>array('name'=>$taxname,'percentage'=>$percentage)));
        	        if(empty($newtaxdetail)){
        	            $data['Inventory_tax']=array(
                			'name'=>$taxname,
                			'percentage'=>$percentage
                	    );
                	    
                	    if($this->Inventory_tax->saveAll($data['Inventory_tax']))
                		{
                		    $taxlastInsertedID = $this->Inventory_tax->id;
        		    
                		} else {
            				$this->Flash->error(__('New Tax could not be saved. Please, try again.'));
            			}
        	        }
        	        
        	        $data['Inventory_semifinished_tax']=array(
            			'product_id'=>$id,
            			'product_name'=>$name,
            			'tax_id'=>$taxlastInsertedID,
            			'tax_name'=>$taxname,
            			'tax_percentage'=>$percentage
            		);
            	    
            	    if($this->Inventory_semifinished_tax->saveAll($data['Inventory_semifinished_tax']))
            		{
            		    
            		}else{
            		    $this->Flash->error(__('Semi-finished New tax could not be saved. Please, try again.'));
            		}
                    
                }
            }
            
            $this->Flash->success(__('Semi-finished has been Updated.'));
            return $this->redirect(array('action' => 'semifinished_list'));
		}
		
    }
	
	public function view_semifinished()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        $this->layout = "users";
	    $id=$_REQUEST['id'];
		
		$products = $this->Inventory_semifinished->query("SELECT * FROM inventory_semifinished where id=$id");
        $this->set(compact('products'));
        
        $taxes=$this->Inventory_semifinished_tax->query("SELECT CONCAT(tax_name, '(', tax_percentage, '%)') as taxname ,id FROM inventory_semifinished_tax where product_id=$id");
        $this->set(compact('taxes'));    	        
    }
	/*
	public function add_recipe()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		$id=$_REQUEST['id'];
    
        $products = $this->Inventory_semifinished->query("SELECT * FROM inventory_semifinished where id=$id");
        $this->set(compact('products'));
        
		$recipes = $this->Inventory_semifinished_sku_linking->query("SELECT * FROM inventory_semifinished_sku_linking where semifinished_id=$id");
        $this->set(compact('recipes'));
        
        $skus=$this->Inventory_sku->find('all',array('conditions'=>array('status'=>1)));
	    $this->set(compact('skus'));
	
		if ($this->request->is(array('post', 'put'))) {
            $semi_id = $this->data['User']['id'];
            if($semi_id==''){
                $this->Flash->error(__('Semifinished Error'));
                return $this->redirect(array('action' => 'add_recipe?id='.$semi_id));
            }
            $semi_name = $this->data['User']['name'];
            $semi_unit = $this->data['User']['unit'];
            $semi_unit_name = $this->data['User']['unit_name'];
            
            // semifinished linking
            
            $selectedSemifinished=[];
            $semifinishedquantity=[];
            $semi_ids=[];
            $semi_quantities=[];
            print_r($this->request->data['User']);
                
            $semifinisheds=$this->Inventory_semifinished->find('all',array('conditions'=>array('status'=>1)));
	        foreach($semifinisheds as $semifinished){
	            $semifinishedid = $semifinished['Inventory_semifinished']['id'];
	            if (!empty($this->request->data['User']['semi_id_' . $semifinishedid])) {
                    $selectedSemifinished[] = $this->request->data['User']['semi_id_' . $semifinishedid];
                    $semifinishedquantity[]=$this->request->data['User']['semi_quantity_' . $semifinishedid];
                }
	        }
	        exit;
            
	        if(isset($_POST['select_semi_name'])){
    	        $semi_ids=$_POST['select_semi_name'];
                $semi_quantities=$_POST['semi_quantity'];
	        }
            $mergedArraysemi = array_merge($selectedSemifinished, $semi_ids);
            $uniqueArraysemi = array_unique($mergedArraysemi);
            $semi_ids = array_values($uniqueArraysemi);
            
            $mergedArraysemi1 = array_merge($semifinishedquantity, $semi_quantities);
            // $uniqueArraysemi1 = array_unique($mergedArraysemi1);
            $semi_quantities = array_values($mergedArraysemi1);
print_r($semi_ids);exit;
            if(isset($semi_ids)){
                $this->Inventory_semifinished_semifinished_linking ->query("DELETE FROM inventory_semifinished_semifinished_linking where semifinished_id=$semi_id");
                    
                for ($i = 0; $i < count($semi_ids); $i++) {
                    $linksemi_id = $semi_ids[$i];
                    $semi_quantity = $semi_quantities[$i];
                    
                    $seminame=$this->Inventory_semifinished->find('first',array('conditions'=>array('id'=>$linksemi_id)));
                    $linksemi_name=$seminame['Inventory_semifinished']['name'];
                    $linksemi_unit=$seminame['Inventory_semifinished']['unit'];
                    $linksemi_unit_name=$seminame['Inventory_semifinished']['unit_name'];
                    
                    $data['Inventory_semifinished_semifinished_linking']=array(
            			'semifinished_id'=>$semi_id,
            			'semifinished_name'=>$semi_name,
            			'semifinished_unit'=>$semi_unit,
            			'semifinished_unit_name'=>$semi_unit_name,
            			'linked_semifinished_id'=>$linksemi_id,
            			'linked_semifinished_name'=>$linksemi_name,
            			'linked_semifinished_unit'=>$linksemi_unit,
            			'linked_semifinished_unit_name'=>$linksemi_unit_name,
            			'linked_semifinished_quantity'=>$semi_quantity
            		);
            	    
            	    if($this->Inventory_semifinished_semifinished_linking->saveAll($data['Inventory_semifinished_semifinished_linking']))
            		{
            		    
            		}else{
            		    $this->Flash->error(__('Semifinished mapping could not be saved. Please, try again.'));
            		}
                }
            }
            
            
            
            //sku linking
            $selectedSkus=[];
            $quantity=[];
            $skus=$this->Inventory_sku->find('all',array('conditions'=>array('status'=>1)));
	        foreach($skus as $sku){
	            $skuid = $sku['Inventory_sku']['id'];
                if (!empty($this->request->data['User']['sku_id_' . $skuid])) {
                    $selectedSkus[] = $this->request->data['User']['sku_id_' . $skuid];
                    $quantity[]=$this->request->data['User']['quantity_' . $skuid];
                }
	        }
	        
	        if(isset($_POST['select_sku_name'])){
        	    $sku_ids=$_POST['select_sku_name'];
                $quantities=$_POST['quantity'];
            }
	        
            $mergedArray = array_merge($selectedSkus, $sku_ids);
            $uniqueArray = array_unique($mergedArray);
            $sku_ids = array_values($uniqueArray);
            
            $mergedArray1 = array_merge($quantity, $quantities);
            // $uniqueArray1 = array_unique($mergedArray1);
            $quantities = array_values($mergedArray1);

            if(isset($sku_ids)){
                $this->Inventory_semifinished_sku_linking->query("DELETE FROM inventory_semifinished_sku_linking where semifinished_id=$semi_id");
                    
                for ($i = 0; $i < count($sku_ids); $i++) {
                    $sku_id = $sku_ids[$i];
                    $quantity = $quantities[$i];
                    
                    $skuname=$this->Inventory_sku->find('first',array('conditions'=>array('id'=>$sku_id)));
                    // print_r($skuname);exit;
                    $sku_name=$skuname['Inventory_sku']['name'];
                    $sku_unit=$skuname['Inventory_sku']['unit'];
                    $sku_unit_name=$skuname['Inventory_sku']['unit_name'];
                    
                    $data['Inventory_semifinished_sku_linking']=array(
            			'semifinished_id'=>$semi_id,
            			'semifinished_name'=>$semi_name,
            			'semifinished_unit'=>$semi_unit,
            			'semifinished_unit_name'=>$semi_unit_name,
            			'sku_id'=>$sku_id,
            			'sku_name'=>$sku_name,
            			'sku_unit'=>$sku_unit,
            			'sku_unit_name'=>$sku_unit_name,
            			'sku_quantity'=>$quantity
            		);
            	    
            	    if($this->Inventory_semifinished_sku_linking->saveAll($data['Inventory_semifinished_sku_linking']))
            		{
            		    
            		}else{
            		    $this->Flash->error(__('Recipe could not be saved. Please, try again.'));
            		}
                }
            }
            
            $this->Flash->success(__('Recipe has been saved.'));
			return $this->redirect(array('action' => 'semifinished_list'));
        }
		
	}
	*/
	public function add_recipe()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		$id=$_REQUEST['id'];
    
        $products = $this->Inventory_semifinished->query("SELECT * FROM inventory_semifinished where id=$id");
        $this->set(compact('products'));
        
		$recipes = $this->Inventory_linking->query("SELECT * FROM inventory_linking where parent_id=$id and parent_type='Semifinished' and component_type='Semifinished'");
        $skurecipes = $this->Inventory_linking->query("SELECT * FROM inventory_linking where parent_id=$id and parent_type='Semifinished' and component_type='Sku'");
        $this->set(compact('recipes'));
        $this->set(compact('recipes','skurecipes'));
        
        if ($this->request->is(array('post', 'put'))) {
            $product_id = $this->data['User']['id'];
            if($product_id==''){
                $this->Flash->error(__('Error'));
                return $this->redirect(array('action' => 'add_recipe?id='.$product_id));
            }
            
            $product_name = $this->data['User']['name'];
            $product_unit = $this->data['User']['unit'];
            $product_unit_name = $this->data['User']['unit_name'];
            
            $yield = $this->data['User']['yield'];
            
            $this->Inventory_semifinished->updateAll(
                ['Inventory_semifinished.yield' => $yield],
                ['Inventory_semifinished.id' => $product_id]
            );
            
            $selectedSemifinished=[];
            $semifinishedquantity=[];
            $semi_ids=[];
            $semi_quantities=[];
            $semifinisheds=$this->Inventory_semifinished->find('all',array('conditions'=>array('status'=>1)));
	        foreach($semifinisheds as $semifinished){
	            $semifinishedid = $semifinished['Inventory_semifinished']['id'];
                if (!empty($this->request->data['User']['semi_id_' . $semifinishedid])) {
                    $selectedSemifinished[] = $this->request->data['User']['semi_id_' . $semifinishedid];
                    $semifinishedquantity[]=$this->request->data['User']['semi_quantity_' . $semifinishedid];
                }
	        }
	        if(isset($_POST['select_semi_name'])){
    	        $semi_ids=$_POST['select_semi_name'];
                $semi_quantities=$_POST['semi_quantity'];
	        }
            $mergedArraysemi = array_merge($selectedSemifinished, $semi_ids);
            $uniqueArraysemi = array_unique($mergedArraysemi);
            $semi_ids = array_values($uniqueArraysemi);
            
            $mergedArraysemi1 = array_merge($semifinishedquantity, $semi_quantities);
            $semi_quantities = array_values($mergedArraysemi1);

            if(isset($semi_ids)){
                $this->Inventory_linking->deleteAll([
                    'Inventory_linking.parent_id' => $product_id,
                    'Inventory_linking.parent_type' => 'Semifinished',
                    'Inventory_linking.component_type' => 'Semifinished'
                ], false);
    
                for ($i = 0; $i < count($semi_ids); $i++) {
                    $semi_id = $semi_ids[$i];
                    $semi_quantity = $semi_quantities[$i];
                    
                    $seminame=$this->Inventory_semifinished->find('first',array('conditions'=>array('id'=>$semi_id)));
                    $semi_name=$seminame['Inventory_semifinished']['name'];
                    $semi_unit=$seminame['Inventory_semifinished']['consumption_unit_id']?$seminame['Inventory_semifinished']['consumption_unit_id']:0;
                    $semi_unit_name=$seminame['Inventory_semifinished']['consumption_unit_name']?$seminame['Inventory_semifinished']['consumption_unit_name']:'';
                    $semi_unit_price=$seminame['Inventory_semifinished']['consumption_unit_price']?$seminame['Inventory_semifinished']['consumption_unit_price']:0;
                    
                    $component_purchase_unit=$seminame['Inventory_semifinished']['unit']?$seminame['Inventory_semifinished']['unit']:0;
                    $component_purchase_unit_name=$seminame['Inventory_semifinished']['unit_name']?$seminame['Inventory_semifinished']['unit_name']:'';
                    
                    $mappedUnits = $this->Catalog_unit_mapping->find('first', [
                        'conditions' => ['mapped_unit_id' => $semi_unit,'unit_id' => $component_purchase_unit, 'status' => 1],
                        'fields' => ['conversion_factor'],
                        'recursive' => -1,
                    ]);
                    
                    
                    $conversion_factor=$mappedUnits['Catalog_unit_mapping']['conversion_factor']?$mappedUnits['Catalog_unit_mapping']['conversion_factor']:0;
                    if($conversion_factor>0){
                       $component_purchase_unit_quantity=$semi_quantity/$conversion_factor; 
                    }else{
                        $component_purchase_unit_quantity=0;
                    }
                    // print_r($sku_quantity);exit;
                    
                    $data['Inventory_linking']=array(
            			'parent_type'=>'Semifinished',
            			'parent_id'=>$product_id,
            			'parent_name'=>$product_name,
            			'parent_yield'=>$yield,
            			'component_type'=>'Semifinished',
            			'component_id'=>$semi_id,
            			'component_name'=>$semi_name,
            			'quantity'=>$component_purchase_unit_quantity,
            			'component_unit'=>$semi_unit,
            			'component_unit_name'=>$semi_unit_name,
            			'component_price'=>$semi_unit_price,
            			'component_purchase_unit'=>$component_purchase_unit,
            			'component_purchase_unit_name'=>$component_purchase_unit_name,
            			'conversion_quantity'=>$semi_quantity
            		);
            	   // print_r($data);exit;
                    if($this->Inventory_linking->saveAll($data['Inventory_linking']))
            		{
            		    
            		}else{
            		    $this->Flash->error(__('Semifinished mapping could not be saved. Please, try again.'));
            		}
                }
            }
            
            $selectedSku=[];
            $skuquantity=[];
            $sku_ids=[];
            $sku_quantities=[];
            $skus=$this->Inventory_sku->find('all',array('conditions'=>array('status'=>1)));
	        foreach($skus as $sku){
	            $skuid = $sku['Inventory_sku']['id'];
                if (!empty($this->request->data['User']['sku_id_' . $skuid])) {
                    $selectedSku[] = $this->request->data['User']['sku_id_' . $skuid];
                    $skuquantity[]=$this->request->data['User']['sku_quantity_' . $skuid];
                }
	        }
	        if(isset($_POST['select_sku_name'])){
    	        $sku_ids=$_POST['select_sku_name'];
                $sku_quantities=$_POST['sku_quantity'];
	        }
            $mergedArraysku = array_merge($selectedSku, $sku_ids);
            $uniqueArraysku = array_unique($mergedArraysku);
            $sku_ids = array_values($uniqueArraysku);
            
            $mergedArraysku1 = array_merge($skuquantity, $sku_quantities);
            $sku_quantities = array_values($mergedArraysku1);
            
            if(isset($sku_ids)){
                $this->Inventory_linking->deleteAll([
                    'Inventory_linking.parent_id' => $product_id,
                    'Inventory_linking.parent_type' => 'Semifinished',
                    'Inventory_linking.component_type' => 'Sku'
                ], false);
                    
                for ($i = 0; $i < count($sku_ids); $i++) {
                    $sku_id = $sku_ids[$i];
                    $sku_quantity = $sku_quantities[$i];
                    
                    $skuname=$this->Inventory_sku->find('first',array('conditions'=>array('id'=>$sku_id)));
                    $sku_name=$skuname['Inventory_sku']['name'];
                    $sku_unit=$skuname['Inventory_sku']['consumption_unit_id']?$skuname['Inventory_sku']['consumption_unit_id']:0;
                    $sku_unit_name=$skuname['Inventory_sku']['consumption_unit_name']?$skuname['Inventory_sku']['consumption_unit_name']:'';
                    $semi_unit_price=$skuname['Inventory_sku']['consumption_unit_price']?$skuname['Inventory_sku']['consumption_unit_price']:0;
                    
                    $component_purchase_unit=$skuname['Inventory_sku']['unit']?$skuname['Inventory_sku']['unit']:0;
                    $component_purchase_unit_name=$skuname['Inventory_sku']['unit_name']?$skuname['Inventory_sku']['unit_name']:'';
                    
                    $mappedUnits = $this->Catalog_unit_mapping->find('first', [
                        'conditions' => ['mapped_unit_id' => $sku_unit,'unit_id' => $component_purchase_unit, 'status' => 1],
                        'fields' => ['conversion_factor'],
                        'recursive' => -1,
                    ]);
                    $conversion_factor=$mappedUnits['Catalog_unit_mapping']['conversion_factor']?$mappedUnits['Catalog_unit_mapping']['conversion_factor']:0;
                    // print_r($mappedUnits);exit;
                    if($conversion_factor>0){
                       $component_purchase_unit_quantity=$sku_quantity/$conversion_factor; 
                    }else{
                        $component_purchase_unit_quantity=0;
                    }
                    
                    
                    $data['Inventory_linking']=array(
            			'parent_type'=>'Semifinished',
            			'parent_id'=>$product_id,
            			'parent_name'=>$product_name,
            			'parent_yield'=>$yield,
            			'component_type'=>'Sku',
            			'component_id'=>$sku_id,
            			'component_name'=>$sku_name,
            			'quantity'=>$component_purchase_unit_quantity,
            			'component_unit'=>$sku_unit,
            			'component_unit_name'=>$sku_unit_name,
            			'component_price'=>$semi_unit_price,
            			'component_purchase_unit'=>$component_purchase_unit,
            			'component_purchase_unit_name'=>$component_purchase_unit_name,
            			'conversion_quantity'=>$sku_quantity
            		);
            	    
                    if($this->Inventory_linking->saveAll($data['Inventory_linking']))
            		{
            		    
            		}else{
            		    $this->Flash->error(__('Sku mapping could not be saved. Please, try again.'));
            		}
                }
            }
            
            $this->Flash->success(__('Recipe has been saved.'));
			return $this->redirect(array('action' => 'semifinished_list'));
        }
		
	}
	
	public function fetch_skus_options() {
        $this->autoRender = false; // Disable view rendering
        $skuss=array();
        $skus=$this->Inventory_sku->find('all',array('conditions'=>array('status'=>1)));
        foreach($skus as $sku){
            $skuss[]=$sku['Inventory_sku'];
        }
        $responseArray = array('response_code' => 1, 'data' => $skuss);
        echo json_encode($responseArray);

    }
    
    public function product_recipe()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		$id=$_REQUEST['id'];
    
        $products = $this->Catalog_product->query("SELECT * FROM catalog_product where id=$id");
        $this->set(compact('products'));
        
		$recipes = $this->Inventory_linking->query("SELECT * FROM inventory_linking where parent_id=$id and parent_type='Product' and component_type='Semifinished'");
        $skurecipes = $this->Inventory_linking->query("SELECT * FROM inventory_linking where parent_id=$id and parent_type='Product' and component_type='Sku'");
        $this->set(compact('recipes','skurecipes'));
        
        if ($this->request->is(array('post', 'put'))) {
            $product_id = $this->data['User']['id'];
            if($product_id==''){
                $this->Flash->error(__('Product Error'));
                return $this->redirect(array('action' => 'product_recipe?id='.$semi_id));
            }
            
            $product_name = $this->data['User']['name'];
            $product_unit = $this->data['User']['unit'];
            $product_unit_name = $this->data['User']['unit_name'];
            $yield = 1;
            
            $this->Catalog_product->updateAll(
                ['Catalog_product.yield' => $yield],
                ['Catalog_product.id' => $product_id]
            );

            $selectedSemifinished=[];
            $semifinishedquantity=[];
            $semi_ids=[];
            $semi_quantities=[];
            $semifinisheds=$this->Inventory_semifinished->find('all',array('conditions'=>array('status'=>1)));
	        foreach($semifinisheds as $semifinished){
	            $semifinishedid = $semifinished['Inventory_semifinished']['id'];
                if (!empty($this->request->data['User']['semi_id_' . $semifinishedid])) {
                    $selectedSemifinished[] = $this->request->data['User']['semi_id_' . $semifinishedid];
                    $semifinishedquantity[]=$this->request->data['User']['semi_quantity_' . $semifinishedid];
                }
	        }
	        if(isset($_POST['select_semi_name'])){
    	        $semi_ids=$_POST['select_semi_name'];
                $semi_quantities=$_POST['semi_quantity'];
	        }
            $mergedArraysemi = array_merge($selectedSemifinished, $semi_ids);
            $uniqueArraysemi = array_unique($mergedArraysemi);
            $semi_ids = array_values($uniqueArraysemi);
            
            $mergedArraysemi1 = array_merge($semifinishedquantity, $semi_quantities);
            $semi_quantities = array_values($mergedArraysemi1);
            if(isset($semi_ids)){
                $this->Inventory_linking->deleteAll([
                    'Inventory_linking.parent_id' => $product_id,
                    'Inventory_linking.parent_type' => 'Product',
                    'Inventory_linking.component_type' => 'Semifinished'
                ], false);
    
                for ($i = 0; $i < count($semi_ids); $i++) {
                    $semi_id = $semi_ids[$i];
                    $semi_quantity = $semi_quantities[$i];
                    
                    $seminame=$this->Inventory_semifinished->find('first',array('conditions'=>array('id'=>$semi_id)));
                    $semi_name=$seminame['Inventory_semifinished']['name'];
                    $semi_unit=$seminame['Inventory_semifinished']['consumption_unit_id']?$seminame['Inventory_semifinished']['consumption_unit_id']:0;
                    $semi_unit_name=$seminame['Inventory_semifinished']['consumption_unit_name']?$seminame['Inventory_semifinished']['consumption_unit_name']:'';
                    $semi_unit_price=$seminame['Inventory_semifinished']['consumption_unit_price']?$seminame['Inventory_semifinished']['consumption_unit_price']:0;
                    
                    $component_purchase_unit=$seminame['Inventory_semifinished']['unit']?$seminame['Inventory_semifinished']['unit']:0;
                    $component_purchase_unit_name=$seminame['Inventory_semifinished']['unit_name']?$seminame['Inventory_semifinished']['unit_name']:'';
                    
                    $mappedUnits = $this->Catalog_unit_mapping->find('first', [
                        'conditions' => ['mapped_unit_id' => $semi_unit,'unit_id' => $component_purchase_unit, 'status' => 1],
                        'fields' => ['conversion_factor'],
                        'recursive' => -1,
                    ]);
                    
                    $conversion_factor=$mappedUnits['Catalog_unit_mapping']['conversion_factor']?$mappedUnits['Catalog_unit_mapping']['conversion_factor']:0;
                    if($conversion_factor>0){
                       $component_purchase_unit_quantity=$semi_quantity/$conversion_factor; 
                    }else{
                        $component_purchase_unit_quantity=0;
                    }

                    $data['Inventory_linking']=array(
            			'parent_type'=>'Product',
            			'parent_id'=>$product_id,
            			'parent_name'=>$product_name,
            			'parent_yield'=>$yield,
            			'component_type'=>'Semifinished',
            			'component_id'=>$semi_id,
            			'component_name'=>$semi_name,
            			'quantity'=>$component_purchase_unit_quantity,
            			'component_unit'=>$semi_unit,
            			'component_unit_name'=>$semi_unit_name,
            			'component_price'=>$semi_unit_price,
            			'component_purchase_unit'=>$component_purchase_unit,
            			'component_purchase_unit_name'=>$component_purchase_unit_name,
            			'conversion_quantity'=>$semi_quantity

            		);
            	    
            	    if($this->Inventory_linking->saveAll($data['Inventory_linking']))
            		{
            		    
            		}else{
            		    $this->Flash->error(__('Semifinished mapping could not be saved. Please, try again.'));
            		}
                }
            }
            
            $selectedSku=[];
            $skuquantity=[];
            $sku_ids=[];
            $sku_quantities=[];
            $skus=$this->Inventory_sku->find('all',array('conditions'=>array('status'=>1)));
	        foreach($skus as $sku){
	            $skuid = $sku['Inventory_sku']['id'];
                if (!empty($this->request->data['User']['sku_id_' . $skuid])) {
                    $selectedSku[] = $this->request->data['User']['sku_id_' . $skuid];
                    $skuquantity[]=$this->request->data['User']['sku_quantity_' . $skuid];
                }
	        }
	        if(isset($_POST['select_sku_name'])){
    	        $sku_ids=$_POST['select_sku_name'];
                $sku_quantities=$_POST['sku_quantity'];
	        }
            $mergedArraysku = array_merge($selectedSku, $sku_ids);
            $uniqueArraysku = array_unique($mergedArraysku);
            $sku_ids = array_values($uniqueArraysku);
            
            $mergedArraysku1 = array_merge($skuquantity, $sku_quantities);
            $sku_quantities = array_values($mergedArraysku1);
            
            if(isset($sku_ids)){

                $this->Inventory_linking->deleteAll([
                    'Inventory_linking.parent_id' => $product_id,
                    'Inventory_linking.parent_type' => 'Product',
                    'Inventory_linking.component_type' => 'Sku'
                ], false);
  
                for ($i = 0; $i < count($sku_ids); $i++) {
                    $sku_id = $sku_ids[$i];
                    $sku_quantity = $sku_quantities[$i];
                    
                    $skuname=$this->Inventory_sku->find('first',array('conditions'=>array('id'=>$sku_id)));
                    $sku_name=$skuname['Inventory_sku']['name'];
                    $sku_unit=$skuname['Inventory_sku']['consumption_unit_id']?$skuname['Inventory_sku']['consumption_unit_id']:0;
                    $sku_unit_name=$skuname['Inventory_sku']['consumption_unit_name']?$skuname['Inventory_sku']['consumption_unit_name']:'';
                    $semi_unit_price=$skuname['Inventory_sku']['consumption_unit_price']?$skuname['Inventory_sku']['consumption_unit_price']:0;
                    
                    $component_purchase_unit=$skuname['Inventory_sku']['unit']?$skuname['Inventory_sku']['unit']:0;
                    $component_purchase_unit_name=$skuname['Inventory_sku']['unit_name']?$skuname['Inventory_sku']['unit_name']:'';
                    
                    $mappedUnits = $this->Catalog_unit_mapping->find('first', [
                        'conditions' => ['mapped_unit_id' => $sku_unit,'unit_id' => $component_purchase_unit, 'status' => 1],
                        'fields' => ['conversion_factor'],
                        'recursive' => -1,
                    ]);
                    $conversion_factor=$mappedUnits['Catalog_unit_mapping']['conversion_factor']?$mappedUnits['Catalog_unit_mapping']['conversion_factor']:0;
                    if($conversion_factor>0){
                       $component_purchase_unit_quantity=$sku_quantity/$conversion_factor; 
                    }else{
                        $component_purchase_unit_quantity=0;
                    }
                    $data['Inventory_linking']=array(
            			'parent_type'=>'Product',
            			'parent_id'=>$product_id,
            			'parent_name'=>$product_name,
            			'parent_yield'=>$yield,
            			'component_type'=>'Sku',
            			'component_id'=>$sku_id,
            			'component_name'=>$sku_name,
            			'quantity'=>$component_purchase_unit_quantity,
            			'component_unit'=>$sku_unit,
            			'component_unit_name'=>$sku_unit_name,
            			'component_price'=>$semi_unit_price,
            			'component_purchase_unit'=>$component_purchase_unit,
            			'component_purchase_unit_name'=>$component_purchase_unit_name,
            			'conversion_quantity'=>$sku_quantity
            		);
            		
            	    if($this->Inventory_linking->saveAll($data['Inventory_linking']))
            		{
            		    
            		}else{
            		    $this->Flash->error(__('Sku mapping could not be saved. Please, try again.'));
            		}
                }
            }
            
            $this->Flash->success(__('Recipe has been saved.'));
			return $this->redirect(array('action' => 'product_list'));
        }
		
	}
	public function package()
    {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller'=>'dashboard', 'action'=>'login']);
        }
    
        $this->layout = "users";
        $id = $_REQUEST['id'];
    
        $products = $this->Catalog_product->query("SELECT * FROM catalog_product WHERE id = $id");
        $this->set(compact('products'));
    
        $packages = $this->Catalog_package->query("SELECT * FROM catalog_package WHERE main_product_id = $id AND status = 1");
        $this->set(compact('packages'));
    
        if (!empty($_POST['select_semi_name']) && !empty($_POST['pro_price']) && !empty($_POST['pro_quantity'])) {
            $semi_ids = $_POST['select_semi_name'];
            $semi_prices = $_POST['pro_price'];
            $semi_quantities = $_POST['pro_quantity'];
            $semi_units = $_POST['pro_unit'];
            $product_id = $id;
    
            $this->Catalog_package->updateAll(['status' => 0], ['main_product_id' => $product_id]);
    
            $mainProduct = $this->Catalog_product->find('first', [
                'conditions' => ['id' => $product_id],
                'fields' => ['id', 'price', 'name', 'unit', 'unit_name']
            ]);
    
            if (empty($mainProduct)) {
                $this->Flash->error(__('Main product not found.'));
                return $this->redirect(['action' => 'product_list']);
            }
    
            $main_price = $mainProduct['Catalog_product']['price'];
            $main_name = $mainProduct['Catalog_product']['name'];
            $main_unit = $mainProduct['Catalog_product']['unit'];
            $main_unit_name = $mainProduct['Catalog_product']['unit_name'];
    
            foreach ($semi_ids as $i => $link_id) {
                $link_price = $semi_prices[$i];
                $link_qty = $semi_quantities[$i];
    
                if (empty($link_id) || $link_qty <= 0) continue;
    
                $linkProduct = $this->Catalog_product->find('first', [
                    'conditions' => ['id' => $link_id],
                    'fields' => ['id', 'name', 'unit', 'unit_name']
                ]);
    
                if (!empty($linkProduct)) {
                    $data['Catalog_package'] = [
                        'main_product_id' => $product_id,
                        'main_product_name' => $main_name,
                        'main_product_unit_id' => $main_unit,
                        'main_product_unit_name' => $main_unit_name,
                        'main_product_price' => $main_price,
                        'link_product_id' => $link_id,
                        'link_product_name' => $linkProduct['Catalog_product']['name'],
                        'link_product_unit_id' => $linkProduct['Catalog_product']['unit'],
                        'link_product_unit_name' => $linkProduct['Catalog_product']['unit_name'],
                        'link_product_price' => $link_price,
                        'link_quantity' => $link_qty,
                        'status' => 1
                    ];
    
                    $this->Catalog_package->create();
                    if (!$this->Catalog_package->save($data)) {
                        $this->Flash->error(__('Failed to save package item.'));
                    }
                }
            }
    
            $this->Catalog_product->updateAll(['package' => 1], ['id' => $product_id]);
    
            $this->Flash->success(__('Package saved successfully.'));
            return $this->redirect(['action' => 'product_list']);
        }
    }

	public function fetch_semifinished_options() {
        $this->autoRender = false; // Disable view rendering
        $semifinishedd=array();
        $semifinisheds=$this->Inventory_semifinished->find('all',array('conditions'=>array('status'=>1)));
        foreach($semifinisheds as $semifinished){
            $semifinishedd[]=$semifinished['Inventory_semifinished'];
        }
        $responseArray = array('response_code' => 1, 'data' => $semifinishedd);
        echo json_encode($responseArray);

    }
    
    public function fetch_sku_options() {
        $this->autoRender = false; // Disable view rendering
        $skuss=array();
        $skus=$this->Inventory_sku->find('all',array('conditions'=>array('status'=>1)));
        foreach($skus as $sku){
            $skuss[]=$sku['Inventory_sku'];
        }
        $responseArray = array('response_code' => 1, 'data' => $skuss);
        echo json_encode($responseArray);

    }
    
    public function bill_printpdf() {
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
        $this->layout = "login";
	    
        $id=  $_GET['id'];
        $transactions = $this->Order_transaction->query("
            SELECT 
                transaction.*, 
                locations.*,
                users.name as cashiername
            FROM 
                order_transactions transaction
            LEFT JOIN 
                users ON users.id = transaction.cashier_id
            LEFT JOIN 
                locations ON locations.id = users.location_id
            WHERE 
                transaction.id = ".$id."
        ");
        $reference_id=$transactions[0]['transaction']['reference_id'];
        $storeId=$transactions[0]['transaction']['store_id'];
        $cashier_id=$transactions[0]['transaction']['cashier_id'];
        $orderno=$transactions[0]['transaction']['orderno'];
        $discount=$transactions[0]['transaction']['discount'];
        $servicecharge=$transactions[0]['transaction']['servicecharge'];
        $delivery_charge=$transactions[0]['transaction']['delivery_charge'];
        $packing_charge=$transactions[0]['transaction']['packing_charge'];
        $amount=$transactions[0]['transaction']['amount'];
        $created=$transactions[0]['transaction']['created'];
        $table_number=$transactions[0]['transaction']['table_number'];
        $price=$transactions[0]['transaction']['price'];
        $today= date('Y-m-d H:i:s');
        
        $name=$transactions[0]['locations']['name'];
        $print_line1=$transactions[0]['locations']['print_line1'];
        $print_line2=$transactions[0]['locations']['print_line2'];
        $print_line3=$transactions[0]['locations']['print_line3'];
        $print_line4=$transactions[0]['locations']['print_line4'];
        $print_line5=$transactions[0]['locations']['print_line5'];
        $print_line6=$transactions[0]['locations']['print_line6'];
        $print_line7=$transactions[0]['locations']['print_line7'];
        $print_line8=$transactions[0]['locations']['print_line8'];
        $print_line9=$transactions[0]['locations']['print_line9'];
        $print_line10=$transactions[0]['locations']['print_line10'];
        $footer_msg=$transactions[0]['locations']['footer_msg'];
        $currency_symbol=$transactions[0]['locations']['currency_symbol'];
        $cashiername=$transactions[0]['users']['cashiername'];
        
        $orderss = $this->Order_orderhistory->query("SELECT id,product_name,SUM(quantity) as quantity,sum(total_price) as total_price FROM `order_orderhistories` WHERE reference_id='$reference_id' and store_id = '$storeId' and status!=0 group BY product_id");
        $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' GROUP by tax_id");
        $discper = $this->Order_tax->query("SELECT discount_percentage FROM `order_tax` WHERE reference_id='$reference_id' and discount_percentage!=0 limit 1");
        if(!empty($discper))
        {
            $discount_percentage=$discper[0]['order_tax']['discount_percentage'];
        }
        if(!isset($discount_percentage)){
            $discount_percentage="0";
        }
        
        $payments = $this->Order_payment->find('all', array('conditions'=>array('reference_id'=>$reference_id,'status !='=>0)));
        $mode=   $payments[0]['Order_payment']['type_value'];
                    
        $this->set(compact('currency_symbol','delivery_charge','packing_charge','mode','price','table_number','cashiername','servicecharge','amount','today','created','name','print_line1','print_line2','print_line3','print_line4','print_line5','print_line6','print_line7','print_line8','print_line9','print_line10','orderno','orderss','taxes','footer_msg','discount_percentage','discount'));
        
    }
	
	public function internal_indent_list()
    {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }

        $this->layout = "users";

        // --- Default date range: last 1 month
        $startDate = date('m/d/Y', strtotime('-1 month'));
        $endDate   = date('m/d/Y');
        $startdate = date('Y-m-d', strtotime('-1 month'));
        $enddate   = date('Y-m-d');

        // --- Handle date range from form
        if ($this->request->is(['post', 'put'])) {
            $daterange = $this->request->data['daterange'] ?? '';
            if (strpos($daterange, '-') !== false) {
                list($startRaw, $endRaw) = explode(" - ", $daterange);
                $startDate = trim($startRaw);
                $endDate   = trim($endRaw);
                $startdate = date('Y-m-d', strtotime($startDate));
                $enddate   = date('Y-m-d', strtotime($endDate));
            }
        }

        // --- Session values
        $authUser  = $this->Session->read('Auth.User');
        $userRole  = $authUser['role'] ?? '';
        $locationIds = $authUser['location_ids'] ?? '';

        // --- Build conditions for store dropdown
        $conditions2 = ['status' => 1,'type' => 'dc'];

        if ($userRole !== 'admin' && !empty($locationIds)) {
            $userLocationIds = Hash::extract(
                ['ids' => is_array($locationIds) ? $locationIds : explode(',', $locationIds)],
                'ids.{n}'
            );
            $conditions2['id IN'] = array_map('trim', $userLocationIds);
        }

        $stores = $this->Location->find('all', [
            'conditions' => $conditions2
        ]);
        $this->set(compact('stores'));

        // --- Build query conditions for internal indent
        $indentConditions = [
            "created >=" => $startdate . " 00:00:01",
            "created <=" => $enddate . " 23:59:59",
        ];

        // Restrict by role
        if ($userRole !== 'admin' && !empty($conditions2['id IN'])) {
            $indentConditions['location_id IN'] = $conditions2['id IN'];
        }

        // Override with cashier search (applies to everyone)
        if (!empty($this->request->data['Search']['cashier'])) {
            $cashierId = (int)$this->request->data['Search']['cashier'];
            $indentConditions['location_id'] = $cashierId;
        }

        // --- Fetch internal indent records
        $users = $this->Inventory_internal_indent->find('all', [
            'conditions' => $indentConditions,
            'order' => ['id' => 'DESC']
        ]);

        // --- Pass variables to view
        $this->set(compact('users'));
        $this->set('startdate', $startDate . ' - ' . $endDate);
    }

	public function create_internal_indent()
    {
        if (!$this->Session->check('Auth.User.id')) {
            $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "users";
    
        if ($this->Session->read('Auth.User.role') == 'admin') {
            $locations = $this->Location->find('all', ['conditions' => ['status' => 1,'type' => 'dc']]);
        } else {
            
            $authUser = $this->Session->read('Auth.User');
            $userRole = $authUser['role'] ?? '';
            $userLocationId = $authUser['location_ids'] ?? 0;
            
            $userLocationIds = is_array($userLocationId) ? $userLocationId : [$userLocationId];
            $locationCondition['id'] = $userLocationIds; // CakePHP automatically handles IN
            
            $locationCondition = ['status' => 1,'type' => 'dc'];
            
            $locations = $this->Location->find('all', [
                'conditions' => [
                    $locationCondition
                ]
            ]);
            
        }
        
    
        $this->set(compact('locations'));
    
        $users = $this->Inventory_sku->find('all', [
            'conditions' => ['Inventory_sku.status' => 1],
            'order' => ['Inventory_sku.name DESC']
        ]);
        $this->set(compact('users'));
    }

    public function add_internal_indent() 
    {
        $this->autoRender = false;
    
        if (!$this->Session->check('Auth.User.id')) {
            echo json_encode(['response_code' => 0, 'data' => 'User session expired.']);
            return;
        }
    
        $id = $this->Session->read('Auth.User.id');
        $name = $this->Session->read('Auth.User.name');
    
        if (isset($_POST['checkedData']) && isset($_POST['location_id'])) {
            $checkeddatas = json_decode($_POST['checkedData'], true);
            $location_id = (int)$_POST['location_id'];
    
            // Validate location
            $location = $this->Location->find('first', [
                'conditions' => ['Location.id' => $location_id],
                'fields' => ['id', 'name'],
                'recursive' => -1
            ]);
    
            if (empty($location)) {
                echo json_encode(['response_code' => 0, 'data' => 'Invalid location selected.']);
                return;
            }
    
            // Generate unique indent_id
            do {
                // $txnid = '';
                $txnid = rand(1, 9);
                for ($i = 0; $i < 10; $i++) {
                    $txnid .= rand(0, 9);
                }
    
                $existing = $this->Inventory_internal_indent_items->find('first', [
                    'conditions' => ['indent_id' => $txnid],
                    'recursive' => -1
                ]);
            } while ($existing);
    
            $amount = 0;
            $itemsSaved = true;
    
            foreach ($checkeddatas as $item) {
                $skuid = $item['id'];
                $price = $item['price'];
                $quantity = $item['sku_quantity'];
                
                $product_taxes=$this->Inventory_sku_tax->query("select SUM(tax_percentage) as total_tax from inventory_sku_tax where product_id='$skuid' ");
                $total_tax=round($product_taxes['0']['0']['total_tax'],2);
                $tax_value = round(($price*$quantity) * ($total_tax / 100),2);
                $skuamount=round(($price*$quantity) + $tax_value,2);
                
                $skuData = [
                    'indent_id' => $txnid,
                    'sku_id' => $skuid,
                    'sku_name' => $item['sku_name'],
                    'sku_brand' => $item['sku_brand'],
                    'sku_unit' => $item['unit_id'],
                    'sku_unit_name' => $item['unit_name'],
                    'sku_price' => $price,
                    'sku_quantity' => $quantity,
                    'sku_total_tax_percentage' => $total_tax,
                    'sku_total_tax_value' => $tax_value,
                    'sku_amount' => $skuamount
                ];
    
                $this->Inventory_internal_indent_items->create(); // ensure new row
                if (!$this->Inventory_internal_indent_items->save($skuData)) {
                    $itemsSaved = false;
                    break;
                }
    
                $amount += ($skuamount);
            }
    
            if ($itemsSaved) {
                $indentData = [
                    'indent_id' => $txnid,
                    'created_by' => $id,
                    'created_by_name' => $name,
                    'total_amount' => $amount,
                    'location_id' => $location['Location']['id'],
                    'location_name' => $location['Location']['name']
                ];
    
                $this->Inventory_internal_indent->create();
                if ($this->Inventory_internal_indent->save($indentData)) {
                    echo json_encode(['response_code' => 1, 'data' => 'saved']);
                } else {
                    echo json_encode(['response_code' => 0, 'data' => 'Failed to save indent master data.']);
                }
            } else {
                echo json_encode(['response_code' => 0, 'data' => 'Failed to save one or more items.']);
            }
        } else {
            echo json_encode(['response_code' => 0, 'data' => 'Invalid request. Missing data.']);
        }
    }

    public function view_internal_indent()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		$id=$_REQUEST['id'];
    
        $indents = $this->Inventory_internal_indent->query("SELECT * FROM inventory_internal_indent where indent_id=$id");
        $this->set(compact('indents'));
        
		$items = $this->Inventory_internal_indent_items->query("SELECT * FROM inventory_internal_indent_items where indent_id=$id and status=1");
        
        $this->set(compact('items'));
        
        
	}
	
	public function edit_internal_indent()
    {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "users";
        $id = $_REQUEST['id'];
    
        $user_id = $this->Session->read('Auth.User.id');
        $role = $this->Session->read('Auth.User.role');
        $user_location = $this->Session->read('Auth.User.location_id');
    
        // Location dropdown data
        if ($role == 'admin') {
            $locations = $this->Location->find('list', ['conditions' => ['status' => 1,'type' => 'dc']]);
        } else {
            $locations = $this->Location->find('list', [
                'conditions' => ['status' => 1, 'id' => $user_location,'type' => 'dc']
            ]);
        }
    
        // Fetch indent data
        $user = "SELECT *,
            (SELECT sku_quantity FROM inventory_internal_indent_items 
             WHERE indent_id='$id' AND sku_id=inventory_skus.id) as quantity 
            FROM inventory_skus 
            WHERE inventory_skus.status=1 
            ORDER BY inventory_skus.name DESC;";
        $users = $this->Inventory_sku->query($user);
    
        // Fetch existing indent record
        $indentData = $this->Inventory_internal_indent->find('first', [
            'conditions' => ['indent_id' => $id],
            'recursive' => -1
        ]);
    
        $selected_location_id = $indentData['Inventory_internal_indent']['location_id'];
    
        $this->set(compact('users', 'id', 'locations', 'selected_location_id'));
    }

    public function update_internal_indent() 
    {
        $this->autoRender = false;
    
        $id = $this->Session->read('Auth.User.id');
        $name = $this->Session->read('Auth.User.name');
    
        if (isset($_POST['checkedData'])) {
            $checkeddatas = json_decode($_POST['checkedData'], true);
            $indentid = $_POST['indent_id'];
            $location_id = isset($_POST['location_id']) ? $_POST['location_id'] : null;
            $location_name = '';
    
            // Optional: fetch location name if not passed from frontend
            if (!empty($location_id)) {
                $loc = $this->Location->find('first', [
                    'conditions' => ['Location.id' => $location_id],
                    'fields' => ['Location.name'],
                    'recursive' => -1
                ]);
                $location_name = isset($loc['Location']['name']) ? $loc['Location']['name'] : '';
            }
    
            // Delete existing indent and items
            $this->Inventory_internal_indent_items->query("DELETE FROM inventory_internal_indent_items WHERE indent_id = " . (int)$indentid);
            $this->Inventory_internal_indent->query("DELETE FROM inventory_internal_indent WHERE indent_id = " . (int)$indentid);
    
            $amount = 0;
            $chk = false;
    
            foreach ($checkeddatas as $checkeddata) {
                $skuid = $checkeddata['id'];
                $price = $checkeddata['price'];
                $sku_name = $checkeddata['sku_name'];
                $sku_brand = $checkeddata['sku_brand'];
                $unit_name = $checkeddata['unit_name'];
                $unit_id = $checkeddata['unit_id'];
                $quantity = $checkeddata['sku_quantity'];
                
                $product_taxes=$this->Inventory_sku_tax->query("select SUM(tax_percentage) as total_tax from inventory_sku_tax where product_id='$skuid' ");
                $total_tax=round($product_taxes['0']['0']['total_tax'],2);
                $tax_value = round(($price*$quantity) * ($total_tax / 100),2);
                $skuamount=round(($price*$quantity) + $tax_value,2);
                
                if (!empty($quantity)) {
                    $itemData = array(
                        'indent_id' => $indentid,
                        'sku_id' => $skuid,
                        'sku_name' => $sku_name,
                        'sku_brand' => $sku_brand,
                        'sku_unit' => $unit_id,
                        'sku_unit_name' => $unit_name,
                        'sku_price' => $price,
                        'sku_quantity' => $quantity,
                        'sku_total_tax_percentage' => $total_tax,
                        'sku_total_tax_value' => $tax_value,
                        'sku_amount' => $skuamount
                    );
    
                    if ($this->Inventory_internal_indent_items->saveAll($itemData)) {
                        $chk = true;
                    } else {
                        $chk = false;
                        $this->Flash->error(__('Internal indent could not be updated. Please, try again.'));
                    }
    
                    // $productamount = $quantity * $price;
                    // $amount += $productamount;
                    $amount += ($skuamount);
                }
            }
    
            if ($chk) {
                $indentData = array(
                    'indent_id' => $indentid,
                    'created_by' => $id,
                    'created_by_name' => $name,
                    'location_id' => $location_id,
                    'location_name' => $location_name,
                    'total_amount' => $amount,
                    'is_updated' => 1
                );
    
                if ($this->Inventory_internal_indent->saveAll($indentData)) {
                    echo json_encode(['response_code' => 1, 'data' => 'Updated']);
                } else {
                    echo json_encode(['response_code' => 0, 'data' => 'Internal indent could not be updated. Please, try again.']);
                }
            } else {
                echo json_encode(['response_code' => 0, 'data' => 'Internal indent items could not be updated. Please, try again.']);
            }
        }
    }

    public function po_list()
    {
        // Redirect if not authenticated
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }

        $this->layout = "users";
        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $locationIds = $authUser['location_ids'] ?? '';

        // --- Default date range (last 1 month)
        $startDate = date('m/d/Y', strtotime('-1 month'));
        $endDate   = date('m/d/Y');
        $startDateFormatted = date('Y-m-d', strtotime('-1 month'));
        $endDateFormatted   = date('Y-m-d');

        // --- Handle custom date range from form
        if ($this->request->is(['post', 'put'])) {
            $daterange = $this->request->data['daterange'] ?? '';
            if (strpos($daterange, '-') !== false) {
                list($startRaw, $endRaw) = explode(" - ", $daterange);
                $startDate = trim($startRaw);
                $endDate   = trim($endRaw);
                $startDateFormatted = date('Y-m-d', strtotime($startDate));
                $endDateFormatted   = date('Y-m-d', strtotime($endDate));
            }
        }

        // --- Build store conditions
        $conditions2 = ['status' => 1];

        if ($userRole !== 'admin' && !empty($locationIds)) {
            // Normalize location IDs to array
            $userLocationIds = Hash::extract(
                ['ids' => is_array($locationIds) ? $locationIds : explode(',', $locationIds)],
                'ids.{n}'
            );
            $conditions2['id IN'] = array_map('trim', $userLocationIds);
        }

        // --- Fetch stores
        $stores = $this->Location->find('all', [
            'conditions' => $conditions2
        ]);

        // --- Build purchase order conditions
        $poConditions = [
            "created >=" => $startDateFormatted . " 00:00:01",
            "created <=" => $endDateFormatted . " 23:59:59",
        ];

        if ($userRole !== 'admin' && !empty($conditions2['id IN'])) {
            $poConditions['location_id IN'] = $conditions2['id IN'];
        }

        // --- Apply cashier search (overrides for all roles)
        if (!empty($this->request->data['Search']['cashier'])) {
            $cashierId = (int)$this->request->data['Search']['cashier'];
            $poConditions['location_id'] = $cashierId;
        }

        // --- Fetch purchase orders
        $purchaseOrders = $this->Inventory_purchase_order->find('all', [
            'conditions' => $poConditions,
            'order' => ['id' => 'DESC']
        ]);
        
        
        // $dbo = $this->Inventory_purchase_order->getDataSource();
        // $logs = $dbo->getLog();
        // $lastQuery = end($logs['log']);
        // debug($lastQuery);die;

        // --- Pass data to view
        $this->set(compact('stores', 'purchaseOrders'));
        $this->set('startdate', $startDate . ' - ' . $endDate);
    }

	
	public function create_po()
    {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "users";
    
        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_id'] ?? 0;
        $id = $authUser['id'];
        $name = $authUser['name'];
        
        // Vendors
        $vendoroptions = $this->Inventory_vendor->find('list', [
            'conditions' => ['Inventory_vendor.status' => 1],
            'fields' => ['id', 'name'],
            'order' => ['name' => 'ASC'],
            'recursive' => -1
        ]);
    
        // Locations
        $locationOptions = $this->Location->find('list', [
            'conditions' => ['status' => 1,'type' => 'dc'] + ($userRole !== 'admin' ? ['id' => $userLocationId] : []),
            'fields' => ['id', 'name'],
            'order' => ['name' => 'ASC'],
            'recursive' => -1
        ]);
    
        $this->set(compact('vendoroptions', 'locationOptions'));
    
        // Handle form submission
        if ($this->request->is(['post', 'put'])) {
            $data = $this->request->data['User'];
            $today = date('Y-m-d H:i:s');
            
            $locationId = (int) ($data['location'] ?? 0);
            $locationSave = $this->Auth->user('id'); // logged in user
            $locationdetail=$this->Location->find('first',array('conditions'=>array('Location.id'=>$locationId)));
	        $locationname=$locationdetail['Location']['name'];
            
            $indentId = (int) $data['indent'];
            $vendorId = (int) $data['vendor'];
            $prices = $this->request->data('prices') ?? [];
            $quantities = $this->request->data('quantity') ?? [];
            $vendor = $this->Inventory_vendor->find('first', [
                'conditions' => ['Inventory_vendor.id' => $vendorId],
                'recursive' => -1
            ]);
        
            if (empty($vendor)) {
                $this->Flash->error(__('Invalid vendor selected.'));
                return;
            }
            $approval_amount=approval_amount;
            
            if($vendor['Inventory_vendor']['po_approval_required']){
                $postatus = 1;
            }else{
                $postatus = 2;
            }
            
            do {
                $poId = str_pad(mt_rand(1, 9999999999), 10, '0', STR_PAD_LEFT);
            } while ($this->Inventory_purchase_order->hasAny(['p_o_id' => $poId]));
        
            $totalAmount = 0;
            
            foreach ($quantities as $skuId => $qty) {
                $qty = (float) $qty;
                if ($qty <= 0) continue;
        
                $price = isset($prices[$skuId]) ? (float) $prices[$skuId] : 0;
        
                $sku = $this->Inventory_sku->find('first', [
                    'conditions' => ['Inventory_sku.id' => $skuId],
                    'recursive' => -1
                ]);
                
                if (empty($sku)) continue;
                
                $product_taxes=$this->Inventory_sku_tax->query("select SUM(tax_percentage) as total_tax from inventory_sku_tax where product_id='$skuId' ");
                $total_tax=round($product_taxes['0']['0']['total_tax'],2);
                $tax_value = round(($price*$qty) * ($total_tax / 100),2);
                $skuamount=round(($price*$qty) + $tax_value,2);
                
                if($postatus==2){
                    $approved_quantity=$qty;
                    $approved_total_tax_value=$total_tax;
                    $approved_amount=$skuamount;
                }else{
                    $approved_quantity=0;
                    $approved_total_tax_value=0;
                    $approved_amount=0;
                }
                $itemData = [
                    'Inventory_purchase_order_item' => [
                        'p_o_id' => $poId,
                        'internal_indent_id' => $indentId,
                        'sku_id' => $skuId,
                        'sku_name' => $sku['Inventory_sku']['name'],
                        'sku_unit' => $sku['Inventory_sku']['unit'],
                        'sku_unit_name' => $sku['Inventory_sku']['unit_name'],
                        'sku_price' => $price,
                        'sku_quantity' => $qty,
                        'sku_total_tax_percentage' => $total_tax,
                        'sku_total_tax_value' => $tax_value,
                        'sku_amount' => $skuamount,
                        'approved_quantity' => $approved_quantity,
                        'approved_total_tax_value' => $approved_total_tax_value,
                        'approved_amount' => $approved_amount,
                        'status' => $postatus
                    ]
                ];
            
                if (!$this->Inventory_purchase_order_item->saveAll($itemData)) {
                    $this->Flash->error(__('Failed to save PO item.'));
                    return;
                }
                // print_r($itemData);
        
                $totalAmount += $skuamount;
            }
            
            if($totalAmount>$approval_amount){
                $postatus=1;
            }
            
            if($postatus==2){
                $approved_by_id=$id;
                $approved_by_name=$name;
                $approved_on=$today;
                $approved_amount=$totalAmount;
            }else{
                $approved_by_id=0;
                $approved_by_name='';
                $approved_on=NULL;
                $approved_amount=0;
            }
            $poData = [
                'Inventory_purchase_order' => [
                    'p_o_id' => $poId,
                    'vendor_id' => $vendorId,
                    'vendor_name' => $vendor['Inventory_vendor']['name'],
                    'internal_indent_id' => $indentId,
                    'location_id' => $locationId,
                    'location_name' => $locationname,
                    'total_amount' => $totalAmount,
                    'status' => $postatus,
                    'approved_by_id' => $approved_by_id,
                    'approved_by_name' => "$approved_by_name", // string needs quoting
                    'approved_on' => $approved_on,      // string needs quoting
                    'approved_amount' => $approved_amount,
                    
                ]
            ];
        
            if ($this->Inventory_purchase_order->saveAll($poData)) {
                $this->Flash->success(__('PO has been successfully created.'));
                return $this->redirect(['action' => 'po_list']);
            } else {
                $this->Flash->error(__('Failed to save PO. Please try again.'));
            }
        }
    }
    
    public function fetch_indents_by_location()
    {
        $this->autoRender = false;
        $this->layout = null;
    
        if ($this->request->is('ajax')) {
            $locationId = (int)$this->request->data('location_id');
            $this->loadModel('Inventory_internal_indent');
    
            $indents = $this->Inventory_internal_indent->find('list', [
                'conditions' => [
                    'location_id' => $locationId,
                    'status' => 1
                ],
                'fields' => ['indent_id', 'indent_id'], // Or add name if needed
                'order' => ['id' => 'DESC'],
                'recursive' => -1
            ]);
    
            echo json_encode($indents);
        }
    }
    public function fetch_indent_items() 
    {
        $this->autoRender = false; // Disable view rendering
        $indentId = $this->request->data('indent_id');
        
        $indent_items=$this->Inventory_internal_indent_items->query("SELECT * FROM `inventory_internal_indent_items`  where indent_id=$indentId");
        
        $x=1;
        foreach ($indent_items as $indent_item) {
            $vendorOptions .= "
            <tr>
                <td>".$x."</td>
                <td>".$indent_item['inventory_internal_indent_items']['sku_name']."</td>
                <td>".$indent_item['inventory_internal_indent_items']['sku_brand']."</td>
                <td>".$indent_item['inventory_internal_indent_items']['sku_unit_name']."</td>
                <td>".$indent_item['inventory_internal_indent_items']['sku_price']."</td>
                <td>".$indent_item['inventory_internal_indent_items']['sku_quantity']."</td>
            </tr>";
            $x++;
        }
        echo $vendorOptions;
    }

    public function fetch_vendor_items() 
    {
        $this->autoRender = false; // Disable view rendering
        $vendorId = $this->request->data('vendor_id');
        $indentId = $this->request->data('indent_id');
        
        $vendor_items=$this->Inventory_internal_indent_items->query("SELECT i.*,v.sku_price as price FROM `inventory_internal_indent_items` i JOIN `inventory_vendor_sku_served` v ON i.sku_id = v.skus_id WHERE i.indent_id = '$indentId' AND v.vendor_id = ".$vendorId);
        
        $x=1;
        foreach ($vendor_items as $vendor_item) {
            // print_r($vendor_item);exit;
            if($vendor_item['i']['sku_quantity']){
                $quantity=$vendor_item['i']['sku_quantity'];
            }else{
                $quantity=0;
            }
            $vendorOptions .= "
            <tr>
                <td>".$x."</td>
                <td>".$vendor_item['i']['sku_name']."</td>
                <td>".$vendor_item['i']['sku_brand']."</td>
                <td>".$vendor_item['i']['sku_unit_name']."</td>
                <td><input type='number' name='prices[".$vendor_item['i']['sku_id']."]' value='".$vendor_item['v']['price']."' class='form-control' step='0.01' /></td>
                <td><input type='number' name='quantity[".$vendor_item['i']['sku_id']."]' value='".$quantity."' class='form-control' step='0.01' /></td>
            </tr>";
            $x++;
        }
        echo $vendorOptions;
    }
    
    public function view_po()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		$id=$_REQUEST['id'];
    
        $indents = $this->Inventory_purchase_order->query("SELECT * FROM inventory_purchase_order where p_o_id=$id");
        $this->set(compact('indents'));
        
		$items = $this->Inventory_purchase_order_item->query("SELECT * FROM inventory_purchase_order_items where p_o_id=$id and status!=0");
        
        $this->set(compact('items'));
        
        
	}
	
	public function edit_po()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		$id=$_REQUEST['id'];
    
        $purchase_orders = $this->Inventory_purchase_order->query("SELECT * FROM inventory_purchase_order where p_o_id=$id");
        
        $internal_indent_id=$purchase_orders[0]['inventory_purchase_order']['internal_indent_id'];
        $vendorId=$purchase_orders[0]['inventory_purchase_order']['vendor_id'];
        
		$vendor_items=$this->Inventory_internal_indent_items->query("SELECT i.*,v.sku_price as vprice,(SELECT sku_price FROM `inventory_purchase_order_items` WHERE p_o_id=$id and internal_indent_id=i.indent_id and sku_id=i.sku_id) AS psku_price,(SELECT sku_quantity FROM `inventory_purchase_order_items` WHERE p_o_id=$id and internal_indent_id=i.indent_id and sku_id=i.sku_id) AS psku_quantity FROM `inventory_internal_indent_items` i JOIN `inventory_vendor_sku_served` v ON i.sku_id = v.skus_id WHERE i.indent_id = '$internal_indent_id' AND v.vendor_id =$vendorId");
        
        $this->set(compact('vendor_items'));
        $this->set(compact('purchase_orders'));
        
        if ($this->request->is(array('post', 'put'))) {
        
            $indent_id = $this->data['User']['indent'];
            $p_o_id = $this->data['User']['p_o_id'];
            $prices=$this->data['prices'];
            $quantities=$this->data['quantity'];
            
            $amount=0;
            $productamount=0;
    	    
    	    $this->Inventory_purchase_order_item->query("DELETE FROM inventory_purchase_order_items WHERE p_o_id =". $p_o_id);
           
            foreach ($quantities as $sku_id => $quantity) {
                if ($quantity != 0) {
                    $price = isset($prices[$sku_id]) ? $prices[$sku_id] : 0;
                    $sku_details = $this->Inventory_sku->query("SELECT * FROM inventory_skus where id=$sku_id");
                    
                    $product_taxes=$this->Inventory_sku_tax->query("select SUM(tax_percentage) as total_tax from inventory_sku_tax where product_id='$sku_id' ");
                    $total_tax=round($product_taxes['0']['0']['total_tax'],2);
                    $tax_value = round(($price*$quantity) * ($total_tax / 100),2);
                    $skuamount=round(($price*$quantity) + $tax_value,2);
                    
                    
                    $data['Inventory_purchase_order_item']=array(
            			'p_o_id'=>$p_o_id,
            			'internal_indent_id'=>$indent_id,
            			'sku_id'=>$sku_id,
            			'sku_name'=>$sku_details[0]['inventory_skus']['name'],
            			'sku_unit'=>$sku_details[0]['inventory_skus']['unit'],
            			'sku_unit_name'=>$sku_details[0]['inventory_skus']['unit_name'],
            			'sku_price'=>$price,
            			'sku_quantity'=>$quantity,
            			'sku_total_tax_percentage' => $total_tax,
                        'sku_total_tax_value' => $tax_value,
                        'sku_amount' => $skuamount
            		);
            		if($this->Inventory_purchase_order_item->saveAll($data['Inventory_purchase_order_item']))
            		{
            		    
            		}else{
            		    $this->Flash->error(__('PO Items could not be saved. Please, try again.'));
            		}
                    // $productamount=$quantity*$price;
        	        $amount=$amount+$skuamount;
            	}
            }
            $approval_amount=approval_amount;
            if($amount>$approval_amount){
                $postatus=1;
            }else{
                $postatus=2;
            }
            
            $this->Inventory_purchase_order->query("UPDATE inventory_purchase_order SET status='$postatus',total_amount='$amount',is_updated=1,sync = 0 WHERE p_o_id =". $p_o_id);
       	    $this->Inventory_purchase_order_item->query("UPDATE inventory_purchase_order_items SET status='$postatus',sync = 0 WHERE p_o_id =". $p_o_id);
       	    $this->Flash->success(__('PO has been Updated.'));
	        return $this->redirect(array('action' => 'po_list'));
        }
    }
    
	public function process_po() 
    {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $poid = $this->request->data['_id'];
            $items = $this->request->data['_items']; // array of item_id and quantity
        
            $today = date('Y-m-d H:i:s');
            $id = $this->Session->read('Auth.User.id');
        
            // Get user name safely
            $user = $this->User->find('first', [
                'conditions' => ['User.id' => $id],
                'fields' => ['User.name'],
                'recursive' => -1
            ]);
            $name = $user['User']['name'];
        
            $amount = 0;
        
            foreach ($items as $item) {
                $itemId = (int)$item['item_id'];
                $quantity = (float)$item['quantity'];
        
                // Fetch SKU ID from PO item
                $poItem = $this->Inventory_purchase_order_item->find('first', [
                    'conditions' => ['Inventory_purchase_order_item.id' => $itemId],
                    'fields' => ['Inventory_purchase_order_item.sku_id','sku_price'],
                    'recursive' => -1
                ]);
                $sku_id = $poItem['Inventory_purchase_order_item']['sku_id'];
                $price = $poItem['Inventory_purchase_order_item']['sku_price'];
        
                // Get total tax percentage for SKU
                $taxResult = $this->Inventory_sku_tax->query(
                    "SELECT SUM(tax_percentage) AS total_tax FROM inventory_sku_tax WHERE product_id = '$sku_id'"
                );
                $total_tax = round($taxResult[0][0]['total_tax'], 2);
        
                // Calculate tax & total amount
                $tax_value = round(($price * $quantity) * ($total_tax / 100), 2);
                $skuamount = round(($price * $quantity) + $tax_value, 2);
        
                // Update purchase order item
                $this->Inventory_purchase_order_item->updateAll(
                    [
                        'Inventory_purchase_order_item.processed_quantity' => $quantity,
                        'Inventory_purchase_order_item.processed_total_tax_value' => $tax_value,
                        'Inventory_purchase_order_item.processed_amount' => $skuamount,
                        'Inventory_purchase_order_item.status' => 3,
                        'Inventory_purchase_order_item.sync' => 0
                    ],
                    [
                        'Inventory_purchase_order_item.id' => $itemId,
                        'Inventory_purchase_order_item.p_o_id' => $poid
                    ]
                );
        
                $amount += $skuamount;
            }
        
            // Update main purchase order
            $this->Inventory_purchase_order->updateAll(
                [
                    'Inventory_purchase_order.status' => 3,
                    'Inventory_purchase_order.processed_by_id' => $id,
                    'Inventory_purchase_order.processed_by_name' => "'$name'", // string needs quoting
                    'Inventory_purchase_order.processed_on' => "'$today'",      // string needs quoting
                    'Inventory_purchase_order.processed_amount' => $amount,
                    'Inventory_purchase_order.sync' => 0
                ],
                [
                    'Inventory_purchase_order.p_o_id' => $poid
                ]
            );
        
            echo json_encode(['status' => true]);
            exit;
        }

    }
    
    public function approve_po() 
    {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $poid = $this->request->data['_id'];
            $items = $this->request->data['_items']; // array of item_id and quantity
        
            $today = date('Y-m-d H:i:s');
            $id = $this->Session->read('Auth.User.id');
        
            // Get user name safely
            $user = $this->User->find('first', [
                'conditions' => ['User.id' => $id],
                'fields' => ['User.name'],
                'recursive' => -1
            ]);
            $name = $user['User']['name'];
        
            $amount = 0;
        
            foreach ($items as $item) {
                $itemId = (int)$item['item_id'];
                $quantity = (float)$item['quantity'];
        
                // Fetch SKU ID from PO item
                $poItem = $this->Inventory_purchase_order_item->find('first', [
                    'conditions' => ['Inventory_purchase_order_item.id' => $itemId],
                    'fields' => ['Inventory_purchase_order_item.sku_id','sku_price'],
                    'recursive' => -1
                ]);
                $sku_id = $poItem['Inventory_purchase_order_item']['sku_id'];
                $price = $poItem['Inventory_purchase_order_item']['sku_price'];
        
                // Get total tax percentage for SKU
                $taxResult = $this->Inventory_sku_tax->query(
                    "SELECT SUM(tax_percentage) AS total_tax FROM inventory_sku_tax WHERE product_id = '$sku_id'"
                );
                $total_tax = round($taxResult[0][0]['total_tax'], 2);
        
                // Calculate tax & total amount
                $tax_value = round(($price * $quantity) * ($total_tax / 100), 2);
                $skuamount = round(($price * $quantity) + $tax_value, 2);
        
                // Update purchase order item
                $this->Inventory_purchase_order_item->updateAll(
                    [
                        'Inventory_purchase_order_item.approved_quantity' => $quantity,
                        'Inventory_purchase_order_item.approved_total_tax_value' => $tax_value,
                        'Inventory_purchase_order_item.approved_amount' => $skuamount,
                        'Inventory_purchase_order_item.status' => 2,
                        'Inventory_purchase_order_item.sync' => 0
                    ],
                    [
                        'Inventory_purchase_order_item.id' => $itemId,
                        'Inventory_purchase_order_item.p_o_id' => $poid
                    ]
                );
        
                $amount += $skuamount;
            }
        
            // Update main purchase order
            $this->Inventory_purchase_order->updateAll(
                [
                    'Inventory_purchase_order.status' => 2,
                    'Inventory_purchase_order.approved_by_id' => $id,
                    'Inventory_purchase_order.approved_by_name' => "'$name'", // string needs quoting
                    'Inventory_purchase_order.approved_on' => "'$today'",      // string needs quoting
                    'Inventory_purchase_order.approved_amount' => $amount,
                    'Inventory_purchase_order.sync' => 0
                ],
                [
                    'Inventory_purchase_order.p_o_id' => $poid
                ]
            );
        
            echo json_encode(['status' => true]);
            exit;
        }

    }
    
    public function po_change_status() 
    {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $userId = $this->request->data['_id'];
        
            // Update user status
            $this->Inventory_purchase_order->id = $userId;
            $newStatus = $this->Inventory_purchase_order->field('status') == 1 ? 0 : 1;
            if ($this->Inventory_purchase_order->save(['status' => $newStatus,'sync' => 0])) {
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }
    
    public function stockin()
    {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_id'] ?? 0;
    
        $this->layout = "users";
        $id = $_POST['po'] ?? null;
        $this->set(compact('id'));
    
        if ($id) {
            // Fetch PO
            $poQuery = "SELECT * FROM inventory_purchase_order WHERE p_o_id = $id";
            $indents = $this->Inventory_purchase_order->query($poQuery);
    
            if (empty($indents)) {
                $this->set('po_error', 'PO Not Found'); // trigger JS alert
                return;
            }
    
            $po = $indents[0]['inventory_purchase_order'];
            
            if ($po['status'] == 4) {
                $this->set('po_error', 'PO Already Stocked IN');
                return;
            } elseif ($po['status'] < 3) {
                $this->set('po_error', 'PO is not Processed');
                return;
            } elseif ($po['status'] < 2) {
                $this->set('po_error', 'PO is not Approved');
                return;
            }

    
            if ($userRole != 'admin' && $po['location_id'] != $userLocationId) {
                $this->set('po_error', 'Location Not Found'); // trigger JS alert
                return;
            }
            // print_r($indents);exit;
            // All good, load items
            $items = $this->Inventory_purchase_order_item->query(
                "SELECT * FROM inventory_purchase_order_items WHERE p_o_id = $id AND status = 3"
            );
            $this->set(compact('indents', 'items'));
        }
    }

	public function stockin_po() 
    {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $poid = $this->request->data['_id'];
            $invoice = trim($this->request->data['_invoice']);
            $quantities = $this->request->data['_quantities']; // associative array: sku_id => quantity
            $today = date('Y-m-d H:i:s');
            $id = $this->Session->read('Auth.User.id');
            
            $poQuery = "SELECT * FROM inventory_purchase_order WHERE p_o_id = $poid";
            $indents = $this->Inventory_purchase_order->query($poQuery);
            $store_id=$indents[0]['inventory_purchase_order']['location_id'];
            $name=$indents[0]['inventory_purchase_order']['location_name'];
            // Generate unique stockin_id
            do {
                $txnid = rand(1, 9);
                for ($i = 0; $i < 10; $i++) {
                    $txnid .= rand(0, 9);
                }
    
                $existing = $this->Inventory_purchase_order->find('first', [
                    'conditions' => ['stockin_id' => $txnid]
                ]);
            } while ($existing);
    
            // $id = $this->Session->read('Auth.User.id');
            // $username = $this->User->query("SELECT name,location_id FROM users WHERE id = $id");
            // $name = $username[0]['users']['name'];
            // $store_id = $username[0]['users']['location_id'];
            
            $stockin_skus = $this->Inventory_purchase_order_item->find('all', [
                'conditions' => ['p_o_id' => $poid]
            ]);
            // print_r($stockin_skus);exit;
            $amount=0;
            foreach ($stockin_skus as $stockin_sku) {
                $sku = $stockin_sku['Inventory_purchase_order_item'];
                $sku_id = $sku['sku_id'];
                
                if (isset($quantities[$sku_id])) {
                    $qty = floatval($quantities[$sku_id]);
                    
                    $poItem = $this->Inventory_purchase_order_item->find('first', [
                        'conditions' => ['Inventory_purchase_order_item.sku_id' => $sku_id,'Inventory_purchase_order_item.p_o_id' => $poid],
                        'fields' => ['sku_price'],
                        'recursive' => -1
                    ]);
                    $price = $poItem['Inventory_purchase_order_item']['sku_price'];
            
                    $product_taxes=$this->Inventory_sku_tax->query("select SUM(tax_percentage) as total_tax from inventory_sku_tax where product_id='$sku_id' ");
                    $total_tax=round($product_taxes['0']['0']['total_tax'],2);
                    $tax_value = round(($price*$qty) * ($total_tax / 100),2);
                    $skuamount=round(($price*$qty) + $tax_value,2);
                    
                    // Update purchase order item
                    $this->Inventory_purchase_order_item->updateAll(
                        ['status' => 4, 'sync' => 0, 'stockin_quantity' => $qty, 'stockin_total_tax_value' => $tax_value, 'stockin_amount' => $skuamount],
                        ['p_o_id' => $poid, 'sku_id' => $sku_id]
                    );
                    $amount=$amount+$skuamount;
                    
                    $ledgerprevdetails = $this->Stock_ledger->find('first', [
                        'conditions' => ['sku_id' => $sku_id,'type'=>'DC','item_type'=>'SKU','store_id'=>$store_id],
                        'fields' => ['actual_balance'],
                        'order' => ['id DESC'],
                        'recursive' => -1
                    ]);
                    
                    $ledger_prev_quantity = !empty($ledgerprevdetails['Stock_ledger']['actual_balance']) 
                        ? $ledgerprevdetails['Stock_ledger']['actual_balance'] 
                        : 0;
                    
                    $newQuantity = $qty + $ledger_prev_quantity;
                    
                    $ledgerData['Stock_ledger'] = [
                            'store_id'        => $store_id,
                            'sku_id'          => $sku_id,
                            'sku_name'        => $sku['sku_name'],
                            'sku_price'       => $sku['sku_price'],
                            'unit_id'         => $sku['sku_unit'],
                            'unit_name'       => $sku['sku_unit_name'],
                            'record_id'       => $txnid,
                            'record_type'     => 'stockin',
                            'quantity'        => $qty,
                            'balance_stock'   => $newQuantity,
                            'actual_balance'  => $newQuantity,
                            'quantity_type'   => 'credit',
                            'type'            => 'DC',
                            'created'         => date('Y-m-d H:i:s')
                    ];
    				$this->Stock_ledger->saveAll($ledgerData['Stock_ledger']);
                    
                }
            }
            
            // Update purchase order
            $this->Inventory_purchase_order->query("UPDATE inventory_purchase_order SET 
                stockin_id = '$txnid',
                status = 4,
                stockin_on = '$today',
                stockin_by_id = $id,
                stockin_by_name = '$name',
                stockin_amount = '$amount',
                invoice_no = '$invoice',
                sync = 0 
                WHERE p_o_id = '$poid'");
    
            echo json_encode(['status' => true]);
        }
    }
    
    public function po_pdf() {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "login"; // or use 'ajax' or a dedicated PDF layout
    
        if ($this->request->is(['post', 'put'])) {
            $po_id = $this->request->data['Report']['poid'];
            // Secure: Use bound parameters
            $indents = $this->Inventory_purchase_order->query(
                "SELECT * FROM inventory_purchase_order 
                 JOIN inventory_vendors ON inventory_purchase_order.vendor_id = inventory_vendors.id 
                 WHERE inventory_purchase_order.p_o_id = ?", 
                [$po_id]
            );
    
            $items = $this->Inventory_purchase_order_item->query(
                "SELECT * FROM inventory_purchase_order_items 
                 WHERE p_o_id = ? AND status != 0", 
                [$po_id]
            );
            
            $location_id=$indents[0]['inventory_purchase_order']['location_id'];
    
            // Get location details - default static for now
            $locationdetail = $this->Location->find('first', [
                'conditions' => ['Location.id' => $location_id]
            ]);
    
            // Send data to the view
            $this->set(compact('po_id', 'indents', 'items', 'locationdetail'));
    
            // Optional: Force specific view if needed
            $this->render('po_pdf'); // e.g., pdf_template.ctp
        }
    }

    
    public function waiter_list() {
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		$startDate = date('m/d/Y', strtotime('-12 months'));
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }   
        
        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;
        
        $locationCondition = ''; // always filter by active locations
        if ($userRole !== 'admin') {
            $locationCondition = "AND location_id IN (" . $userLocationId . ")";
        }
		
		$users = $this->Order_waiter->query("SELECT * FROM order_waiters where created between '$startdate 00:00:01' and  '$enddate 23:59:59' $locationCondition ORDER BY id desc");
        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        
		$this->set(compact('users'));

	}
	
	public function create_waiter()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		$authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;
        
        $locationCondition = ['status' => 1];
        
        if ($userRole !== 'admin') {
            $userLocationIds = is_array($userLocationId) ? $userLocationId : [$userLocationId];
            $locationCondition['id'] = $userLocationIds; // CakePHP automatically handles IN
        }
		$locations=$this->Location->find('all',array('conditions'=>array($locationCondition)));
	    $this->set(compact('locations'));
		
		if ($this->request->is(array('post', 'put'))) {
            
            $name = $this->data['User']['name'];
            if($name==''){
                $this->Flash->error(__('Name could not be Blank'));
                return $this->redirect(array('action' => 'create_waiter'));
            }
            $phone = $this->data['User']['phone'];
            $pin=$this->data['User']['pin'];
            $pin_req = $this->data['User']['pin_req'];
            
            $namecheck=$this->Order_waiter->find('all',array('conditions'=>array('name'=>$name)));
            if(!empty($namecheck)){
	            $this->Flash->error(__('Waiter Name already exist.'));
	            return $this->redirect(array('action' => 'waiter_list'));
	        }
            $phonecheck=$this->Order_waiter->find('all',array('conditions'=>array('phone'=>$phone)));
            if(!empty($phonecheck)){
	            $this->Flash->error(__('Waiter Phone already exist.'));
	            return $this->redirect(array('action' => 'waiter_list'));
	        }
	        $pincheck=$this->Order_waiter->find('all',array('conditions'=>array('pin_number'=>$pin)));
            if(!empty($pincheck)){
	            $this->Flash->error(__('Waiter Pin already exist.'));
	            return $this->redirect(array('action' => 'waiter_list'));
	        }
	        $location_id =$this->data['User']['location'];
            $locationdetail=$this->Location->find('first',array('conditions'=>array('Location.id'=>$location_id)));
	        $locationname=$locationdetail['Location']['name'];
            
            $data['Order_waiter']=array(
    			'name'=>$name,
    			'phone'=>$phone,
    			'location_id'=>$location_id,
    			'location_name'=>$locationname,
    			'pin_number'=>$pin,
    			'is_pin_required'=>$pin_req
    		);
    	    
    	    if($this->Order_waiter->saveAll($data['Order_waiter']))
    		{
    		    $this->Flash->success(__('Waiter has been saved.'));
				return $this->redirect(array('action' => 'waiter_list'));
			} else {
				$this->Flash->error(__('Waiter could not be saved. Please, try again.'));
			}
		}
	}
	
	public function waiter_change_status() {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $Id = $this->request->data['_id'];
            
            $this->Order_waiter->id = $Id;
            
            $currentStatus = $this->Order_waiter->field('status', ['id' => $Id]);
            $newStatus = in_array($currentStatus, [1]) ? 0 : 1;
            

            if ($this->Order_waiter->save(['status' => $newStatus,'sync' => 0])) {
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }
    
    public function edit_waiter()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		
		if ($this->data['User']['id']!='') {
		  
		    $id = $this->data['User']['id'];
            $name = $this->data['User']['name'];
            $phone = $this->data['User']['phone'];
            $pin = $this->data['User']['pin'];
            $is_pin_required = $this->data['User']['pin_req'];
            
            $phonecheck=$this->Order_waiter->find('all',array('conditions'=>array('phone'=>$phone,'id !='=>$id)));
            if(!empty($phonecheck)){
	            $this->Flash->error(__('Waiter Phone already exist.'));
	            return $this->redirect(array('action' => 'waiter_list'));
	        }
	        $pincheck=$this->Order_waiter->find('all',array('conditions'=>array('pin_number'=>$pin,'id !='=>$id)));
            if(!empty($pincheck)){
	            $this->Flash->error(__('Waiter Pin already exist.'));
	            return $this->redirect(array('action' => 'waiter_list'));
	        }
	        $location = $this->data['User']['location'];
            $locationdetail=$this->Location->find('first',array('conditions'=>array('Location.id'=>$location)));
	        $locationname=$locationdetail['Location']['name'];
            
            $this->Order_table->query("UPDATE order_waiters SET name ='$name',phone='$phone',location_id ='$location',location_name='$locationname',pin_number='$pin',is_pin_required='$is_pin_required',sync = 0 WHERE id =". $id);
            $this->Flash->success(__('Waiter has been Updated.'));
            return $this->redirect(array('action' => 'waiter_list'));
		}else{
		    $id=$_REQUEST['id'];
		    
            $authUser = $this->Session->read('Auth.User');
            $userRole = $authUser['role'] ?? '';
            $userLocationId = $authUser['location_ids'] ?? 0;


		    $userdetail=$this->Order_waiter->find('first',array('conditions'=>array('Order_waiter.id'=>$id)));
	        $this->set(compact('userdetail'));
	        
	        $locationCondition = ['status' => 1];
        
            if ($userRole !== 'admin') {
                $userLocationIds = is_array($userLocationId) ? $userLocationId : [$userLocationId];
                $locationCondition['id'] = $userLocationIds; // CakePHP automatically handles IN
            }
        	$locations=$this->Location->find('all',array('conditions'=>array($locationCondition)));
            $this->set(compact('locations'));
	  	}
		
    }
    
    public function stock_transfer()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		$startDate = date('m/d/Y', strtotime('-12 months'));
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
		}else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }   
        
		$users = $this->Stock_transfer->query("SELECT * FROM stock_transfers where status=1 and created between '$startdate 00:00:01' and  '$enddate 23:59:59' ORDER BY id desc");
        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        
		$this->set(compact('users'));

	}
	
	public function create_stock_tranfer()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        $this->layout = "users";
	    
	    $userchk="SELECT * FROM `users`  where role='kitchen' and status=1"; 
        $transferto=$this->User->query($userchk);
        
        
	    $user="SELECT * FROM `inventory_skus`  where inventory_skus.status=1 order by inventory_skus.name desc"; 
        $users=$this->Inventory_sku->query($user);
        $this->set(compact('users','transferto'));
        
    }
    
    public function add_stock_transfer() 
    {
        $this->autoRender = false; // Disable view rendering
        
        $id = $this->Session->read('Auth.User.id');
        $name = $this->Session->read('Auth.User.name');
            
        if(isset($_POST['checkedData'])){
    	    $checkeddatas=JSON_decode($_POST['checkedData'],true);
    	    $transfer_from=$_POST['tranferfrom'];
    	    $transfer_to=$_POST['transferto'];
    	    do {
    	        $txnid = rand(1, 9);
                for ($i = 0; $i < 10; $i++) {
                    $txnid .= rand(0, 9);
                }
                
                $existingOTP = $this->Stock_transfer->find('first', array(
                    'conditions' => array(
                        'transfer_id' => $txnid
                    )
                ));
               
            } while ($existingOTP); // Continue generating OTP until it doesn't exist
            
            $amount=0;
            $productamount=0;
    	    foreach($checkeddatas as $checkeddata){
    	        $skuid=$checkeddata['id'];
    	        $price=$checkeddata['price'];
    	        $sku_name=$checkeddata['sku_name'];
    	        $sku_brand=$checkeddata['sku_brand'];
    	        $unit_name=$checkeddata['unit_name'];
    	        $unit_id=$checkeddata['unit_id'];
    	        $quantity=$checkeddata['sku_quantity'];
    	        
    	        if(isset($quantity)){
            
        	        $data['Stock_transfer_item']=array(
            			'transfer_id'=>$txnid,
            			'sku_id'=>$skuid,
            			'sku_name'=>$sku_name,
            			'sku_brand'=>$sku_brand,
            			'sku_unit'=>$unit_id,
            			'sku_unit_name'=>$unit_name,
            			'sku_price'=>$price,
            			'sku_quantity'=>$quantity
            		);
            		
            	    if($this->Stock_transfer_item->saveAll($data['Stock_transfer_item']))
            		{
            		    
            		    $id = $this->Session->read('Auth.User.id');
                        $username = $this->User->query("SELECT location_id FROM users WHERE id = $id");
                        $store_id = $username[0]['users']['location_id'];
                        
                        
            		    $ledgerprevdetails = $this->Stock_ledger->find('first', [
                            'conditions' => ['sku_id' => $skuid,'store_id'=>$store_id,'type'=>'DC','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-$quantity;
                        
                        $ledgerData['Stock_ledger'] = [
                                'store_id'        => $store_id,
                                'sku_id'          => $skuid,
                                'sku_name'        => $sku_name,
                                'sku_price'       => $price,
                                'unit_id'         => $unit_id,
                                'unit_name'       => $unit_name,
                                'record_id'       => $txnid,
                                'record_type'     => 'stock_transfer_to_kitchen',
                                'quantity'        => $quantity,
                                'balance_stock'   => $newQuantity,
                                'actual_balance'  => $newQuantity,
                                'quantity_type'   => 'debit',
                                'type'            => 'DC',
                                'created'         => date('Y-m-d H:i:s')
                        ];
        				if(!$this->Stock_ledger->saveAll($ledgerData['Stock_ledger'])){
                		    $chk=false;
                		    $this->Flash->error(__('Transfer error in ledger . Please, try again.'));
                		}
                		
                		$usernamekitchen = $this->User->query("SELECT location_id FROM users WHERE role = 'kitchen' and location_id='$store_id'");
                        $kithcen_store_id = $usernamekitchen[0]['users']['location_id'];
                        
                        $kithcneledgerprevdetails = $this->Stock_ledger->find('first', [
                            'conditions' => ['sku_id' => $skuid,'store_id'=>$kithcen_store_id,'type'=>'KITCHEN'],
                            'fields' => ['actual_balance'],
                            'order' => ['id DESC'],
                            'recursive' => -1
                        ]);
                        
                        $kitchen_ledger_prev_quantity = !empty($kithcneledgerprevdetails['Stock_ledger']['actual_balance']) 
                            ? $kithcneledgerprevdetails['Stock_ledger']['actual_balance'] 
                            : 0;
                        
                        $kithcnenewQuantity = $kitchen_ledger_prev_quantity+$quantity;
                        
                        $kithcneledgerData['Stock_ledger'] = [
                                'store_id'        => $kithcen_store_id,
                                'sku_id'          => $skuid,
                                'sku_name'        => $sku_name,
                                'sku_price'       => $price,
                                'unit_id'         => $unit_id,
                                'unit_name'       => $unit_name,
                                'record_id'       => $txnid,
                                'record_type'     => 'stock_transfer_from_warehouse',
                                'quantity'        => $quantity,
                                'balance_stock'   => $kithcnenewQuantity,
                                'actual_balance'  => $kithcnenewQuantity,
                                'quantity_type'   => 'credit',
                                'type'            => 'KITCHEN',
                                'created'         => date('Y-m-d H:i:s')
                        ];
        				if(!$this->Stock_ledger->saveAll($kithcneledgerData['Stock_ledger'])){
                		    $chk=false;
                		    $this->Flash->error(__('Transfer error in ledger . Please, try again.'));
                		}
            		    $chk=true;   
            		}else{
            		    $chk=false;
            		    $this->Flash->error(__('Transfer could not be saved. Please, try again.'));
            		}
    	        }
    	        $productamount=$quantity*$price;
    	        $amount=$amount+$productamount;
    	    }

        	if($chk){
        	    $data['Stock_transfer']=array(
        			'transfer_id'=>$txnid,
        			'transfer_from'=>$transfer_from,
        			'transfer_to'=>$transfer_to,
        			'created_by'=>$id
        		);
        		
        	    if($this->Stock_transfer->saveAll($data['Stock_transfer']))
        		{
                    $responseArray = array('response_code' => 1, 'data' => 'saved');
                    echo json_encode($responseArray);
        		}else{
        		    $responseArray = array('response_code' => 0, 'data' => 'Transfer Items could not be saved. Please, try again.');
                    echo json_encode($responseArray);
        		}
        	}else{
        	    $responseArray = array('response_code' => 0, 'data' => 'Transfer Items could not be saved. Please, try again.');
                echo json_encode($responseArray);
        	}
        }
    }
    
    public function view_stock_transfer()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		$id=$_REQUEST['id'];
    
        $transfers = $this->Stock_transfer->query("SELECT * FROM stock_transfers where transfer_id=$id");
        $this->set(compact('transfers'));
        
		$items = $this->Stock_transfer_item->query("SELECT * FROM stock_transfer_items where transfer_id=$id and status!=0");
        
        $this->set(compact('items'));
    }
    
    public function delete_stock_transfer() {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $userId = $this->request->data['_id'];
    
            // Update user status
            $this->Stock_transfer->id = $userId;
            if ($this->Stock_transfer->save(['status' => 0,'sync' => 0])) {
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }
    
    public function kds() 
    {
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		$startDate = date('m/d/Y', strtotime('-12 months'));
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }   
        
        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;
        
        $conditions = [
            'created BETWEEN ? AND ?' => [$startdate . ' 00:00:01', $enddate . ' 23:59:59'],
            'status' => 1
        ];
        
        if ($userRole !== 'admin') {
            // Add raw SQL condition as a string
            $conditions[] = "store_id IN ($userLocationId)";
        }
        
        $users = $this->Pos_printer->find('all', [
            'conditions' => $conditions,
            'order' => ['id' => 'DESC']
        ]);

        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        
		$this->set(compact('users'));

	}
	
	public function create_kds()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
	    
	    $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;
        
        $locationCondition = ['status' => 1]; // always filter by active locations
        
        if ($userRole !== 'admin') {
            // If $userLocationId is a single ID, make it an array
            $userLocationIds = is_array($userLocationId) ? $userLocationId : [$userLocationId];
            $locationCondition['id'] = $userLocationIds; // CakePHP automatically handles IN
        }
        
		$locations=$this->Location->find('all',array('conditions'=>$locationCondition));
	    $this->set(compact('locations'));
		if ($this->request->is(array('post', 'put'))) {
            
            $name = $this->data['User']['name'];
            if($name==''){
                $this->Flash->error(__('The Name could not be Blank'));
                return $this->redirect(array('action' => 'create_kds'));
            }
            
            $ip = $this->data['User']['ip'];
            $location = $this->data['User']['location'];
            $locationdetail=$this->Location->find('first',array('conditions'=>array('Location.id'=>$location)));
	        $locationname=$locationdetail['Location']['name'];
            
            $data['Pos_printer']=array(
    			'name'=>$name,
    			'ip'=>$ip,
    			'store_id'=>$location,
    			'store_name'=>$locationname
    	    );
    	    
    	    if($this->Pos_printer->save($data['Pos_printer']))
    		{
    		    $kds_id = $this->Pos_printer->id;
                // Update the same record with kds_id
                $this->Pos_printer->id = $kds_id;
                $this->Pos_printer->saveField('kds', $kds_id);
        
    		    $this->Flash->success(__('Kds has been saved.'));
				return $this->redirect(array('action' => 'kds'));
			} else {
				$this->Flash->error(__('kds could not be saved. Please, try again.'));
			}
		}
	}
	
	public function kds_change_status() 
	{
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $Id = $this->request->data['_id'];
            
            $this->Pos_printer->id = $Id;
            $newStatus = $this->Pos_printer->field('status') == 1 ? 0 : 1;
            
            if ($this->Pos_printer->save(['status' => $newStatus,'sync' => 0])) {
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }
    
    public function fetch_pro_options() {
        $this->autoRender = false;
        $this->response->type('json');
    
        $products = $this->Catalog_product->find('all', [
            'conditions' => ['Catalog_product.package' => 0, 'Catalog_product.status' => 1],
            'fields' => ['Catalog_product.id', 'Catalog_product.name', 'Catalog_product.unit_name', 'Catalog_product.price'],
            'order' => ['Catalog_product.name' => 'asc']
        ]);
    
        $data = [];
        foreach ($products as $product) {
            $data[] = [
                'id' => $product['Catalog_product']['id'],
                'name' => $product['Catalog_product']['name'],
                'price' => $product['Catalog_product']['price'],
                'unit_name' => $product['Catalog_product']['unit_name']
            ];
        }
    
        echo json_encode(['response_code' => 1, 'data' => $data]);
        exit;
    }
    
    public function stock_level() {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "users";
    
        $stocklevel_startdate = $stocklevel_enddate = $skuledger_startdate = $skuledger_enddate = date('Y-m-d');
        $sku_id = null;
    
        if ($this->request->is(['post', 'put'])) {
            if (isset($this->request->data['submit_stocklevel'])) {
                $daterange = $this->request->data['stocklevel_daterange'] ?? '';
                $dates = explode(" - ", $daterange);
                if (count($dates) === 2) {
                    $stocklevel_startdate = date('Y-m-d', strtotime(trim($dates[0])));
                    $stocklevel_enddate = date('Y-m-d', strtotime(trim($dates[1])));
                }
            }
    
            if (isset($this->request->data['submit_skutransactions'])) {
                $daterange = $this->request->data['daterange'] ?? '';
                $dates = explode(" - ", $daterange);
                if (count($dates) === 2) {
                    $skuledger_startdate = date('Y-m-d', strtotime(trim($dates[0])));
                    $skuledger_enddate = date('Y-m-d', strtotime(trim($dates[1])));
                }
                $sku_id = $this->request->data['SkuLedger']['sku'] ?? null;
            }
            
        }
        $id = $this->Session->read('Auth.User.id');
        
        
        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;
        $conditions = [
            'status' => 1,
            'type'   => 'DC'
        ];
        
        if ($userRole !== 'admin' && !empty($userLocationId)) {
            $userLocationIds = Hash::extract(
                ['ids' => is_array($userLocationId) ? $userLocationId : explode(',', $userLocationId)],
                'ids.{n}'
            );
            $conditions['id IN'] = array_map('trim', $userLocationIds);
            $store_id = implode(',', $userLocationIds);
        }
        else{
            $username = $this->User->query("SELECT location_id FROM users WHERE id = $id");
            $store_id = $username[0]['users']['location_id'];
        }

        if (!empty($this->request->data['StockLevel']['cashier'])) {
            $store_id = $this->request->data['StockLevel']['cashier'];
            $transactions = $this->Stock_ledger->query("
                SELECT sl1.sku_id,sl1.sku_price,sl1.sku_name,sl1.unit_name, sl1.actual_balance
                FROM stock_ledger sl1
                INNER JOIN (
                    SELECT sku_id, MAX(id) AS max_id
                    FROM stock_ledger
                    WHERE type = 'dc'  AND item_type = 'SKU' 
                      AND store_id IN ($store_id)
                      AND created BETWEEN '$stocklevel_startdate 00:00:01' AND '$stocklevel_enddate 23:59:59'
                    GROUP BY sku_id
                ) latest ON sl1.id = latest.max_id
                WHERE sl1.type = 'DC' AND sl1.item_type = 'SKU' 
            ");
        } else{
            $transactions = $this->Stock_ledger->query("
            SELECT sl1.sku_id,sl1.sku_price,sl1.sku_name,sl1.unit_name, sl1.actual_balance
            FROM stock_ledger sl1
            INNER JOIN (
                SELECT sku_id, MAX(id) AS max_id
                FROM stock_ledger
                WHERE type = 'dc'  AND item_type = 'SKU' 
                  AND created BETWEEN '$stocklevel_startdate 00:00:01' AND '$stocklevel_enddate 23:59:59'
                GROUP BY sku_id
            ) latest ON sl1.id = latest.max_id
            WHERE sl1.type = 'DC' AND sl1.item_type = 'SKU' 
        ");
        }
        
        
        $skus = $this->Inventory_sku->query("SELECT * FROM inventory_skus WHERE status=1");
        
        $skutransactions = [];
        if (!empty($sku_id)) {
            if($store_id){
                $skutransactions = $this->Stock_ledger->query("
                    SELECT * FROM stock_ledger 
                    WHERE created BETWEEN '$skuledger_startdate 00:00:01' AND '$skuledger_enddate 23:59:59'
                    AND type='DC' AND sku_id = $sku_id and store_id IN ($store_id) and item_type = 'SKU'
                    ORDER BY id DESC
                ");
            }else{
                $skutransactions = $this->Stock_ledger->query("
                    SELECT * FROM stock_ledger 
                    WHERE created BETWEEN '$skuledger_startdate 00:00:01' AND '$skuledger_enddate 23:59:59'
                    AND type='DC' AND sku_id = $sku_id and item_type = 'SKU'
                    ORDER BY id DESC
                                    ");
            }
        }
        
        $this->set('stocklevel_daterange', date('m/d/Y', strtotime($stocklevel_startdate)) . ' - ' . date('m/d/Y', strtotime($stocklevel_enddate)));
        $this->set('skuledger_daterange', date('m/d/Y', strtotime($skuledger_startdate)) . ' - ' . date('m/d/Y', strtotime($skuledger_enddate)));

            
        $users=$this->Location->find('all',array('conditions'=>$conditions));
                
	    $this->set(compact('users'));
    
        $this->set(compact('transactions', 'skus', 'skutransactions'));
    }

    public function stock_levelexport() {
        $date_range = $_GET['sdate'] ?? '';
    
        $dates = explode(" - ", $date_range);
        if (count($dates) !== 2) {
            throw new BadRequestException('Invalid date range.');
        }
        $id = $this->Session->read('Auth.User.id');
        $username = $this->User->query("SELECT location_id FROM users WHERE id = $id");
        $store_id = $username[0]['users']['location_id'];
        
        $start_date = trim($dates[0]);
        $end_date = trim($dates[1]);
    
        $startdate = date('Y-m-d', strtotime($start_date));
        $enddate = date('Y-m-d', strtotime($end_date));
    
        // Fetch stock ledger data
        $transactions = $this->Stock_ledger->query("
            SELECT sl1.sku_id,sl1.sku_price,sl1.sku_name,sl1.unit_name, sl1.actual_balance
            FROM stock_ledger sl1
            INNER JOIN (
                SELECT sku_id, MAX(id) AS max_id
                FROM stock_ledger
                WHERE type = 'dc' AND item_type = 'SKU' 
                  AND store_id = $store_id
                  AND created BETWEEN '$startdate 00:00:01' AND '$enddate 23:59:59'
                GROUP BY sku_id
            ) latest ON sl1.id = latest.max_id
            WHERE sl1.type = 'dc' and sl1.item_type = 'SKU' 
              AND sl1.store_id = $store_id
        ");
        
        // Prepare for Excel export
        App::import('Vendor', 'PHPExcel/PHPExcel');
        error_reporting(0);
        ini_set('display_errors', TRUE);
        ini_set('display_startup_errors', TRUE);
    
        if (PHP_SAPI == 'cli') {
            die('This example should only be run from a Web Browser');
        }
    
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()
            ->setCreator("Aether")
            ->setLastModifiedBy("Aether")
            ->setTitle("Stock Level Report")
            ->setSubject("Stock Report")
            ->setDescription("Exported stock level data.")
            ->setKeywords("stock excel")
            ->setCategory("Export File");
    
        // Header and formatting
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', 'STOCK LEVEL REPORT FROM '.$startdate.' TO '.$enddate);
        $objPHPExcel->getActiveSheet()->mergeCells('A1:F1');
        $objPHPExcel->getActiveSheet()->getStyle('A1:F1')->getFont()->setBold(true)->setSize(14);
    
        // Column headers
        $headers = ['Sr No.', 'SKU Name', 'Unit Name', 'Price', 'Quantity', 'Value'];
        $col = 'A';
        foreach ($headers as $header) {
            $objPHPExcel->getActiveSheet()->setCellValue($col . '3', $header);
            $objPHPExcel->getActiveSheet()->getStyle($col . '3')->getFont()->setBold(true);
            $col++;
        }
    
        // Fill data
        $row = 4;
        $count = 1;
        foreach ($transactions as $txn) {
            $data = $txn['sl1'];
            $value = round($data['sku_price'] * $data['actual_balance'], 2);
    
            $objPHPExcel->getActiveSheet()
                ->setCellValue("A$row", $count)
                ->setCellValue("B$row", $data['sku_name'])
                ->setCellValue("C$row", $data['unit_name'])
                ->setCellValue("D$row", (float) $data['sku_price'])
                ->setCellValue("E$row", (float) $data['actual_balance'])
                ->setCellValue("F$row", $value);
    
            $row++;
            $count++;
        }
    
        // Finalize
        $objPHPExcel->getActiveSheet()->setTitle('Stock Level');
        $objPHPExcel->setActiveSheetIndex(0);
    
        // Output headers
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="Stock_Level_Report.xls"');
        header('Cache-Control: max-age=0');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
        header('Cache-Control: cache, must-revalidate');
        header('Pragma: public');
    
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }
    
    public function kitchen_stock_level() {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "users";
    
        $stocklevel_startdate = $stocklevel_enddate = $skuledger_startdate = $skuledger_enddate = date('Y-m-d');
        $sku_id = null;
    
        if ($this->request->is(['post', 'put'])) {
            if (isset($this->request->data['submit_stocklevel'])) {
                $daterange = $this->request->data['daterange'] ?? '';
                $dates = explode(" - ", $daterange);
                if (count($dates) === 2) {
                    $stocklevel_startdate = date('Y-m-d', strtotime(trim($dates[0])));
                    $stocklevel_enddate = date('Y-m-d', strtotime(trim($dates[1])));
                }
            }
    
            if (isset($this->request->data['submit_skutransactions'])) {
                $daterange = $this->request->data['daterange'] ?? '';
                $dates = explode(" - ", $daterange);
                if (count($dates) === 2) {
                    $skuledger_startdate = date('Y-m-d', strtotime(trim($dates[0])));
                    $skuledger_enddate = date('Y-m-d', strtotime(trim($dates[1])));
                }
                $sku_id = $this->request->data['SkuLedger']['sku'] ?? null;
            }
            
        }
        $id = $this->Session->read('Auth.User.id');
        
        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;
        
        $conditions = [
            'status' => 1,
            'type'   => 'kitchen'
        ];
        
        if ($userRole !== 'admin' && !empty($userLocationId)) {
             $userLocationIds = Hash::extract(
                ['ids' => is_array($userLocationId) ? $userLocationId : explode(',', $userLocationId)],
                'ids.{n}'
            );
            $conditions['id IN'] = array_map('trim', $userLocationIds);
            $store_id = implode(',', $userLocationIds);
        }
        else{
            $username = $this->User->query("SELECT location_id FROM users WHERE id = $id");
            $store_id = $username[0]['users']['location_id'];
        }

        if (!empty($this->request->data['StockLevel']['cashier'])) {
            $store_id = $this->request->data['StockLevel']['cashier'];
        } 
        
        $transactions = $this->Stock_ledger->query("
            SELECT sl1.sku_id,sl1.sku_price,sl1.sku_name,sl1.unit_name, sl1.actual_balance
            FROM stock_ledger sl1
            INNER JOIN (
                SELECT sku_id, MAX(id) AS max_id
                FROM stock_ledger
                WHERE type = 'KITCHEN' 
                  AND store_id IN($store_id)
                  AND created BETWEEN '$stocklevel_startdate 00:00:01' AND '$stocklevel_enddate 23:59:59'
                GROUP BY sku_id
            ) latest ON sl1.id = latest.max_id
            WHERE sl1.type = 'KITCHEN' 
              AND sl1.store_id IN($store_id)
        ");
        
        $skus = $this->Inventory_sku->query("SELECT * FROM inventory_skus WHERE status=1");
        
        $skutransactions = [];
        if (!empty($sku_id)) {
            $skutransactions = $this->Stock_ledger->query("
                SELECT * FROM stock_ledger 
                WHERE created BETWEEN '$skuledger_startdate 00:00:01' AND '$skuledger_enddate 23:59:59'
                AND type='KITCHEN' AND sku_id = $sku_id and store_id IN($store_id)
                ORDER BY id DESC
            ");
        }
        
        $this->set('stocklevel_daterange', date('m/d/Y', strtotime($stocklevel_startdate)) . ' - ' . date('m/d/Y', strtotime($stocklevel_enddate)));
        $this->set('skuledger_daterange', date('m/d/Y', strtotime($skuledger_startdate)) . ' - ' . date('m/d/Y', strtotime($skuledger_enddate)));

        $users=$this->Location->find('all',array('conditions'=>$conditions));
                
	    $this->set(compact('users'));
    
        $this->set(compact('transactions', 'skus', 'skutransactions'));
    }

    public function kitchen_stock_levelexport() {
        $date_range = $_GET['sdate'] ?? '';
    
        $dates = explode(" - ", $date_range);
        if (count($dates) !== 2) {
            throw new BadRequestException('Invalid date range.');
        }
        $id = $this->Session->read('Auth.User.id');
        $username = $this->User->query("SELECT location_id FROM users WHERE id = $id");
        $store_id = $username[0]['users']['location_id'];
        $start_date = trim($dates[0]);
        $end_date = trim($dates[1]);
        $startdate = date('Y-m-d', strtotime($start_date));
        $enddate = date('Y-m-d', strtotime($end_date));
    
        // Fetch stock ledger data
        $transactions = $this->Stock_ledger->query("
            SELECT sl1.sku_id,sl1.sku_price,sl1.sku_name,sl1.unit_name, sl1.actual_balance
            FROM stock_ledger sl1
            INNER JOIN (
                SELECT sku_id, MAX(id) AS max_id
                FROM stock_ledger
                WHERE type = 'KITCHEN' 
                  AND store_id = $store_id
                  AND created BETWEEN '$startdate 00:00:01' AND '$enddate 23:59:59'
                GROUP BY sku_id
            ) latest ON sl1.id = latest.max_id
            WHERE sl1.type = 'KITCHEN' 
              AND sl1.store_id = $store_id
        ");
        
        
        // Prepare for Excel export
        App::import('Vendor', 'PHPExcel/PHPExcel');
        error_reporting(0);
        ini_set('display_errors', TRUE);
        ini_set('display_startup_errors', TRUE);
    
        if (PHP_SAPI == 'cli') {
            die('This example should only be run from a Web Browser');
        }
    
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()
            ->setCreator("Aether")
            ->setLastModifiedBy("Aether")
            ->setTitle("Stock Level Report")
            ->setSubject("Stock Report")
            ->setDescription("Exported stock level data.")
            ->setKeywords("stock excel")
            ->setCategory("Export File");
    
        // Header and formatting
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', 'STOCK LEVEL REPORT FROM '.$startdate.' TO '.$enddate);
        $objPHPExcel->getActiveSheet()->mergeCells('A1:F1');
        $objPHPExcel->getActiveSheet()->getStyle('A1:F1')->getFont()->setBold(true)->setSize(14);
    
        // Column headers
        $headers = ['Sr No.', 'SKU Name', 'Unit Name', 'Price', 'Quantity', 'Value'];
        $col = 'A';
        foreach ($headers as $header) {
            $objPHPExcel->getActiveSheet()->setCellValue($col . '3', $header);
            $objPHPExcel->getActiveSheet()->getStyle($col . '3')->getFont()->setBold(true);
            $col++;
        }
    
        // Fill data
        $row = 4;
        $count = 1;
        foreach ($transactions as $txn) {
            $data = $txn['sl1'];
            $value = round($data['sku_price'] * $data['actual_balance'], 2);
    
            $objPHPExcel->getActiveSheet()
                ->setCellValue("A$row", $count)
                ->setCellValue("B$row", $data['sku_name'])
                ->setCellValue("C$row", $data['unit_name'])
                ->setCellValue("D$row", (float) $data['sku_price'])
                ->setCellValue("E$row", (float) $data['actual_balance'])
                ->setCellValue("F$row", $value);
    
            $row++;
            $count++;
        }
    
        // Finalize
        $objPHPExcel->getActiveSheet()->setTitle('Stock Level');
        $objPHPExcel->setActiveSheetIndex(0);
    
        // Output headers
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="Stock_Level_Report.xls"');
        header('Cache-Control: max-age=0');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
        header('Cache-Control: cache, must-revalidate');
        header('Pragma: public');
    
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }
    
    public function semi_stock_level() {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "users";
    
        $stocklevel_startdate = $stocklevel_enddate = $skuledger_startdate = $skuledger_enddate = date('Y-m-d');
        $sku_id = null;
    
        if ($this->request->is(['post', 'put'])) {
            if (isset($this->request->data['submit_stocklevel'])) {
                $daterange = $this->request->data['stocklevel_daterange'] ?? '';
                $dates = explode(" - ", $daterange);
                if (count($dates) === 2) {
                    $stocklevel_startdate = date('Y-m-d', strtotime(trim($dates[0])));
                    $stocklevel_enddate = date('Y-m-d', strtotime(trim($dates[1])));
                }
            }
    
            if (isset($this->request->data['submit_skutransactions'])) {
                $daterange = $this->request->data['daterange'] ?? '';
                $dates = explode(" - ", $daterange);
                if (count($dates) === 2) {
                    $skuledger_startdate = date('Y-m-d', strtotime(trim($dates[0])));
                    $skuledger_enddate = date('Y-m-d', strtotime(trim($dates[1])));
                }
                $sku_id = $this->request->data['SkuLedger']['sku'] ?? null;
            }
            
        }
    
        $transactions = $this->Stock_ledger->query("
            SELECT * FROM stock_ledger 
            WHERE created BETWEEN '$stocklevel_startdate 00:00:01' AND '$stocklevel_enddate 23:59:59'
            AND type='OUTLET' and item_type='SKU'
            ORDER BY id DESC
        ");
    
        $skus = $this->Inventory_semifinished->query("SELECT * FROM inventory_semifinished WHERE status=1");
        
        $skutransactions = [];
        if (!empty($sku_id)) {
            $skutransactions = $this->Stock_ledger->query("
                SELECT * FROM stock_ledger 
                WHERE created BETWEEN '$skuledger_startdate 00:00:01' AND '$skuledger_enddate 23:59:59'
                AND type='OUTLET' AND sku_id = $sku_id
                ORDER BY id DESC
            ");
        }
        
        $this->set('stocklevel_daterange', date('m/d/Y', strtotime($stocklevel_startdate)) . ' - ' . date('m/d/Y', strtotime($stocklevel_enddate)));
        $this->set('skuledger_daterange', date('m/d/Y', strtotime($skuledger_startdate)) . ' - ' . date('m/d/Y', strtotime($skuledger_enddate)));
    
        $this->set(compact('transactions', 'skus', 'skutransactions'));
    }

    public function semi_stock_levelexport() {
        $date_range = $_GET['sdate'] ?? '';
    
        $dates = explode(" - ", $date_range);
        if (count($dates) !== 2) {
            throw new BadRequestException('Invalid date range.');
        }
    
        $start_date = trim($dates[0]);
        $end_date = trim($dates[1]);
    
        $startdate = date('Y-m-d', strtotime($start_date));
        $enddate = date('Y-m-d', strtotime($end_date));
    
        // Fetch stock ledger data
        $transactions = $this->Stock_ledger->query("
            SELECT * FROM stock_ledger 
            WHERE created BETWEEN '$startdate 00:00:01' AND '$enddate 23:59:59' and type='OUTLET' and item_type='SKU'
            ORDER BY id DESC
        ");
    
        // Prepare for Excel export
        App::import('Vendor', 'PHPExcel/PHPExcel');
        error_reporting(0);
        ini_set('display_errors', TRUE);
        ini_set('display_startup_errors', TRUE);
    
        if (PHP_SAPI == 'cli') {
            die('This example should only be run from a Web Browser');
        }
    
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()
            ->setCreator("Aether")
            ->setLastModifiedBy("Aether")
            ->setTitle("Stock Level Report")
            ->setSubject("Stock Report")
            ->setDescription("Exported stock level data.")
            ->setKeywords("stock excel")
            ->setCategory("Export File");
    
        // Header and formatting
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', 'STOCK LEVEL REPORT FROM '.$startdate.' TO '.$enddate);
        $objPHPExcel->getActiveSheet()->mergeCells('A1:F1');
        $objPHPExcel->getActiveSheet()->getStyle('A1:F1')->getFont()->setBold(true)->setSize(14);
    
        // Column headers
        $headers = ['Sr No.', 'SKU Name', 'Unit Name', 'Price', 'Quantity', 'Value'];
        $col = 'A';
        foreach ($headers as $header) {
            $objPHPExcel->getActiveSheet()->setCellValue($col . '3', $header);
            $objPHPExcel->getActiveSheet()->getStyle($col . '3')->getFont()->setBold(true);
            $col++;
        }
    
        // Fill data
        $row = 4;
        $count = 1;
        foreach ($transactions as $txn) {
            $data = $txn['stock_ledger'];
            $value = round($data['sku_price'] * $data['quantity'], 2);
    
            $objPHPExcel->getActiveSheet()
                ->setCellValue("A$row", $count)
                ->setCellValue("B$row", $data['sku_name'])
                ->setCellValue("C$row", $data['unit_name'])
                ->setCellValue("D$row", (float) $data['sku_price'])
                ->setCellValue("E$row", (float) $data['quantity'])
                ->setCellValue("F$row", $value);
    
            $row++;
            $count++;
        }
    
        // Finalize
        $objPHPExcel->getActiveSheet()->setTitle('Stock Level');
        $objPHPExcel->setActiveSheetIndex(0);
    
        // Output headers
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="Stock_Level_Report.xls"');
        header('Cache-Control: max-age=0');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
        header('Cache-Control: cache, must-revalidate');
        header('Pragma: public');
    
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

    public function modifiers() {
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		$startDate = date('m/d/Y', strtotime('-12 months'));
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
		}else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }   
        
		
		$users = $this->Catalog_modifier->query("SELECT * FROM catalog_modifier where created between '$startdate 00:00:01' and  '$enddate 23:59:59' ORDER BY id desc");
        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        
		$this->set(compact('users'));

	}
	
	public function create_modifier()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
        $this->layout = "users";
	    
		if ($this->request->is(array('post', 'put'))) {
            
            $name = $this->data['User']['name'];
            if($name==''){
                $this->Flash->error(__('The Name could not be Blank'));
                return $this->redirect(array('action' => 'create_modifier'));
            }
            
            $name = $this->data['User']['name'];
            $description = $this->data['User']['description'];
            $food_type = $this->data['User']['food_type'];
            $sort_order = $this->data['User']['sort_order'];
            $price = $this->data['User']['price'];
            $weight = $this->data['User']['weight'];
                
            $data['Catalog_modifier']=array(
    			'name'=>$name,
    			'description'=>$description,
    			'food_type'=>$food_type,
    			'sort_order'=>$sort_order,
    			'price'=>$price,
    			'weight'=>$weight
    		);
	    
            if($this->Catalog_modifier->saveAll($data['Catalog_modifier']))
    		{
    		    $this->Flash->success(__('Modifier has been saved.'));
				return $this->redirect(array('action' => 'modifiers'));
			} else {
				$this->Flash->error(__('Modifier could not be saved. Please, try again.'));
			}
		}
		
	}
    
    public function modifier_change_status() 
    {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $Id = $this->request->data['_id'];
            
            $this->Catalog_modifier->id = $Id;
            $newStatus = $this->Catalog_modifier->field('status') == 1 ? 0 : 1;
            
            if ($this->Catalog_modifier->save(['status' => $newStatus,'sync' => 0])) {
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }	
    
    public function view_modifier()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        $this->layout = "users";
	    $id=$_REQUEST['id'];
		
		$products = $this->Catalog_modifier->query("SELECT * FROM catalog_modifier where id=$id");
        $this->set(compact('products'));
        
    }
	
    public function modifiers_group() 
    {
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		$startDate = date('m/d/Y', strtotime('-12 months'));
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
		}else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }   
        
		
		$users = $this->Catalog_modifier_group->query("SELECT * FROM catalog_modifier_group where status=1 and created between '$startdate 00:00:01' and  '$enddate 23:59:59' ORDER BY id desc");
        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        
		$this->set(compact('users'));

	}
	
	public function create_modifiers_group()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
        $this->layout = "users";
	    
		if ($this->request->is(array('post', 'put'))) {
            
            $name = $this->data['User']['name'];
            if($name==''){
                $this->Flash->error(__('The Name could not be Blank'));
                return $this->redirect(array('action' => 'create_modifiers_group'));
            }
            if(isset($this->data['User']['is_default'])){
                $is_default=$this->data['User']['is_default'];
            }else{
                $is_default=0;
            }
            
            $name = $this->data['User']['name'];
            $description = $this->data['User']['description'];
            $group_type = $this->data['User']['group_type'];
            $sort_order = $this->data['User']['sort_order'];
            $min = $this->data['User']['min']?$this->data['User']['min']:0;
            $max = $this->data['User']['max']?$this->data['User']['max']:0;
                
            $data['Catalog_modifier_group']=array(
    			'name'=>$name,
    			'description'=>$description,
    			'group_type'=>$group_type,
    			'sort_order'=>$sort_order,
    			'is_default'=>$is_default,
    			'min'=>$min,
    			'max'=>$max
    		);
	        
            if($this->Catalog_modifier_group->saveAll($data['Catalog_modifier_group']))
    		{
    		    $last_id = $this->Catalog_modifier_group->getLastInsertID();
                $modifier_ids = $this->request->data['modifier_id'];
                
                if (!empty($modifier_ids)) {
                    $this->Inventory_linking->deleteAll([
                        'Inventory_linking.parent_id' => $last_id,
                        'Inventory_linking.parent_type' => 'Modifier_group',
                        'Inventory_linking.component_type' => 'Modifier'
                    ], false);
        
                    $linkData = [];
                
                    foreach ($modifier_ids as $modid) {
                        // Fetch modifier name safely
                        $modifier = $this->Catalog_modifier->find('first', [
                            'conditions' => ['Catalog_modifier.id' => $modid],
                            'fields' => ['name'],
                            'recursive' => -1
                        ]);
                
                        $mod_name = $modifier['Catalog_modifier']['name'] ?? '';
                        
                        $data['Inventory_linking']=array(
                			'parent_type'=>'Modifier_group',
                			'parent_id'=>$last_id,
                			'parent_name'=>$name,
                			'component_type'=>'Modifier',
                			'component_id'=>$modid,
                			'component_name'=>$mod_name,
                			'quantity'=>1
                		);
                	    
                	    // Save all rows
                        if ($this->Inventory_linking->saveAll($data['Inventory_linking'])) {
                            // Success
                        } else {
                            $this->Flash->error(__('Modifiers could not be grouped. Please try again.'));
                        }
                    }
                
                    
                }
    		    $this->Flash->success(__('Modifier Group has been saved.'));
				return $this->redirect(array('action' => 'modifiers_group'));
			} else {
				$this->Flash->error(__('Modifier Group could not be saved. Please, try again.'));
			}
		}
		
	}
    
    public function modifiers_group_change_status() 
    {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $Id = $this->request->data['_id'];
            
            $this->Catalog_modifier_group->id = $Id;
            $currentStatus = $this->Catalog_modifier_group->field('status');
            $newStatus = $currentStatus == 1 ? 0 : 1;
    
            // Begin transaction
            $this->Catalog_modifier_group->begin();
    
            // Try saving group status
            if ($this->Catalog_modifier_group->save(['status' => $newStatus, 'sync' => 0])) {
    
                $this->Inventory_linking->updateAll(
                    ['Inventory_linking.status' => $newStatus],
                    ['Inventory_linking.parent_id' => $Id],
                    ['Inventory_linking.parent_type' => 'Modifier_group'],
                    ['Inventory_linking.component_type' => 'Modifier']
                );

                $this->Inventory_linking->updateAll(
                    ['Inventory_linking.status' => $newStatus],
                    ['Inventory_linking.component_id' => $Id],
                    ['Inventory_linking.parent_type' => 'Product'],
                    ['Inventory_linking.component_type' => 'Modifier_group']
                );
                $this->Catalog_modifier_group->commit();
                echo json_encode(['status' => true]);
            } else {
                $this->Catalog_modifier_group->rollback();
                echo json_encode(['status' => false]);
            }
        }
    }

    
    public function view_modifiers_group()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        $this->layout = "users";
	    $id=$_REQUEST['id'];
		
		$products = $this->Catalog_modifier_group->query("SELECT * FROM catalog_modifier_group where id=$id");
        $this->set(compact('products'));
        
        $modifier_linking = $this->Inventory_linking->query("SELECT * FROM inventory_linking where parent_id=$id and parent_type='Modifier_group' and component_type='Modifier'");
        $this->set(compact('modifier_linking'));
        
    }
	
	public function fetch_modifiers_options()
    {
        $this->autoRender = false;
    
        $modifiers = $this->Catalog_modifier->find('all', [
            'conditions' => ['Catalog_modifier.status' => 1],
            'fields' => ['id', 'name', 'price'] // Include 'price'
        ]);
    
        $data = array_map(function ($item) {
            return $item['Catalog_modifier'];
        }, $modifiers);
    
        echo json_encode(['response_code' => 1, 'data' => $data]);
    }
    
    public function product_modifier()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		$id=$_REQUEST['id'];
    
        $products = $this->Catalog_product->query("SELECT * FROM catalog_product where id=$id");
        $this->set(compact('products'));
        
		$modifiers = $this->Inventory_linking->query("SELECT * FROM inventory_linking where parent_id=$id and parent_type='Product' and component_type='Modifier_group'");
        $this->set(compact('modifiers'));
        
	   if ($this->request->is(['post', 'put'])) {
            $data = $this->request->data['User'];
        
            $product_id = $data['id'] ?? null;
            $product_name = $data['name'] ?? '';
            $product_unit = $data['unit'] ?? '';
            $product_unit_name = $data['unit_name'] ?? '';
        
            if (empty($product_id)) {
                $this->Flash->error(__('Product Error'));
                return $this->redirect(['action' => 'product_modifier', '?' => ['id' => $product_id]]);
            }
        
            $selectedModifiers = [];
        
            // 1. Collect modifier IDs from PHP input fields (semi_id_X)
            $allModifiers = $this->Catalog_modifier_group->find('list', [
                'fields' => ['id'],
                'conditions' => ['status' => 1],
                'recursive' => -1
            ]);
        
            foreach ($allModifiers as $modifier_id => $val) {
                if (!empty($data['semi_id_' . $modifier_id])) {
                    $selectedModifiers[] = $data['semi_id_' . $modifier_id];
                }
            }
        
            // 2. Collect modifier IDs from JS-added inputs (select_sku_name[])
            $jsModifiers = $_POST['select_sku_name'] ?? [];
        
            // 3. Merge and deduplicate
            $modifier_ids = array_values(array_unique(array_merge($selectedModifiers, $jsModifiers)));
        
            // 4. Delete old mappings
            $this->Inventory_linking->deleteAll([
                    'Inventory_linking.parent_id' => $product_id,
                    'Inventory_linking.parent_type' => 'Product',
                    'Inventory_linking.component_type' => 'Modifier_group'
                ], false);
    
            // 5. Build new mappings
            $linkData = [];
        
            foreach ($modifier_ids as $mod_id) {
                $mod = $this->Catalog_modifier_group->find('first', [
                    'conditions' => ['id' => $mod_id],
                    'fields' => ['id', 'name'],
                    'recursive' => -1
                ]);
        
                if (!$mod) continue;
        
                $linkData[] = [
                    'parent_type'=>'Product',
        			'parent_id'=>$product_id,
        			'parent_name'=>$product_name,
        			'component_type'=>'Modifier_group',
        			'component_id'=>$mod_id,
        			'component_name'=>$mod['Catalog_modifier_group']['name'],
        			'quantity'=>1
                ];
            }
        
            // 6. Save all
            if (!empty($linkData)) {
                if ($this->Inventory_linking->saveAll($linkData)) {
                    $this->Flash->success(__('Group modifiers have been saved successfully.'));
                } else {
                    $this->Flash->error(__('Some group modifiers could not be saved.'));
                }
            } else {
                $this->Flash->success(__('No modifiers selected. Existing mappings have been cleared.'));
            }
        
            return $this->redirect(['action' => 'product_list']);
        }

    }
 
    public function fetch_modifiers_group_options()
    {
        $this->autoRender = false;
    
        $linkedGroupIds = $this->Inventory_linking->find('list', [
            'fields' => ['Inventory_linking.parent_id', 'Inventory_linking.parent_id'],
            'conditions' => [
                'Inventory_linking.status' => 1,
                'Inventory_linking.parent_type' => 'Modifier_group',
                'Inventory_linking.component_type' => 'Modifier'
            ],
            'recursive' => -1
        ]);
    // print_r($linkedGroupIds);exit;
        $modifiers = $this->Catalog_modifier_group->find('all', [
            'conditions' => [
                'Catalog_modifier_group.status' => 1,
                'Catalog_modifier_group.id' => array_keys($linkedGroupIds)
            ],
            'fields' => ['Catalog_modifier_group.id', 'Catalog_modifier_group.name'],
            'order' => ['Catalog_modifier_group.name' => 'ASC']
        ]);
    
        $data = array_map(function ($item) {
            return $item['Catalog_modifier_group'];
        }, $modifiers);
    
        echo json_encode(['response_code' => 1, 'data' => $data]);
    }

	public function edit_modifiers() 
	{
        // Check if user is authenticated
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = 'users';
    
        // Get modifier ID from query string
        $id = $this->request->query('id') ?? null;
    
        if (!$id) {
            $this->Flash->error(__('Modifier ID not provided.'));
            return $this->redirect(['action' => 'modifiers']);
        }
    
        // Fetch modifier by ID
        $modifier = $this->Catalog_modifier->findById($id);
        if (!$modifier) {
            $this->Flash->error(__('Modifier not found.'));
            return $this->redirect(['action' => 'modifiers']);
        }
    
        // If form is submitted
        if ($this->request->is(['post', 'put'])) {
            $this->Catalog_modifier->id = $id;
    
            // Save updated data
            if ($this->Catalog_modifier->save($this->request->data)) {
                $this->Flash->success(__('Modifier has been updated successfully.'));
                return $this->redirect(['action' => 'modifiers']);
            } else {
                $this->Flash->error(__('Failed to update modifier. Please try again.'));
            }
        }
    
        // Pre-fill form with existing data
        $this->request->data = $modifier;
        $this->set(compact('modifier'));
    }
    
    public function edit_modifier_group()
    {
        $this->layout = 'users';
    
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $groupId = $this->request->query('id') ?? null;
    
        if (!$groupId) {
            $this->Flash->error(__('Invalid Modifier Group ID.'));
            return $this->redirect(['action' => 'modifiers_group']);
        }
    
        // Fetch current group details and modifiers
        $products = $this->Catalog_modifier_group->find('all', [
            'conditions' => ['Catalog_modifier_group.id' => $groupId],
            'limit' => 1
        ]);
        $modifier_linking = $this->Inventory_linking->find('all', [
            'conditions' => ['parent_id' => $groupId,'parent_type' => 'Modifier_group','component_type' => 'Modifier']
        ]);
        $this->set(compact('products', 'modifier_linking'));
    
        // On form submission
        if ($this->request->is(['post', 'put'])) {
            $data = $this->request->data;
            if($data['Catalog_modifier_group']['group_type']==0){
                $min=$data['Catalog_modifier_group']['min'];
                $max=$data['Catalog_modifier_group']['max'];
            }else{
                $min=0;
                $max=0;
            }
            $groupData = [
                'id' => $data['Catalog_modifier_group']['id'],
                'name' => $data['Catalog_modifier_group']['name'],
                'group_type' => $data['Catalog_modifier_group']['group_type'],
                'description' => $data['Catalog_modifier_group']['description'],
                'sort_order' => $data['Catalog_modifier_group']['sort_order'],
                'min' => $min,
                'max' => $max,
                'is_default' => $data['Catalog_modifier_group']['is_default']?$data['Catalog_modifier_group']['is_default']:0
            ];
    
            if ($this->Catalog_modifier_group->save($groupData)) {
    
                // Delete old modifier group linkings
                $this->Inventory_linking->deleteAll([
                    'Inventory_linking.parent_id' => $groupId,
                    'Inventory_linking.parent_type' => 'Modifier_group',
                    'Inventory_linking.component_type' => 'Modifier'
                ], false);
                
                $modifierIds = $data['modifier_id'] ?? [];
                $modifierIds = array_unique(array_filter($modifierIds)); // also removes empty values
                $linkData = [];
    
                foreach ($modifierIds as $modId) {
                    if (empty($modId)) continue;
    
                    $mod = $this->Catalog_modifier->find('first', [
                        'conditions' => ['Catalog_modifier.id' => $modId],
                        'fields' => ['name'],
                        'recursive' => -1
                    ]);
                    $modName = $mod['Catalog_modifier']['name'] ?? '';
    
                    $linkData[] = [
                        'parent_type'=>'Modifier_group',
            			'parent_id'=>$groupId,
            			'parent_name'=>$groupData['name'],
            			'component_type'=>'Modifier',
            			'component_id'=>$modId,
            			'component_name'=>$modName,
            			'quantity'=>1
                    ];
                }
    
                if (!empty($linkData)) {
                    $this->Inventory_linking->saveAll($linkData);
                }
    
                $this->Flash->success(__('Modifier Group updated successfully.'));
                return $this->redirect(['action' => 'modifiers_group']);
            } else {
                $this->Flash->error(__('Failed to update Modifier Group.'));
            }
        }
    }
    
    public function modifier_recipe()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		$id=$_REQUEST['id'];
    
        $products = $this->Catalog_modifier->query("SELECT * FROM catalog_modifier where id=$id");
        $this->set(compact('products'));
        
		$recipes = $this->Inventory_linking->query("SELECT * FROM inventory_linking where parent_id=$id and parent_type='Modifier' and component_type='Semifinished'");
        $skurecipes = $this->Inventory_linking->query("SELECT * FROM inventory_linking where parent_id=$id and parent_type='Modifier' and component_type='Sku'");
        $this->set(compact('recipes','skurecipes'));
        
        if ($this->request->is(array('post', 'put'))) {
            $product_id = $this->data['User']['id'];
            $product_name = $this->data['User']['name'];
            
            $selectedSemifinished=[];
            $semifinishedquantity=[];
            $semi_ids=[];
            $semi_quantities=[];
            $semifinisheds=$this->Inventory_semifinished->find('all',array('conditions'=>array('status'=>1)));
	        foreach($semifinisheds as $semifinished){
	            $semifinishedid = $semifinished['Inventory_semifinished']['id'];
                if (!empty($this->request->data['User']['semi_id_' . $semifinishedid])) {
                    $selectedSemifinished[] = $this->request->data['User']['semi_id_' . $semifinishedid];
                    $semifinishedquantity[]=$this->request->data['User']['semi_quantity_' . $semifinishedid];
                }
	        }
	        if(isset($_POST['select_semi_name'])){
    	        $semi_ids=$_POST['select_semi_name'];
                $semi_quantities=$_POST['semi_quantity'];
	        }
            $mergedArraysemi = array_merge($selectedSemifinished, $semi_ids);
            $uniqueArraysemi = array_unique($mergedArraysemi);
            $semi_ids = array_values($uniqueArraysemi);
            
            $mergedArraysemi1 = array_merge($semifinishedquantity, $semi_quantities);
            $semi_quantities = array_values($mergedArraysemi1);

            if(isset($semi_ids)){
                $this->Inventory_linking->deleteAll([
                    'Inventory_linking.parent_id' => $product_id,
                    'Inventory_linking.parent_type' => 'Modifier',
                    'Inventory_linking.component_type' => 'Semifinished'
                ], false);
    
                for ($i = 0; $i < count($semi_ids); $i++) {
                    $semi_id = $semi_ids[$i];
                    $semi_quantity = $semi_quantities[$i];
                    
                    $seminame=$this->Inventory_semifinished->find('first',array('conditions'=>array('id'=>$semi_id)));
                    $semi_name=$seminame['Inventory_semifinished']['name'];
                    $semi_unit=$seminame['Inventory_semifinished']['unit'];
                    $semi_unit_name=$seminame['Inventory_semifinished']['unit_name'];
                    
                    $data['Inventory_linking']=array(
            			'parent_type'=>'Modifier',
            			'parent_id'=>$product_id,
            			'parent_name'=>$product_name,
            			'component_type'=>'Semifinished',
            			'component_id'=>$semi_id,
            			'component_name'=>$semi_name,
            			'quantity'=>$semi_quantity,
            			'component_unit'=>$semi_unit,
            			'component_unit_name'=>$semi_unit_name
            		);
            	    
            	    if($this->Inventory_linking->saveAll($data['Inventory_linking']))
            		{
            		    
            		}else{
            		    $this->Flash->error(__('Semifinished mapping could not be saved. Please, try again.'));
            		}
                }
            }
            
            $selectedSku=[];
            $skuquantity=[];
            $sku_ids=[];
            $sku_quantities=[];
            $skus=$this->Inventory_sku->find('all',array('conditions'=>array('status'=>1)));
	        foreach($skus as $sku){
	            $skuid = $sku['Inventory_sku']['id'];
                if (!empty($this->request->data['User']['sku_id_' . $skuid])) {
                    $selectedSku[] = $this->request->data['User']['sku_id_' . $skuid];
                    $skuquantity[]=$this->request->data['User']['sku_quantity_' . $skuid];
                }
	        }
	        if(isset($_POST['select_sku_name'])){
    	        $sku_ids=$_POST['select_sku_name'];
                $sku_quantities=$_POST['sku_quantity'];
	        }
            $mergedArraysku = array_merge($selectedSku, $sku_ids);
            $uniqueArraysku = array_unique($mergedArraysku);
            $sku_ids = array_values($uniqueArraysku);
            
            $mergedArraysku1 = array_merge($skuquantity, $sku_quantities);
            $sku_quantities = array_values($mergedArraysku1);
            
            if(isset($sku_ids)){
                $this->Inventory_linking->deleteAll([
                    'Inventory_linking.parent_id' => $product_id,
                    'Inventory_linking.parent_type' => 'Modifier',
                    'Inventory_linking.component_type' => 'Sku'
                ], false);
    
                for ($i = 0; $i < count($sku_ids); $i++) {
                    $sku_id = $sku_ids[$i];
                    $sku_quantity = $sku_quantities[$i];
                    
                    $skuname=$this->Inventory_sku->find('first',array('conditions'=>array('id'=>$sku_id)));
                    $sku_name=$skuname['Inventory_sku']['name'];
                    $sku_unit=$skuname['Inventory_sku']['unit'];
                    $sku_unit_name=$skuname['Inventory_sku']['unit_name'];
                    
            		$data['Inventory_linking']=array(
            			'parent_type'=>'Modifier',
            			'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
            		);
            	    
            	    
            	    if($this->Inventory_linking->saveAll($data['Inventory_linking']))
            		{
            		    
            		}else{
            		    $this->Flash->error(__('Sku mapping could not be saved. Please, try again.'));
            		}
                }
            }
            
            $this->Flash->success(__('Recipe has been saved.'));
			return $this->redirect(array('action' => 'modifiers'));
        }
		
	}
	
	public function inv_category_list() 
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		$startDate = date('m/d/Y', strtotime('-12 months'));
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }   
        
		$users = $this->Inventory_category->find('all', array(
            'conditions' => array('created BETWEEN ? AND ?' => array($startdate.' 00:00:01', $enddate.' 23:59:59')
            ),
            'order' => array(
                'id' => 'DESC' // Order by the 'created' field in ascending order
            )
        ));
        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        
		$this->set(compact('users'));

	}
	
	public function inv_subcategory_list() 
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		$startDate = date('m/d/Y', strtotime('-12 months'));
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }   
        
		$users = $this->Inventory_subcategory->query("SELECT *,(SELECT name FROM inventory_category where id=inventory_subcategory.cat_id) as cat_name FROM inventory_subcategory where created between '$startdate 00:00:01' and  '$enddate 23:59:59' ORDER BY id desc");
        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        
		$this->set(compact('users'));

	}
	
	public function inv_create_category()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		if ($this->request->is(array('post', 'put'))) {
            
            $name = $this->data['User']['name'];
            if($name==''){
                $this->Flash->error(__('The Name could not be Blank'));
                return $this->redirect(array('action' => 'create_category'));
            }
            
            if(isset($_POST['subcat'])){
                $is_subcat=1;
            }else{
                $is_subcat=0;
            }
            
            $image=$this->data['User']['image'];
            if (!empty($image['name'])) {
                $uploadPath = WWW_ROOT . 'uploads' . DS . 'category_images' . DS;
                $file=basename(time().$image['name']);
                $file = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', $file);
                $uploadFile = $uploadPath . $file;
                
                if (move_uploaded_file($image['tmp_name'], $uploadFile)) {
                    $filename=$file;
                }else{
                    $filename='';
                }
            }
            // print_r($this->data);exit;
            
            $data['Inventory_category']=array(
    			'name'=>$name,
    			'is_subcategory'=>$is_subcat,
    			'image'=>$filename
    	    );
    	    
    	    if($this->Inventory_category->saveAll($data['Inventory_category']))
    		{
    		    $lastInsertedID = $this->Inventory_category->id;
    		    if(isset($_POST['subcat'])){
                    $subcats = $_POST['subcat'];
                    foreach ($subcats as $subcat) {
                        $data['Inventory_subcategory']=array(
                			'cat_id'=>$lastInsertedID,
                			'name'=>$subcat
                		);
                	    
                	    if($this->Inventory_subcategory->saveAll($data['Inventory_subcategory']))
                		{
                		    
                		}else{
                		    $this->Flash->error(__('Sub category could not be saved. Please, try again.'));
                		}
                    }
                }
        	    
    		    
                $this->Flash->success(__('Category has been saved.'));
				return $this->redirect(array('action' => 'inv_category_list'));
			} else {
				$this->Flash->error(__('Category could not be saved. Please, try again.'));
			}
		}
	}
	
	public function inv_edit_category()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		$id=$_REQUEST['id'];
		
		$categories = $this->Inventory_category->query("SELECT * FROM inventory_category where id=$id");
        $this->set(compact('categories'));
        
        $subcategories=$this->Inventory_subcategory->query("SELECT * FROM inventory_subcategory where cat_id=$id and status=1");
        $this->set(compact('subcategories')); 
        
        if ($this->request->is(array('post', 'put'))) {
            // print_r($this->data);exit;
            $id = $this->data['User']['id'];
            $name = $this->data['User']['name'];
            if($name==''){
                $this->Flash->error(__('The Name could not be Blank'));
                return $this->redirect(array('action' => 'inv_edit_category?id='.$id));
            }
            
            $image=$this->data['User']['image'];
            if (!empty($image['name'])) {
                $uploadPath = WWW_ROOT . 'uploads' . DS . 'category_images' . DS;
                $file=basename(time().$image['name']);
                $file = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', $file);
                $uploadFile = $uploadPath . $file;
                
                if (move_uploaded_file($image['tmp_name'], $uploadFile)) {
                    $filename=$file;
                }else{
                    $filename='';
                }
                $this->Inventory_category->query("UPDATE `inventory_category` SET image='$filename',sync = 0 WHERE id=$id");
            }
            $this->Inventory_category->query("UPDATE `inventory_category` SET name='$name',sync = 0 WHERE id=$id");
            
	        $lastInsertedID = $id;
		    if(isset($_POST['subcat'])){
                $subcats = $_POST['subcat'];
                foreach ($subcats as $subcat) {
                    $data['Inventory_subcategory']=array(
            			'cat_id'=>$lastInsertedID,
            			'name'=>$subcat
            		);
            	    
            	    if($this->Inventory_subcategory->saveAll($data['Inventory_subcategory']))
            		{
            		    
            		}else{
            		    $this->Flash->error(__('Sub category could not be saved. Please, try again.'));
            		}
                }
            }
    	    
    	    $subcategorychk=$this->Inventory_subcategory->query("SELECT * FROM inventory_subcategory where cat_id=$id and status=1");
            if($subcategorychk){
                $this->Inventory_category->query("UPDATE `inventory_category` SET is_subcategory='1',sync = 0 WHERE id=$id");
            }else{
                $this->Inventory_category->query("UPDATE `inventory_category` SET is_subcategory='0',sync = 0 WHERE id=$id");
            }
		    
            $this->Flash->success(__('Category has been Updated.'));
			return $this->redirect(array('action' => 'inv_category_list'));
		
		}
	}
	
	public function inv_remove_subcategory() 
	{
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $Id = $this->request->data['_id'];
            
            $this->Inventory_subcategory->id = $Id;
            if ($this->Inventory_subcategory->save(['status' => 0,'sync' => 0])) {
                
                $categoryid = $this->Inventory_subcategory->query("SELECT cat_id FROM inventory_subcategory where id=$Id");
                $cat_id=$categoryid['0']['inventory_subcategory']['cat_id'];
                
                $subcategorychk=$this->Inventory_subcategory->query("SELECT * FROM inventory_subcategory where cat_id=$cat_id and status=1");
                if($subcategorychk){
                    $this->Inventory_category->query("UPDATE inventory_category SET is_subcategory=1,sync = 0 WHERE id=$cat_id");
                }else{
                    $this->Inventory_category->query("UPDATE inventory_category SET is_subcategory=0,sync = 0 WHERE id=$cat_id");
                }
    		    
    		    echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }

    public function inv_create_subcategory()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		if ($this->request->is(array('post', 'put'))) {
            $subcategoriesname=$_POST['subcat'];
            $categoryid = $this->data['User']['category'];
            if($categoryid==''){
                $this->Flash->error(__('Select Category'));
                return $this->redirect(array('action' => 'inv_create_subcategory'));
            }
            
            $image=$this->data['User']['image'];
            if (!empty($image['name'])) {
                $uploadPath = WWW_ROOT . 'uploads' . DS . 'category_images' . DS;
                $file=basename(time().$image['name']);
                $file = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', $file);
                $uploadFile = $uploadPath . $file;
                
                if (move_uploaded_file($image['tmp_name'], $uploadFile)) {
                    $filename=$file;
                }else{
                    $filename='';
                }
            }
            
            foreach($subcategoriesname as $subcategory){
                $data['Inventory_subcategory']=array(
        			'name'=>$subcategory,
        			'cat_id'=>$categoryid,
        			'image'=>$filename
        	    );
                
                if($this->Inventory_subcategory->saveAll($data['Inventory_subcategory']))
    		    {
    		        $savechk=true;
    		        
                }else{
                    $savechk=false;
                }
        	    
            }    
            
            if($savechk){
                $this->Inventory_category->query("UPDATE `inventory_category` SET is_subcategory='1',sync = 0 WHERE id=$categoryid");
            
    		        
                $this->Flash->success(__('Sub Category has been saved.'));
				return $this->redirect(array('action' => 'inv_subcategory_list'));
			} else {
				$this->Flash->error(__('Some sub Category could not be saved. Please, try again.'));
				return $this->redirect(array('action' => 'inv_subcategory_list'));
			}
		}
		
		$categories=$this->Inventory_category->find('all',array('conditions'=>array('status'=>1)));
	    $this->set(compact('categories'));
	
	}
    
    public function inv_category_change_status() 
    {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $Id = $this->request->data['_id'];
            
            $this->Inventory_category->id = $Id;
            $newStatus = $this->Inventory_category->field('status') == 1 ? 0 : 1;
            
            if ($this->Inventory_category->save(['status' => $newStatus,'sync' => 0])) {
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }

    public function inv_subcategory_change_status() 
    {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $Id = $this->request->data['_id'];
            
            $this->Inventory_subcategory->id = $Id;
            $newStatus = $this->Inventory_subcategory->field('status') == 1 ? 0 : 1;
            
            if ($this->Inventory_subcategory->save(['status' => $newStatus,'sync' => 0])) {
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }
    
    public function inv_view_category()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		$id=$_REQUEST['id'];
		
		$categories = $this->Inventory_category->query("SELECT * FROM inventory_category where id=$id");
        $this->set(compact('categories'));
        
        $subcategories=$this->Inventory_subcategory->query("SELECT * FROM inventory_subcategory where cat_id=$id and status=1");
        $this->set(compact('subcategories')); 
	}
	
	public function inv_edit_subcategory()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		$id=$_REQUEST['id'];
		
		$subcategories=$this->Inventory_subcategory->query("SELECT *,(SELECT name FROM `inventory_category` WHERE id=inventory_subcategory.cat_id) as catname FROM inventory_subcategory where id=$id");
        $this->set(compact('subcategories')); 
        
        $categories=$this->Inventory_category->find('all',array('conditions'=>array('status'=>1),'order' => array(
                'name' => 'asc' // Order by the 'created' field in ascending order
            )));
	    $this->set(compact('categories'));
	    
	    if ($this->request->is(array('post', 'put'))) {
            // print_r($this->data);exit;
            $id = $this->data['User']['id'];
            $name = $this->data['User']['name'];
            if($name==''){
                $this->Flash->error(__('The Name could not be Blank'));
                return $this->redirect(array('action' => 'inv_edit_subcategory?id='.$id));
            }
            
            $image=$this->data['User']['image'];
            if (!empty($image['name'])) {
                $uploadPath = WWW_ROOT . 'uploads' . DS . 'category_images' . DS;
                $file=basename(time().$image['name']);
                $file = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', $file);
                $uploadFile = $uploadPath . $file;
                
                if (move_uploaded_file($image['tmp_name'], $uploadFile)) {
                    $filename=$file;
                }else{
                    $filename='';
                }
                $this->Inventory_subcategory->query("UPDATE `inventory_subcategory` SET image='$filename',sync = 0 WHERE id=$id");
            }
            $category=$this->data['User']['category'];
        
            $categoryid = $this->Inventory_subcategory->query("SELECT cat_id FROM inventory_subcategory where id=$id");
            $cat_id=$categoryid['0']['inventory_subcategory']['cat_id'];
        
            $this->Inventory_subcategory->query("UPDATE `inventory_subcategory` SET name='$name',cat_id=$category,sync = 0 WHERE id=$id");
            $this->Inventory_category->query("UPDATE `inventory_category` SET is_subcategory=1,sync = 0 WHERE id=$category");
            
            $subcategorychk=$this->Inventory_subcategory->query("SELECT * FROM inventory_subcategory where cat_id=$cat_id and status=1");
            if($subcategorychk){
                $this->Inventory_category->query("UPDATE inventory_category SET is_subcategory=1,sync = 0 WHERE id=$cat_id");
            }else{
                $this->Inventory_category->query("UPDATE inventory_category SET is_subcategory=0,sync = 0 WHERE id=$cat_id");
            }
            
            $this->Flash->success(__('Sub Category has been Updated.'));
			return $this->redirect(array('action' => 'inv_subcategory_list'));
		
		}
	
	}
	
	public function inv_view_subcategory()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		$id=$_REQUEST['id'];
		
		$categories=$this->Inventory_subcategory->query("SELECT *,(SELECT name FROM `inventory_category` WHERE id=inventory_subcategory.cat_id) as catname FROM inventory_subcategory where id=$id");
        $this->set(compact('categories')); 
	}
	
	public function indent()
    {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "users";
    
        // Default date range
        $startDate = date('m/d/Y', strtotime('-1 month'));
        $endDate = date('m/d/Y');
    
        if ($this->request->is(['post', 'put'])) 
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }
    
        // Auth info
        $locationId = $this->Session->read('Auth.User.location_id');
        $userRole = $this->Session->read('Auth.User.role');
    
        // Base condition
        $conditions = "created BETWEEN '$startdate 00:00:01' AND '$enddate 23:59:59'";
        if ($userRole !== 'admin') {
            $conditions .= " AND warehouse_id = '$locationId'";
        }
    
        // Indents by status
        $submittedIndents = $this->Inventory_indent->query("
            SELECT * FROM inventory_indent 
            WHERE $conditions AND status = 1 
            ORDER BY id DESC
        ");
        $approvedIndents = $this->Inventory_indent->query("
            SELECT * FROM inventory_indent 
            WHERE $conditions AND status = 2 
            ORDER BY id DESC
        ");
        $processedIndents = $this->Inventory_indent->query("
            SELECT * FROM inventory_indent 
            WHERE $conditions AND status = 3 
            ORDER BY id DESC
        ");
    
        $yourStartDateValue = $startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        $this->set(compact('submittedIndents', 'approvedIndents', 'processedIndents'));
    }

    public function approve_indent()
    {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'outlet', 'action' => 'login']);
        }
    
        $this->layout = "users";
        $id = $_REQUEST['id'];
    
        $user = "
            SELECT 
                inventory_semifinished.*,
                inventory_indent_items.sku_quantity AS quantity
            FROM 
                inventory_semifinished
            INNER JOIN 
                inventory_indent_items 
                ON inventory_indent_items.sku_id = inventory_semifinished.id
                AND inventory_indent_items.indent_id = $id
                AND inventory_indent_items.sku_quantity IS NOT NULL
                AND inventory_indent_items.sku_quantity != 0
            WHERE 
                inventory_semifinished.status = 1
            ORDER BY 
                inventory_semifinished.name DESC
        ";
        
        $users = $this->Inventory_semifinished->query($user);
    
        $indentData = $this->Inventory_indent->find('first', [
            'conditions' => ['indent_id' => $id],
            'recursive' => -1
        ]);
    
        $selected_location_id = $indentData['Inventory_indent']['location_id'];
        $selected_expiry = $indentData['Inventory_indent']['expiry'];
    
        $this->set(compact('users', 'id', 'selected_location_id'));
    }
    
    public function update_approve_indent() 
    {
        $this->autoRender = false;
    
        $userId = $this->Session->read('Auth.User.id');
        $userName = $this->Session->read('Auth.User.name');
    
        if (isset($_POST['checkedData'])) {
            $checkeddatas = json_decode($_POST['checkedData'], true);
            $indentId = $_POST['indent_id'];
            $expiry = $_POST['expiry'];
            $remarks = $_POST['remarks'];
            $vehicle = $_POST['vehicle'];
            $location_id = $_POST['location_id'] ?? null;
    
            $amount = 0;
            $success = false;
            foreach ($checkeddatas as $checkeddata) {
                $skuId = $checkeddata['id'];
                $price = floatval($checkeddata['price']);
                $approvedQty = intval($checkeddata['sku_quantity']);
                
                $product_taxes=$this->Inventory_semifinished_tax->query("select SUM(tax_percentage) as total_tax from inventory_semifinished_tax where product_id='$skuId' ");
                $total_tax=round($product_taxes['0']['0']['total_tax'],2);
                
                $tax_value = round(($price*$approvedQty) * ($total_tax / 100),2);

                $skuamount=round(($price*$approvedQty) + $tax_value,2);
                
                $this->Inventory_indent_items->updateAll(
                    [
                        'approved_price' => $price,
                        'approved_quantity' => $approvedQty,
                        'approved_tax_value' => $tax_value,
                        'approved_amount' => $skuamount
                    ],
                    [
                        'indent_id' => $indentId,
                        'sku_id' => $skuId
                    ]
                );
    
                $amount += ($skuamount);
                $success = true;
            }
            if ($success) {
                $vehicle_value = $vehicle ? "'$vehicle'" : "''";
                $remarks_value = $remarks ? "'$remarks'" : "''";
                $expiry_value = $expiry ? "'$expiry'" : "''";
                
                
                $currentDate = date('Y-m-d H:i:s');
                
                $this->Inventory_indent->updateAll(
                    [
                        'approved_amount' => $amount,
                        'vehicle_no' => $vehicle_value,
                        'remarks' => $remarks_value,
                        'approved_selected_date' => $expiry_value,
                        'approved_date' => "'$currentDate'",
                        'status' => 2
                    ],
                    ['indent_id' => $indentId]
                );
                echo json_encode(['response_code' => 1, 'data' => 'Approved']);
            } else {
                echo json_encode(['response_code' => 0, 'data' => 'Indent items could not be updated.']);
            }
        }
    }

    public function process_indent()
    {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'outlet', 'action' => 'login']);
        }
    
        $this->layout = "users";
        $id = $_REQUEST['id'];
    
        $id = (int)$id; // Prevent SQL injection

        $user = "
            SELECT 
                inventory_semifinished.*,
                inventory_indent_items.sku_quantity AS quantity,
                inventory_indent_items.approved_quantity AS approved_quantity,
                inventory_indent_items.approved_price AS price
            FROM 
                inventory_semifinished
            INNER JOIN 
                inventory_indent_items 
                ON inventory_indent_items.sku_id = inventory_semifinished.id
                AND inventory_indent_items.indent_id = $id
                AND inventory_indent_items.sku_quantity IS NOT NULL
                AND inventory_indent_items.sku_quantity != 0
            WHERE 
                inventory_semifinished.status = 1
            ORDER BY 
                inventory_semifinished.name DESC;

        ";
        
        $users = $this->Inventory_semifinished->query($user);

    
        $indentData = $this->Inventory_indent->find('first', [
            'conditions' => ['indent_id' => $id],
            'recursive' => -1
        ]);
    
        $selected_location_id = $indentData['Inventory_indent']['location_id'];
        $selected_expiry = $indentData['Inventory_indent']['expiry'];
    
        $this->set(compact('users', 'id', 'selected_location_id'));
    }

    public function update_process_indent() 
    {
        $this->autoRender = false;
    
        $userId = $this->Session->read('Auth.User.id');
        $locationId = $this->Session->read('Auth.User.location_id');
        $userName = $this->Session->read('Auth.User.name');
    
        if (isset($_POST['checkedData'])) {
            $checkeddatas = json_decode($_POST['checkedData'], true);
            $indentId = $_POST['indent_id'];
            $location_id = $_POST['location_id'] ?? null;
    
            $amount = 0;
            $success = false;
            
            do {
                $consignment_id = rand(1, 9);
                for ($i = 1; $i < 10; $i++) {
                    $consignment_id .= rand(0, 9);
                }
    
                $existing = $this->Inventory_indent->find('first', [
                    'conditions' => ['consignment_id' => $consignment_id],
                    'recursive' => -1
                ]);
            } while ($existing);
            
            $year = date('Y') + 501; // Example: 2025 + 573 = 2598 (you can adjust logic as per your 2526 example)

            // Step 2: Set prefix
            $prefix = 'TGI' . $year; // e.g., TGI2526
        
            // Step 3: Find latest code that starts with this year's prefix
            $latest = $this->Inventory_indent->find('first', [
                'fields' => ['serial_number'],
                'conditions' => ['Inventory_indent.serial_number LIKE' => $prefix . '%'],
                'order' => ['Inventory_indent.id' => 'DESC']
            ]);
        
            // Step 4: Calculate next number
            $nextNumber = 1;
            if (!empty($latest) && !empty($latest['Inventory_indent']['serial_number'])) {
                $lastCode = $latest['Inventory_indent']['serial_number']; // e.g., TGI252600057
                $numberPart = (int)substr($lastCode, strlen($prefix)); // Extract 00057 → 57
                $nextNumber = $numberPart + 1;
            }
        
            // Step 5: Final padded code
            $serial_number = $prefix . str_pad($nextNumber, 5, '0', STR_PAD_LEFT); // e.g., TGI252600058
        
            foreach ($checkeddatas as $checkeddata) {
                $skuId = $checkeddata['id'];
                $approvedQty = intval($checkeddata['sku_quantity']);
                $price = isset($checkeddata['price']) ? floatval($checkeddata['price']) : 0;
                
                $product_taxes=$this->Inventory_semifinished_tax->query("select SUM(tax_percentage) as total_tax from inventory_semifinished_tax where product_id='$skuId' ");
                $total_tax=round($product_taxes['0']['0']['total_tax'],2);
                
                $tax_value = round(($price*$approvedQty) * ($total_tax / 100),2);

                $skuamount=round(($price*$approvedQty) + $tax_value,2);
                
                // Update each indent item with approved quantity and price
                $this->Inventory_indent_items->updateAll(
                    [
                        'processed_quantity' => $approvedQty,
                        'consignment_id' => $consignment_id,
                        'processed_tax_value' => $tax_value,
                        'processed_amount' => $skuamount
                    ],
                    [
                        'indent_id' => $indentId,
                        'sku_id' => $skuId
                    ]
                );
    
                $amount += ($skuamount);
                
                $sku = $this->Inventory_semifinished->find('first', [
                    'conditions' => ['Inventory_semifinished.id' => $skuId],
                    'recursive' => -1
                ]);
                
                $ledgerprevdetails = $this->Stock_ledger->find('first', [
                    'conditions' => ['sku_id' => $skuId,'type'=>'DC','item_type'=>'semifinised','store_id'=>$locationId],
                    '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-$approvedQty;
                
                $ledgerData['Stock_ledger'] = [
                        'store_id'        => $locationId,
                        'sku_id'          => $skuId,
                        'sku_name'        => $sku['Inventory_semifinished']['name'],
                        'sku_price'       => $sku['Inventory_semifinished']['price'],
                        'unit_id'         => $sku['Inventory_semifinished']['unit'],
                        'unit_name'       => $sku['Inventory_semifinished']['unit_name'],
                        'record_id'       => $indentId,
                        'record_type'     => 'process_indent',
                        'quantity'        => $approvedQty,
                        'balance_stock'   => $newQuantity,
                        'actual_balance'  => $newQuantity,
                        'quantity_type'   => 'debit',
                        'item_type'       => 'semifinised',
                        'type'            => 'DC',
                        'created'         => date('Y-m-d H:i:s')
                ];
                $this->Stock_ledger->saveAll($ledgerData['Stock_ledger']);
                
                
                $ingredients = $this->Inventory_linking->find('all', [
                    'conditions' => ['parent_id' => $skuId,'parent_type' => 'Semifinished','component_type' => 'Sku', 'status' => 1]
                ]);
                // print_r($ingredients);exit;
                foreach ($ingredients as $ingredient) {
                    $sku_id = $ingredient['Inventory_linking']['component_id'];
                    $sku_quantity= $ingredient['Inventory_linking']['quantity']*$approvedQty;
                        
                    $ledgerprevdetails = $this->Stock_ledger->find('first', [
                        'conditions' => ['sku_id' => $sku_id,'store_id' =>$locationId,'item_type'=>'SKU' ,'type' =>'DC' ],
                        '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-$sku_quantity;
                    
                    $sku = $this->Inventory_sku->find('first', [
                        'conditions' => ['Inventory_sku.id' => $sku_id],
                        'recursive' => -1
                    ]);
                    
                    $ledgerData['Stock_ledger'] = [
                            'store_id'        => $locationId,
                            'sku_id'          => $ingredient['Inventory_linking']['component_id'],
                            'sku_name'        => $ingredient['Inventory_linking']['component_name'],
                            'sku_price'       => $sku['Inventory_sku']['price'],
                            'unit_id'         => $ingredient['Inventory_linking']['component_unit'],
                            'unit_name'       => $ingredient['Inventory_linking']['component_unit_name'],
                            'record_id'       => $indentId,
                            'record_type'     => 'process_indent',
                            'quantity'        => $sku_quantity,
                            'balance_stock'   => $newQuantity,
                            'actual_balance'  => $newQuantity,
                            'quantity_type'   => 'debit',
                            'item_type'       => 'SKU',
                            'type'            => 'DC',
                            'created'         => date('Y-m-d H:i:s')
                    ];
    				if(!$this->Stock_ledger->saveAll($ledgerData['Stock_ledger'])){
                        $success=false;
                    }
                }
                $success = true;
            }
    
            if ($success) {
                $currentDate = date('Y-m-d H:i:s');
    
                // Update the indent summary
                $this->Inventory_indent->updateAll(
                    [
                        'processed_amount' => $amount,
                        'processed_date' => "'$currentDate'",
                        'consignment_id' => $consignment_id,
                        'serial_number' => "'$serial_number'",
                        'status' => 3
                    ],
                    ['indent_id' => $indentId]
                );
        
                echo json_encode(['response_code' => 1, 'data' => 'Processed']);
            } else {
                echo json_encode(['response_code' => 0, 'data' => 'Indent items could not be updated.']);
            }
        } else {
            echo json_encode(['response_code' => 0, 'data' => 'Invalid request.']);
        }
    }

    public function edit_indent()
    {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'outlet', 'action' => 'login']);
        }
    
        $this->layout = "users";
        $id = $_REQUEST['id'];
    
        $role = $this->Session->read('Auth.User.role');
        $user_location = $this->Session->read('Auth.Location.id');
        
        // Fetch indent data
        $user = "SELECT *,
            (SELECT sku_quantity FROM inventory_indent_items 
             WHERE indent_id='$id' AND sku_id=inventory_skus.id) as quantity
            FROM inventory_skus 
            WHERE inventory_skus.status=1 
            ORDER BY inventory_skus.name DESC;";
        $users = $this->Inventory_sku->query($user);
    
        // Fetch existing indent record
        $indentData = $this->Inventory_indent->find('first', [
            'conditions' => ['indent_id' => $id],
            'recursive' => -1
        ]);
    
        $selected_location_id = $indentData['Inventory_indent']['location_id'];
        $selected_expiry = $indentData['Inventory_indent']['expiry'];
    
        $this->set(compact('users', 'id', 'locations', 'selected_location_id', 'selected_expiry'));
    }

    public function update_indent() 
    {
        $this->autoRender = false;
    
        $id = $this->Session->read('Auth.Location.id');
        $name = $this->Session->read('Auth.Location.name');
        
        if (isset($_POST['checkedData'])) {
            $checkeddatas = json_decode($_POST['checkedData'], true);
            $indentid = $_POST['indent_id'];
            $expiry = $_POST['expiry'];
            $location_id = isset($_POST['location_id']) ? $_POST['location_id'] : null;
            $location_name = '';
    
            // Optional: fetch location name if not passed from frontend
            if (!empty($location_id)) {
                $loc = $this->Location->find('first', [
                    'conditions' => ['Location.id' => $location_id],
                    'fields' => ['Location.name'],
                    'recursive' => -1
                ]);
                $location_name = isset($loc['Location']['name']) ? $loc['Location']['name'] : '';
            }
    
            // Delete existing indent and items
            $this->Inventory_indent_items->query("DELETE FROM inventory_indent_items WHERE indent_id = " . (int)$indentid);
            $this->Inventory_indent->query("DELETE FROM inventory_indent WHERE indent_id = " . (int)$indentid);
    
            $amount = 0;
            $chk = false;
    
            foreach ($checkeddatas as $checkeddata) {
                $skuid = $checkeddata['id'];
                $price = $checkeddata['price'];
                $sku_name = $checkeddata['sku_name'];
                $sku_brand = $checkeddata['sku_brand'];
                $unit_name = $checkeddata['unit_name'];
                $unit_id = $checkeddata['unit_id'];
                $quantity = $checkeddata['sku_quantity'];
    
                if (!empty($quantity)) {
                    $itemData = array(
                        'indent_id' => $indentid,
                        'sku_id' => $skuid,
                        'sku_name' => $sku_name,
                        'sku_brand' => $sku_brand,
                        'sku_unit' => $unit_id,
                        'sku_unit_name' => $unit_name,
                        'sku_price' => $price,
                        'sku_quantity' => $quantity
                    );
    
                    if ($this->Inventory_indent_items->saveAll($itemData)) {
                        $chk = true;
                    } else {
                        $chk = false;
                        $this->Flash->error(__('Internal indent could not be updated. Please, try again.'));
                    }
    
                    $productamount = $quantity * $price;
                    $amount += $productamount;
                }
            }
    
            if ($chk) {
                $indentData = array(
                    'indent_id' => $indentid,
                    'expiry' =>$expiry,
                    'created_by' => $id,
                    'created_by_name' => $name,
                    'location_id' => $location_id,
                    'location_name' => $location_name,
                    'total_amount' => $amount,
                    'is_updated' => 1
                );
    
                if ($this->Inventory_indent->saveAll($indentData)) {
                    echo json_encode(['response_code' => 1, 'data' => 'Updated']);
                } else {
                    echo json_encode(['response_code' => 0, 'data' => 'Internal indent could not be updated. Please, try again.']);
                }
            } else {
                echo json_encode(['response_code' => 0, 'data' => 'Internal indent items could not be updated. Please, try again.']);
            }
        }
    }
    
    public function grn()
    {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "users";
    
        // Default date range
        $startDate = date('m/d/Y', strtotime('-1 month'));
        $endDate = date('m/d/Y');
    
        if ($this->request->is(['post', 'put'])) {
            $daterange = $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $end_date = trim($dates[1]);
    
            $startDate = date('m/d/Y', strtotime($start_date));
            $endDate = date('m/d/Y', strtotime($end_date));
    
            $startdate = date('Y-m-d', strtotime($start_date));
            $enddate = date('Y-m-d', strtotime($end_date));
        } else {
            $startdate = date('Y-m-d', strtotime($startDate));
            $enddate = date('Y-m-d', strtotime($endDate));
        }
    
        // Auth info
        $locationId = $this->Session->read('Auth.User.location_id');
        $userRole = $this->Session->read('Auth.User.role');
    
        // Base condition
        $conditions = "created BETWEEN '$startdate 00:00:01' AND '$enddate 23:59:59'";
        if ($userRole !== 'admin') {
            $conditions .= " AND warehouse_id = '$locationId'";
        }
    
        // Indents by status
        $submittedIndents = $this->Inventory_indent->query("
            SELECT * FROM inventory_indent 
            WHERE $conditions AND status = 3 
            ORDER BY id DESC
        ");
        $approvedIndents = $this->Inventory_indent->query("
            SELECT * FROM inventory_indent 
            WHERE $conditions AND status = 4
            ORDER BY id DESC
        ");
        $yourStartDateValue = $startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        $this->set(compact('submittedIndents', 'approvedIndents'));
    }

    public function indent_pdf() {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "login"; // or use 'ajax' or a dedicated PDF layout
    
        if ($this->request->is(['post', 'put'])) {
            $po_id = $this->request->data['Report']['poid'];
            // Secure: Use bound parameters
            $indents = $this->Inventory_indent->query(
                "SELECT *,(SELECT print_line1  FROM `locations`where id=inventory_indent.location_id) as print_line1
                ,(SELECT print_line2  FROM `locations`where id=inventory_indent.location_id) as print_line2
                ,(SELECT print_line3  FROM `locations`where id=inventory_indent.location_id) as print_line3
                ,(SELECT print_line1  FROM `locations`where id=inventory_indent.warehouse_id) as warehouse_print_line1
                ,(SELECT print_line2  FROM `locations`where id=inventory_indent.warehouse_id) as warehouse_print_line2
                ,(SELECT print_line3  FROM `locations`where id=inventory_indent.warehouse_id) as warehouse_print_line3
                FROM inventory_indent 
                 WHERE inventory_indent.indent_id = ?", 
                [$po_id]
            );
    
            $items = $this->Inventory_indent_items->query(
                "SELECT * FROM inventory_indent_items 
                 WHERE indent_id = ? AND status != 0", 
                [$po_id]
            );
            $location_id=$indents[0]['inventory_indent']['location_id'];
    
            // Get location details - default static for now
            $locationdetail = $this->Location->find('first', [
                'conditions' => ['Location.id' => $location_id]
            ]);
    
            // Send data to the view
            $this->set(compact('po_id', 'indents', 'items', 'locationdetail'));
    
            // Optional: Force specific view if needed
            $this->render('indent_pdf'); // e.g., pdf_template.ctp
        }
    }
    
    
	public function stock_damage()
    {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "users";
    
        $startDate = date('m/d/Y', strtotime('-1 month'));
        $endDate = date('m/d/Y');
    
        if ($this->request->is(['post', 'put'])) {
            $daterange = $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $end_date = trim($dates[1]);
    
            $startDate = date('m/d/Y', strtotime($start_date));
            $endDate = date('m/d/Y', strtotime($end_date));
    
            $startdate = date('Y-m-d', strtotime($start_date));
            $enddate = date('Y-m-d', strtotime($end_date));
        } else {
            $startdate = date('Y-m-d', strtotime($startDate));
            $enddate = date('Y-m-d', strtotime($endDate));
        }
    
        // Session values
        $userRole = $this->Session->read('Auth.User.role');
        $locationId = $this->Session->read('Auth.User.location_id');
    
        // Build condition based on role
        $conditions = "created BETWEEN '$startdate 00:00:01' AND '$enddate 23:59:59'";
        if ($userRole !== 'admin') {
            $conditions .= " AND location_id = '$locationId'";
        }
    
        $users = $this->Inventory_damage->query("
            SELECT * FROM inventory_damage 
            WHERE $conditions and item_type='SKU' and type='Warehouse'
            ORDER BY id DESC
        ");
    
        $yourStartDateValue = $startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        $this->set(compact('users'));
    }
    
    public function damage_change_status() 
    {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $userId = $this->request->data['_id'];
    
            // Update user status
            $this->Inventory_damage->id = $userId;
            $newStatus = $this->Inventory_damage->field('status') == 1 ? 0 : 1;
            if ($this->Inventory_damage->save(['status' => $newStatus,'sync' => 0])) {
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }

	public function create_damage()
    {
        if (!$this->Session->check('Auth.User.id')) {
            $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "users";
    
        if ($this->Session->read('Auth.User.role') == 'admin') {
            $locations = $this->Location->find('all', ['conditions' => ['status' => 1,'type' => 'dc']]);
        } else {
            $location_id = $this->Session->read('Auth.User.location_id');
            $locations = $this->Location->find('all', [
                'conditions' => ['status' => 1, 'id' => $location_id,'type' => 'dc']
            ]);
        }
    
        $this->set(compact('locations'));
    
        $users = $this->Inventory_sku->find('all', [
            'conditions' => ['Inventory_sku.status' => 1],
            'order' => ['Inventory_sku.name DESC']
        ]);
        $this->set(compact('users'));
    }

    public function add_damage() 
    {
        $this->autoRender = false;
    
        if (!$this->Session->check('Auth.User.id')) {
            echo json_encode(['response_code' => 0, 'data' => 'User session expired.']);
            return;
        }
    
        $id = $this->Session->read('Auth.User.id');
        $name = $this->Session->read('Auth.User.name');
    
        if (isset($_POST['checkedData']) && isset($_POST['location_id'])) {
            $checkeddatas = json_decode($_POST['checkedData'], true);
            $location_id = (int)$_POST['location_id'];
            $damage_date = $_POST['damage_date'];
            
            // Validate location
            $location = $this->Location->find('first', [
                'conditions' => ['Location.id' => $location_id],
                'fields' => ['id', 'name'],
                'recursive' => -1
            ]);
    
            if (empty($location)) {
                echo json_encode(['response_code' => 0, 'data' => 'Invalid location selected.']);
                return;
            }
    
            // Generate unique indent_id
            do {
                // $txnid = '';
                $txnid = rand(1, 9);
                for ($i = 0; $i < 10; $i++) {
                    $txnid .= rand(0, 9);
                }
    
                $existing = $this->Inventory_damage->find('first', [
                    'conditions' => ['damage_id' => $txnid],
                    'recursive' => -1
                ]);
            } while ($existing);
    
            $amount = 0;
            $itemsSaved = true;
    
            foreach ($checkeddatas as $item) {
                $skuid = $item['id'];
                $price = $item['price'];
                $quantity = $item['sku_quantity'];
                
                $skuData = [
                    'location_id' => $location_id,
                    'location_name' => $location['Location']['name'],
                    'damage_id' => $txnid,
                    'item_id' => $skuid,
                    'item_name' => $item['sku_name'],
                    'item_category_id' => $item['cat_id'],
                    'item_category_name' => $item['cat_name'],
                    'unit_id' => $item['unit_id'],
                    'unit_name' => $item['unit_name'],
                    'item_price' => $price,
                    'quantity' => $quantity,
                    'amount' => $price*$quantity
                ];
                $this->Inventory_damage_item->create(); // ensure new row
                if (!$this->Inventory_damage_item->save($skuData)) {
                    $itemsSaved = false;
                    break;
                }
                
                $amount=$amount+($price*$quantity);
                
                $ledgerprevdetails = $this->Stock_ledger->find('first', [
                    'conditions' => ['sku_id' => $skuid,'type'=>'DC','item_type'=>'SKU','item_type'=>'SKU','store_id'=>$location_id],
                    '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 - $quantity;
                // print_r($ledger_prev_quantity);exit;
                $ledgerData['Stock_ledger'] = [
                        'store_id'        => $location_id,
                        'sku_id'          => $skuid,
                        'sku_name'        => $item['sku_name'],
                        'sku_price'       => $price,
                        'unit_id'         => $item['unit_id'],
                        'unit_name'       => $item['unit_name'],
                        'record_id'       => $txnid,
                        'record_type'     => 'damage',
                        'quantity'        => $quantity,
                        'balance_stock'   => $newQuantity,
                        'actual_balance'  => $newQuantity,
                        'quantity_type'   => 'debit',
                        'type'            => 'DC',
                        'created'         => date('Y-m-d H:i:s')
                ];
				$this->Stock_ledger->saveAll($ledgerData['Stock_ledger']);
                
            }
    
            if ($itemsSaved) {
                $damageData = [
                    'location_id' => $location_id,
                    'location_name' => $location['Location']['name'],
                    'damage_id' => $txnid,
                    'damage_date' => $damage_date,
                    'type' => 'Warehouse',
                    'item_type' => 'SKU',
                    'amount' => $amount
                ];
                
                $this->Inventory_damage->create();
                if ($this->Inventory_damage->save($damageData)) {
                    echo json_encode(['response_code' => 1, 'data' => 'saved']);
                } else {
                    echo json_encode(['response_code' => 0, 'data' => 'Failed to save damage master data.']);
                }
            } else {
                echo json_encode(['response_code' => 0, 'data' => 'Failed to save one or more items.']);
            }
        } else {
            echo json_encode(['response_code' => 0, 'data' => 'Invalid request. Missing data.']);
        }
    }

    public function view_damage()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		$id=$_REQUEST['id'];
    
        $indents = $this->Inventory_damage->query("SELECT * FROM inventory_damage where damage_id=$id");
        $this->set(compact('indents'));
        
		$items = $this->Inventory_damage_item->query("SELECT * FROM inventory_damage_items where damage_id=$id and status=1");
        
        $this->set(compact('items'));
        
        
	}
	
	public function edit_damage()
    {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "users";
        $id = $_REQUEST['id'];
    
        $user_id = $this->Session->read('Auth.User.id');
        $role = $this->Session->read('Auth.User.role');
        $user_location = $this->Session->read('Auth.User.location_id');
    
        // Location dropdown data
        if ($role == 'admin') {
            $locations = $this->Location->find('list', ['conditions' => ['status' => 1,'type' => 'dc']]);
        } else {
            $locations = $this->Location->find('list', [
                'conditions' => ['status' => 1, 'id' => $user_location,'type' => 'dc']
            ]);
        }
    
        // Fetch indent data
        $user = "SELECT *,
            (SELECT quantity FROM inventory_damage_items
             WHERE damage_id='$id' AND item_id=inventory_skus.id) as quantity 
            FROM inventory_skus 
            WHERE inventory_skus.status=1 
            ORDER BY inventory_skus.name DESC";
       
        $users = $this->Inventory_sku->query($user);
         
        // Fetch existing indent record
        $indentData = $this->Inventory_damage->find('first', [
            'conditions' => ['damage_id' => $id],
            'recursive' => -1
        ]);
        $selected_location_id = $indentData['Inventory_damage']['location_id'];
        $selected_date = $indentData['Inventory_damage']['damage_date'];
    
        $this->set(compact('users', 'id', 'locations', 'selected_location_id', 'selected_date'));
    }

    public function update_damage() 
    {
        $this->autoRender = false;
    
        $id = $this->Session->read('Auth.User.id');
        $name = $this->Session->read('Auth.User.name');
    
        if (isset($_POST['checkedData'])) {
            $checkeddatas = json_decode($_POST['checkedData'], true);
            $indentid = $_POST['indent_id'];
            $damage_date = $_POST['damage_date'];
            $location_id = isset($_POST['location_id']) ? $_POST['location_id'] : null;
            $location_name = '';
            
            // Optional: fetch location name if not passed from frontend
            if (!empty($location_id)) {
                $loc = $this->Location->find('first', [
                    'conditions' => ['Location.id' => $location_id],
                    'fields' => ['Location.name'],
                    'recursive' => -1
                ]);
                $location_name = isset($loc['Location']['name']) ? $loc['Location']['name'] : '';
            }
            
            $items = $this->Inventory_damage_item->find('all', [
                'conditions' => [
                    'damage_id' => $indentid,
                    'status' => 1
                ],
                'recursive' => -1
            ]);
            
            foreach ($items as $lastdata) {
                $damagedata = $lastdata['Inventory_damage_item']; // Use the correct model alias
                $skuid       = $damagedata['item_id'];
                $price       = $damagedata['item_price'];
                $sku_name    = $damagedata['item_name'];
                $sku_brand   = isset($damagedata['sku_brand']) ? $damagedata['sku_brand'] : ''; // if available
                $unit_name   = $damagedata['unit_name'];
                $unit_id     = $damagedata['unit_id'];
                $cat_id      = $damagedata['item_category_id'];
                $cat_name    = $damagedata['item_category_name'];
                $quantity    = $damagedata['quantity'];
            
                if (!empty($quantity)) {
                    $ledgerprevdetails = $this->Stock_ledger->find('first', [
                        'conditions' => [
                            'sku_id' => $skuid,
                            'type' => 'DC',
                            'item_type'=>'SKU',
                            'store_id' => $location_id
                        ],
                        '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 + $quantity;
            
                    $ledgerData = [
                        'Stock_ledger' => [
                            'store_id'        => $location_id,
                            'sku_id'          => $skuid,
                            'sku_name'        => $sku_name,
                            'sku_price'       => $price,
                            'unit_id'         => $unit_id,
                            'unit_name'       => $unit_name,
                            'record_id'       => $indentid,
                            'record_type'     => 'reverse_damage',
                            'quantity'        => $quantity,
                            'balance_stock'   => $newQuantity,
                            'actual_balance'  => $newQuantity,
                            'quantity_type'   => 'credit',
                            'type'            => 'DC',
                            'created'         => date('Y-m-d H:i:s')
                        ]
                    ];
            
                    $this->Stock_ledger->create(); // ensure a fresh entry
                    $this->Stock_ledger->save($ledgerData['Stock_ledger']);
                }
            }

    
            
            // Delete existing indent and items
            $this->Inventory_damage_item->query("DELETE FROM inventory_damage_items WHERE damage_id = " . (int)$indentid);
            $this->Inventory_damage->query("DELETE FROM inventory_damage WHERE damage_id = " . (int)$indentid);
    
            $amount = 0;
            $chk = false;
    
            foreach ($checkeddatas as $checkeddata) {
                $skuid = $checkeddata['id'];
                $price = $checkeddata['price'];
                $sku_name = $checkeddata['sku_name'];
                $sku_brand = $checkeddata['sku_brand'];
                $unit_name = $checkeddata['unit_name'];
                $unit_id = $checkeddata['unit_id'];
                $cat_id = $checkeddata['cat_id'];
                $cat_name = $checkeddata['cat_name'];
                $quantity = $checkeddata['sku_quantity'];
                
                if (!empty($quantity)) {
                    $itemData = array(
                        'location_id' => $location_id,
                        'location_name' => $location_name,
                        'damage_id' => $indentid,
                        'item_id' => $skuid,
                        'item_name' => $sku_name,
                        'item_category_id' => $cat_id,
                        'item_category_name' => $cat_name,
                        'unit_id' => $unit_id,
                        'unit_name' => $unit_name,
                        'item_price' => $price,
                        'quantity' => $quantity,
                        'amount' => $price*$quantity
                    );
                    
                    if ($this->Inventory_damage_item->saveAll($itemData)) {
                        
                        $ledgerprevdetails = $this->Stock_ledger->find('first', [
                            'conditions' => ['sku_id' => $skuid,'type'=>'DC','item_type'=>'SKU','store_id'=>$location_id],
                            '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 - $quantity;
                        // print_r($ledger_prev_quantity);exit;
                        $ledgerData['Stock_ledger'] = [
                                'store_id'        => $location_id,
                                'sku_id'          => $skuid,
                                'sku_name'        => $sku_name,
                                'sku_price'       => $price,
                                'unit_id'         => $unit_id,
                                'unit_name'       => $unit_name,
                                'record_id'       => $indentid,
                                'record_type'     => 'update_damage',
                                'quantity'        => $quantity,
                                'balance_stock'   => $newQuantity,
                                'actual_balance'  => $newQuantity,
                                'quantity_type'   => 'debit',
                                'type'            => 'DC',
                                'created'         => date('Y-m-d H:i:s')
                        ];
        				$this->Stock_ledger->saveAll($ledgerData['Stock_ledger']);
                        
                        $chk = true;
                    } else {
                        $chk = false;
                        $this->Flash->error(__('Damage could not be updated. Please, try again.'));
                    }
    
                    // $productamount = $quantity * $price;
                    // $amount += $productamount;
                    $amount += ($price*$quantity);
                }
            }
    
            if ($chk) {
                $indentData = array(
                    'location_id' => $location_id,
                    'location_name' => $location_name,
                    'damage_id' => $indentid,
                    'damage_date' => $damage_date,
                    'type' => 'Warehouse',
                    'item_type' => 'SKU',
                    'amount' => $amount
                );
    
                if ($this->Inventory_damage->saveAll($indentData)) {
                    echo json_encode(['response_code' => 1, 'data' => 'Updated']);
                } else {
                    echo json_encode(['response_code' => 0, 'data' => 'Damage could not be updated. Please, try again.']);
                }
            } else {
                echo json_encode(['response_code' => 0, 'data' => 'Damage items could not be updated. Please, try again.']);
            }
        }
    }
    
    public function semi_stock_damage()
    {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "users";
    
        $startDate = date('m/d/Y', strtotime('-1 month'));
        $endDate = date('m/d/Y');
    
        if ($this->request->is(['post', 'put'])) {
            $daterange = $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $end_date = trim($dates[1]);
    
            $startDate = date('m/d/Y', strtotime($start_date));
            $endDate = date('m/d/Y', strtotime($end_date));
    
            $startdate = date('Y-m-d', strtotime($start_date));
            $enddate = date('Y-m-d', strtotime($end_date));
        } else {
            $startdate = date('Y-m-d', strtotime($startDate));
            $enddate = date('Y-m-d', strtotime($endDate));
        }
    
        // Session values
        $userRole = $this->Session->read('Auth.User.role');
        $locationId = $this->Session->read('Auth.User.location_id');
    
        // Build condition based on role
        $conditions = "created BETWEEN '$startdate 00:00:01' AND '$enddate 23:59:59'";
        if ($userRole !== 'admin') {
            $conditions .= " AND location_id = '$locationId'";
        }
    
        $users = $this->Inventory_damage->query("
            SELECT * FROM inventory_damage 
            WHERE $conditions and item_type='semifinished' and type='Warehouse'
            ORDER BY id DESC
        ");
    
        $yourStartDateValue = $startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        $this->set(compact('users'));
    }
    
    public function semi_damage_change_status() 
    {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $userId = $this->request->data['_id'];
    
            // Update user status
            $this->Inventory_damage->id = $userId;
            $newStatus = $this->Inventory_damage->field('status') == 1 ? 0 : 1;
            if ($this->Inventory_damage->save(['status' => $newStatus,'sync' => 0])) {
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }

	public function semi_create_damage()
    {
        if (!$this->Session->check('Auth.User.id')) {
            $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "users";
    
        if ($this->Session->read('Auth.User.role') == 'admin') {
            $locations = $this->Location->find('all', ['conditions' => ['status' => 1,'type' => 'dc']]);
        } else {
            $location_id = $this->Session->read('Auth.User.location_id');
            $locations = $this->Location->find('all', [
                'conditions' => ['status' => 1, 'id' => $location_id,'type' => 'dc']
            ]);
        }
    
        $this->set(compact('locations'));
    
        $users = $this->Inventory_semifinished->find('all', [
            'conditions' => ['Inventory_semifinished.status' => 1],
            'order' => ['Inventory_semifinished.name DESC']
        ]);
        $this->set(compact('users'));
    }

    public function semi_add_damage() 
    {
        $this->autoRender = false;
    
        if (!$this->Session->check('Auth.User.id')) {
            echo json_encode(['response_code' => 0, 'data' => 'User session expired.']);
            return;
        }
    
        $id = $this->Session->read('Auth.User.id');
        $name = $this->Session->read('Auth.User.name');
    
        if (isset($_POST['checkedData']) && isset($_POST['location_id'])) {
            $checkeddatas = json_decode($_POST['checkedData'], true);
            $location_id = (int)$_POST['location_id'];
            $damage_date = $_POST['damage_date'];
            
            // Validate location
            $location = $this->Location->find('first', [
                'conditions' => ['Location.id' => $location_id],
                'fields' => ['id', 'name'],
                'recursive' => -1
            ]);
    
            if (empty($location)) {
                echo json_encode(['response_code' => 0, 'data' => 'Invalid location selected.']);
                return;
            }
    
            // Generate unique indent_id
            do {
                // $txnid = '';
                $txnid = rand(1, 9);
                for ($i = 0; $i < 10; $i++) {
                    $txnid .= rand(0, 9);
                }
    
                $existing = $this->Inventory_damage->find('first', [
                    'conditions' => ['damage_id' => $txnid],
                    'recursive' => -1
                ]);
            } while ($existing);
    
            $amount = 0;
            $itemsSaved = true;
    
            foreach ($checkeddatas as $item) {
                $skuid = $item['id'];
                $price = $item['price'];
                $quantity = $item['sku_quantity'];
                
                $skuData = [
                    'location_id' => $location_id,
                    'location_name' => $location['Location']['name'],
                    'damage_id' => $txnid,
                    'item_id' => $skuid,
                    'item_name' => $item['sku_name'],
                    'item_category_id' => $item['cat_id'],
                    'item_category_name' => $item['cat_name'],
                    'unit_id' => $item['unit_id'],
                    'unit_name' => $item['unit_name'],
                    'item_price' => $price,
                    'quantity' => $quantity,
                    'amount' => $price*$quantity
                ];
                $this->Inventory_damage_item->create(); // ensure new row
                if (!$this->Inventory_damage_item->save($skuData)) {
                    $itemsSaved = false;
                    break;
                }
                
                $amount=$amount+($price*$quantity);
                
                $ledgerprevdetails = $this->Stock_ledger->find('first', [
                    'conditions' => ['sku_id' => $skuid,'type'=>'DC','item_type'=>'semifinished','store_id'=>$location_id],
                    '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 - $quantity;
                // print_r($ledger_prev_quantity);exit;
                $ledgerData['Stock_ledger'] = [
                        'store_id'        => $location_id,
                        'sku_id'          => $skuid,
                        'sku_name'        => $item['sku_name'],
                        'sku_price'       => $price,
                        'unit_id'         => $item['unit_id'],
                        'unit_name'       => $item['unit_name'],
                        'record_id'       => $txnid,
                        'record_type'     => 'damage',
                        'quantity'        => $quantity,
                        'balance_stock'   => $newQuantity,
                        'actual_balance'  => $newQuantity,
                        'quantity_type'   => 'debit',
                        'type'            => 'DC',
                        'item_type'       => 'semifinished',
                        'created'         => date('Y-m-d H:i:s')
                ];
				$this->Stock_ledger->saveAll($ledgerData['Stock_ledger']);
                
            }
    
            if ($itemsSaved) {
                $damageData = [
                    'location_id' => $location_id,
                    'location_name' => $location['Location']['name'],
                    'damage_id' => $txnid,
                    'damage_date' => $damage_date,
                    'type' => 'Warehouse',
                    'item_type' => 'semifinished',
                    'amount' => $amount
                ];
                
                $this->Inventory_damage->create();
                if ($this->Inventory_damage->save($damageData)) {
                    echo json_encode(['response_code' => 1, 'data' => 'saved']);
                } else {
                    echo json_encode(['response_code' => 0, 'data' => 'Failed to save damage master data.']);
                }
            } else {
                echo json_encode(['response_code' => 0, 'data' => 'Failed to save one or more items.']);
            }
        } else {
            echo json_encode(['response_code' => 0, 'data' => 'Invalid request. Missing data.']);
        }
    }

    public function semi_view_damage()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		$id=$_REQUEST['id'];
    
        $indents = $this->Inventory_damage->query("SELECT * FROM inventory_damage where damage_id=$id");
        $this->set(compact('indents'));
        
		$items = $this->Inventory_damage_item->query("SELECT * FROM inventory_damage_items where damage_id=$id and status=1");
        
        $this->set(compact('items'));
        
        
	}
	
	public function semi_edit_damage()
    {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "users";
        $id = $_REQUEST['id'];
    
        $user_id = $this->Session->read('Auth.User.id');
        $role = $this->Session->read('Auth.User.role');
        $user_location = $this->Session->read('Auth.User.location_id');
    
        // Location dropdown data
        if ($role == 'admin') {
            $locations = $this->Location->find('list', ['conditions' => ['status' => 1,'type' => 'dc']]);
        } else {
            $locations = $this->Location->find('list', [
                'conditions' => ['status' => 1, 'id' => $user_location,'type' => 'dc']
            ]);
        }
    
        // Fetch indent data
        $user = "SELECT *,
            (SELECT quantity FROM inventory_damage_items
             WHERE damage_id='$id' AND item_id=inventory_semifinished.id) as quantity 
            FROM inventory_semifinished 
            WHERE inventory_semifinished.status=1 
            ORDER BY inventory_semifinished.name DESC";
       
        $users = $this->Inventory_semifinished->query($user);
         
        // Fetch existing indent record
        $indentData = $this->Inventory_damage->find('first', [
            'conditions' => ['damage_id' => $id],
            'recursive' => -1
        ]);
        $selected_location_id = $indentData['Inventory_damage']['location_id'];
        $selected_date = $indentData['Inventory_damage']['damage_date'];
    
        $this->set(compact('users', 'id', 'locations', 'selected_location_id', 'selected_date'));
    }

    public function semi_update_damage() 
    {
        $this->autoRender = false;
    
        $id = $this->Session->read('Auth.User.id');
        $name = $this->Session->read('Auth.User.name');
    
        if (isset($_POST['checkedData'])) {
            $checkeddatas = json_decode($_POST['checkedData'], true);
            $indentid = $_POST['indent_id'];
            $damage_date = $_POST['damage_date'];
            $location_id = isset($_POST['location_id']) ? $_POST['location_id'] : null;
            $location_name = '';
            
            // Optional: fetch location name if not passed from frontend
            if (!empty($location_id)) {
                $loc = $this->Location->find('first', [
                    'conditions' => ['Location.id' => $location_id],
                    'fields' => ['Location.name'],
                    'recursive' => -1
                ]);
                $location_name = isset($loc['Location']['name']) ? $loc['Location']['name'] : '';
            }
            
            $items = $this->Inventory_damage_item->find('all', [
                'conditions' => [
                    'damage_id' => $indentid,
                    'status' => 1
                ],
                'recursive' => -1
            ]);
            
            foreach ($items as $lastdata) {
                $damagedata = $lastdata['Inventory_damage_item']; // Use the correct model alias
                $skuid       = $damagedata['item_id'];
                $price       = $damagedata['item_price'];
                $sku_name    = $damagedata['item_name'];
                $sku_brand   = isset($damagedata['sku_brand']) ? $damagedata['sku_brand'] : ''; // if available
                $unit_name   = $damagedata['unit_name'];
                $unit_id     = $damagedata['unit_id'];
                $cat_id      = $damagedata['item_category_id'];
                $cat_name    = $damagedata['item_category_name'];
                $quantity    = $damagedata['quantity'];
            
                if (!empty($quantity)) {
                    $ledgerprevdetails = $this->Stock_ledger->find('first', [
                        'conditions' => [
                            'sku_id' => $skuid,
                            'item_type' => 'semifinished',
                            'type' => 'DC',
                            'store_id' => $location_id
                        ],
                        '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 + $quantity;
            
                    $ledgerData = [
                        'Stock_ledger' => [
                            'store_id'        => $location_id,
                            'sku_id'          => $skuid,
                            'sku_name'        => $sku_name,
                            'sku_price'       => $price,
                            'unit_id'         => $unit_id,
                            'unit_name'       => $unit_name,
                            'record_id'       => $indentid,
                            'record_type'     => 'reverse_damage',
                            'quantity'        => $quantity,
                            'balance_stock'   => $newQuantity,
                            'actual_balance'  => $newQuantity,
                            'quantity_type'   => 'credit',
                            'item_type'       => 'semifinished',
                            'type'            => 'DC',
                            'created'         => date('Y-m-d H:i:s')
                        ]
                    ];
            
                    $this->Stock_ledger->create(); // ensure a fresh entry
                    $this->Stock_ledger->save($ledgerData['Stock_ledger']);
                }
            }

    
            
            // Delete existing indent and items
            $this->Inventory_damage_item->query("DELETE FROM inventory_damage_items WHERE damage_id = " . (int)$indentid);
            $this->Inventory_damage->query("DELETE FROM inventory_damage WHERE damage_id = " . (int)$indentid);
    
            $amount = 0;
            $chk = false;
    
            foreach ($checkeddatas as $checkeddata) {
                $skuid = $checkeddata['id'];
                $price = $checkeddata['price'];
                $sku_name = $checkeddata['sku_name'];
                $sku_brand = $checkeddata['sku_brand'];
                $unit_name = $checkeddata['unit_name'];
                $unit_id = $checkeddata['unit_id'];
                $cat_id = $checkeddata['cat_id'];
                $cat_name = $checkeddata['cat_name'];
                $quantity = $checkeddata['sku_quantity'];
                
                if (!empty($quantity)) {
                    $itemData = array(
                        'location_id' => $location_id,
                        'location_name' => $location_name,
                        'damage_id' => $indentid,
                        'item_id' => $skuid,
                        'item_name' => $sku_name,
                        'item_category_id' => $cat_id,
                        'item_category_name' => $cat_name,
                        'unit_id' => $unit_id,
                        'unit_name' => $unit_name,
                        'item_price' => $price,
                        'quantity' => $quantity,
                        'amount' => $price*$quantity
                    );
                    
                    if ($this->Inventory_damage_item->saveAll($itemData)) {
                        
                        $ledgerprevdetails = $this->Stock_ledger->find('first', [
                            'conditions' => ['sku_id' => $skuid,'type'=>'DC','item_type'=>'semifinished','store_id'=>$location_id],
                            '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 - $quantity;
                        // print_r($ledger_prev_quantity);exit;
                        $ledgerData['Stock_ledger'] = [
                                'store_id'        => $location_id,
                                'sku_id'          => $skuid,
                                'sku_name'        => $sku_name,
                                'sku_price'       => $price,
                                'unit_id'         => $unit_id,
                                'unit_name'       => $unit_name,
                                'record_id'       => $indentid,
                                'record_type'     => 'update_damage',
                                'quantity'        => $quantity,
                                'balance_stock'   => $newQuantity,
                                'actual_balance'  => $newQuantity,
                                'quantity_type'   => 'debit',
                                'type'            => 'DC',
                                'item_type'       => 'semifinished',
                                'created'         => date('Y-m-d H:i:s')
                        ];
        				$this->Stock_ledger->saveAll($ledgerData['Stock_ledger']);
                        
                        $chk = true;
                    } else {
                        $chk = false;
                        $this->Flash->error(__('Damage could not be updated. Please, try again.'));
                    }
    
                    // $productamount = $quantity * $price;
                    // $amount += $productamount;
                    $amount += ($price*$quantity);
                }
            }
    
            if ($chk) {
                $indentData = array(
                    'location_id' => $location_id,
                    'location_name' => $location_name,
                    'damage_id' => $indentid,
                    'damage_date' => $damage_date,
                    'type' => 'Warehouse',
                    'item_type' => 'semifinished',
                    'amount' => $amount
                );
    
                if ($this->Inventory_damage->saveAll($indentData)) {
                    echo json_encode(['response_code' => 1, 'data' => 'Updated']);
                } else {
                    echo json_encode(['response_code' => 0, 'data' => 'Damage could not be updated. Please, try again.']);
                }
            } else {
                echo json_encode(['response_code' => 0, 'data' => 'Damage items could not be updated. Please, try again.']);
            }
        }
    }
    
    public function auditstock()
    {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "users";
    
        // Default date range (last 30 days)
        $startDate = date('m/d/Y', strtotime('-7 days'));
        $endDate = date('m/d/Y');
        
        // If form submitted, get date range
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        } 
    
        // Auth User Info
        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_id'] ?? 0;
    
        // Base conditions
        $baseConditions = [
            // 'Audit_stock.auditto >=' => $startdate,
            'auditto <=' => $enddate
        ];
    
        // Location filter for non-admins
        if ($userRole !== 'admin') {
            // $baseConditions['Audit_stock.location_id'] = $userLocationId;
        }
        
        $sdate=$startdate.' 00:00:01';
        $edate=$enddate.' 23:59:59';
       
       
        $preparedStocks = $this->Audit_stock->find('all', [
            'conditions' => [
                'Audit_stock.status' => 1,
                'Audit_stock.updateon BETWEEN ? AND ?' => [$sdate, $edate],
                'Audit_stock.item_type' => 'SKU',
                'Audit_stock.type' => 'DC'
            ],
            'fields' => ['Audit_stock.*'], // Ensure ID is included
            'order' => ['Audit_stock.id' => 'DESC'],
            'recursive' => 1
        ]);
        

    
        // Pass to view
        $daterangeFormatted = $startDate . ' - ' . $endDate;
        $this->set(compact('daterangeFormatted', 'startdate', 'enddate', 'preparedStocks'));
    }

    public function create_audit_stock()
    {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "users";
    
        $userId = $this->Session->read('Auth.User.id');
        $today = date("Y-m-d");
        $currentTime = date("H:i");
        $this->set(compact('today', 'currentTime'));
    
        // Load SKU list
        $skus = $this->Inventory_sku->query("SELECT * FROM inventory_skus WHERE status = 1 ORDER BY name DESC");
        $this->set(compact('skus'));
    
        if ($this->request->is(['post', 'put'])) {
            $data = $this->request->data;
    
            $remarks = trim($data['remarks']);
            $auditDate = $data['audit_date'] ?? $today;
            $auditTime = $data['audit_time'] ?? $currentTime;
            $submitAll = $data['submit_all_items'] ?? 'no';
            $createdTime = date('Y-m-d H:i:s');
    
            $authUser = $this->Session->read('Auth.User');
            $storeId = $authUser['location_id'] ?? 0;
            
            $loc = $this->Location->find('first', [
                'conditions' => ['Location.id' => $storeId],
                'fields' => ['Location.name'],
                'recursive' => -1
            ]);
            $store_name = isset($loc['Location']['name']) ? $loc['Location']['name'] : '';
            
            do {
                // Generate a numeric-only ID: remove non-digits and trim to 12 digits
                $pos_audit_id = preg_replace('/\D/', '', substr(sha1(uniqid() . rand()), 0, 32));
                $pos_audit_id = substr($pos_audit_id, 0, 12); // Adjust digit length as needed
                if ($pos_audit_id[0] === '0') {
                    $pos_audit_id[0] = strval(rand(1, 9)); // replace first digit with 1–9
                }
                
                // Check for uniqueness in both pos_auditstock and temp_audit_stock tables
                $existsMain = $this->Audit_stock->find('count', [
                    'conditions' => ['Audit_stock.pos_audit_id' => $pos_audit_id],
                    'recursive' => -1
                ]);
            
                $existsTemp = $this->Temp_audit_stock->find('count', [
                    'conditions' => ['Temp_audit_stock.pos_audit_id' => $pos_audit_id],
                    'recursive' => -1
                ]);
            
            } while ($existsMain > 0 || $existsTemp > 0);
            
            $selectAll = ($submitAll === 'yes') ? 1 : 0;
    
            $header = [
                'pos_audit_id' => $pos_audit_id,
                'store_id' => $storeId,
                'store_name' => $store_name,
                'remarks' => $remarks,
                'status' => 1,
                'select_all' => $selectAll,
                'updateon' => $createdTime
            ];
    
            $quantities = $data['quantity'] ?? [];
            // print_r($data['quantity']);exit;
            
                
            $items = [];
            
            if (isset($data['prepare_submit'])) {
                foreach ($quantities as $skuId => $qty) {
                    $qty = floatval($qty);
                    if ($qty <= 0) continue;
                
                    // Get last audit info
                    $lastAudit = $this->Audit_stock_items->find('first', [
                        'conditions' => ['sku_id' => $skuId,'item_type' => 'sku','type' => 'DC', 'status' => 1],
                        'order' => ['id DESC'],
                        'fields' => ['physicalstock', 'auditto'],
                        'recursive' => -1
                    ]);
                
                    $openingstock = 0;
                    $auditfrom = '2022-01-01 00:00:01';
                
                    if (!empty($lastAudit)) {
                        $openingstock = floatval($lastAudit['Audit_stock_items']['physicalstock']);
                        $auditfrom = $lastAudit['Audit_stock_items']['auditto'];
                    }
                
                    $variance = $qty - $openingstock;
                    $auditto = $auditDate . ' ' . $auditTime . ':00';
                
                    $skuName = $data['sku_name'][$skuId] ?? '';
                    $unitId = (int)($data['unit_id'][$skuId] ?? 0);
                    $unitName = $data['unit_name'][$skuId] ?? '';
                    $sku_price=$data['price'][$skuId] ?? 0;
                    
                    $auditItem = [
                        'sku_id' => $skuId,
                        'pos_audit_id' => $pos_audit_id,
                        'sku_name' => $skuName,
                        'sku_unit' => $unitId,
                        'sku_unit_name' => $unitName,
                        'sku_price'=>$sku_price,
                        'openingstock' => $openingstock,
                        'closingstock' => 0,
                        'physicalstock' => $qty,
                        'variance' => $variance,
                        'auditfrom' => $auditfrom,
                        'auditto' => $auditto,
                        'remarks' => $remarks,
                        'status' => 1,
                        'created' => $createdTime,
                        'modified' => $createdTime
                    ];
                
                    $this->Audit_stock_items->create();
                    $this->Audit_stock_items->save($auditItem);
                
                    
                    $skuquantityForLedger = $qty;
                
                    $ledgerEntries = $this->Stock_ledger->find('all', [
                        'conditions' => [
                            'store_id' => $storeId,
                            'sku_id' => $skuId,
                            'item_type'=>'SKU',
                            'type' => 'DC',
                            'record_type !=' => 'audit_stock',
                            'created >' => $auditto
                        ],
                        'order' => ['created ASC'],
                        'recursive' => -1
                    ]);
                
                    if (!empty($ledgerEntries)) {
                        foreach ($ledgerEntries as $entry) {
                            $ledger = $entry['Stock_ledger'];
                            $prevQuantity = floatval($ledger['quantity']);
                            $quantityType = $ledger['quantity_type'];
                
                            $newBalance = ($quantityType === 'credit')
                                ? $skuquantityForLedger + $prevQuantity
                                : $skuquantityForLedger - $prevQuantity;
                
                            $this->Stock_ledger->id = $ledger['id'];
                            $this->Stock_ledger->save([
                                'variance' => $variance,
                                'actual_balance' => $newBalance,
                                'variance_type' => 'back_audit',
                                'variance_id' => $pos_audit_id,
                                'modified' => $createdTime
                            ]);
                
                            $skuquantityForLedger = $newBalance;
                        }
                    } else {
                        // Insert fresh ledger row
                        $this->Stock_ledger->create();
                        $this->Stock_ledger->save([
                            'store_id' => $storeId,
                            'sku_id' => $skuId,
                            'sku_name' => $skuName,
                            'sku_price'=>$sku_price,
                            'unit_id' => $unitId,
                            'unit_name' => $unitName,
                            'record_id' => $pos_audit_id,
                            'record_type' => 'audit_stock',
                            'quantity' => 0,
                            'balance_stock' => 0,
                            'variance' => $variance,
                            'actual_balance' => $qty,
                            'variance_type' => 'audit',
                            'variance_id' => $pos_audit_id,
                            'type' => 'DC',
                            'quantity_type' => 'audit',
                            'created' => $auditto,
                            'modified' => $createdTime
                        ]);
                    }
                }
                
                // Save audit_stock header
                if ($this->Audit_stock->save($header)) {
                    $this->Flash->success(__('Audit submitted successfully.'));
                    return $this->redirect(['action' => 'auditstock']);
                } else {
                    $this->Flash->error(__('Failed to submit audit.'));
                }
            }
        }
    }
    
    public function view_audit()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		$id=$_REQUEST['id'];
    
        $indents = $this->Audit_stock->query("SELECT * FROM pos_auditstock where pos_audit_id=$id");
        $this->set(compact('indents'));
        
		$items = $this->Audit_stock_items->query("SELECT * FROM pos_auditstock_items where pos_audit_id=$id and status=1");
        
        $this->set(compact('items'));
        
        
	}
	
	public function semi_auditstock()
    {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "users";
    
        // Default date range (last 30 days)
        $startDate = date('m/d/Y', strtotime('-7 days'));
        $endDate = date('m/d/Y');
        
        // If form submitted, get date range
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        } 
    
        // Auth User Info
        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_id'] ?? 0;
    
        // Base conditions
        $baseConditions = [
            // 'Audit_stock.auditto >=' => $startdate,
            'auditto <=' => $enddate
        ];
    
        // Location filter for non-admins
        if ($userRole !== 'admin') {
            // $baseConditions['Audit_stock.location_id'] = $userLocationId;
        }
        
        $sdate=$startdate.' 00:00:01';
        $edate=$enddate.' 23:59:59';
       
       
        $preparedStocks = $this->Audit_stock->find('all', [
            'conditions' => [
                'Audit_stock.status' => 1,
                'Audit_stock.updateon BETWEEN ? AND ?' => [$sdate, $edate],
                'Audit_stock.item_type' => 'Semifinished',
                'Audit_stock.type' => 'DC'
            ],
            'fields' => ['Audit_stock.*'], // Ensure ID is included
            'order' => ['Audit_stock.id' => 'DESC'],
            'recursive' => 1
        ]);



    
        // Pass to view
        $daterangeFormatted = $startDate . ' - ' . $endDate;
        $this->set(compact('daterangeFormatted', 'startdate', 'enddate', 'preparedStocks'));
    }

    public function semi_create_audit_stock()
    {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "users";
    
        $userId = $this->Session->read('Auth.User.id');
        $today = date("Y-m-d");
        $currentTime = date("H:i");
        $this->set(compact('today', 'currentTime'));
    
        // Load SKU list
        $skus = $this->Inventory_semifinished->query("SELECT * FROM inventory_semifinished WHERE status = 1 ORDER BY name DESC");
        $this->set(compact('skus'));
    
        if ($this->request->is(['post', 'put'])) {
            $data = $this->request->data;
    
            $remarks = trim($data['remarks']);
            $auditDate = $data['audit_date'] ?? $today;
            $auditTime = $data['audit_time'] ?? $currentTime;
            $submitAll = $data['submit_all_items'] ?? 'no';
            $createdTime = date('Y-m-d H:i:s');
    
            $authUser = $this->Session->read('Auth.User');
            $storeId = $authUser['location_id'] ?? 0;
            $store_name = $authUser['location_name'] ?? 0;
            
            // $loc = $this->Location->find('first', [
            //     'conditions' => ['Location.id' => $storeId],
            //     'fields' => ['Location.name'],
            //     'recursive' => -1
            // ]);
            
            // $store_name = isset($loc['Location']['name']) ? $loc['Location']['name'] : '';
            
            do {
                // Generate a numeric-only ID: remove non-digits and trim to 12 digits
                $pos_audit_id = preg_replace('/\D/', '', substr(sha1(uniqid() . rand()), 0, 32));
                $pos_audit_id = substr($pos_audit_id, 0, 12); // Adjust digit length as needed
                if ($pos_audit_id[0] === '0') {
                    $pos_audit_id[0] = strval(rand(1, 9)); // replace first digit with 1–9
                }
                
                // Check for uniqueness in both pos_auditstock and temp_audit_stock tables
                $existsMain = $this->Audit_stock->find('count', [
                    'conditions' => ['Audit_stock.pos_audit_id' => $pos_audit_id],
                    'recursive' => -1
                ]);
            
                $existsTemp = $this->Temp_audit_stock->find('count', [
                    'conditions' => ['Temp_audit_stock.pos_audit_id' => $pos_audit_id],
                    'recursive' => -1
                ]);
            
            } while ($existsMain > 0 || $existsTemp > 0);
            
            $selectAll = ($submitAll === 'yes') ? 1 : 0;
    
            $header = [
                'pos_audit_id' => $pos_audit_id,
                'store_id' => $storeId,
                'store_name' => $store_name,
                'remarks' => $remarks,
                'status' => 1,
                'item_type' => 'semifinished',
                'type' => 'DC',
                'select_all' => $selectAll,
                'updateon' => $createdTime
            ];
    
            $quantities = $data['quantity'] ?? [];
            // print_r($data['quantity']);exit;
            
                
            $items = [];
            
            if (isset($data['prepare_submit'])) {
                foreach ($quantities as $skuId => $qty) {
                    $qty = floatval($qty);
                    if ($qty <= 0) continue;
                
                    // Get last audit info
                    $lastAudit = $this->Audit_stock_items->find('first', [
                        'conditions' => ['sku_id' => $skuId,'item_type' => 'Semifinished','type' => 'DC', 'status' => 1],
                        'order' => ['id DESC'],
                        'fields' => ['physicalstock', 'auditto'],
                        'recursive' => -1
                    ]);
                
                    $openingstock = 0;
                    $auditfrom = '2022-01-01 00:00:01';
                
                    if (!empty($lastAudit)) {
                        $openingstock = floatval($lastAudit['Audit_stock_items']['physicalstock']);
                        $auditfrom = $lastAudit['Audit_stock_items']['auditto'];
                    }
                
                    $variance = $qty - $openingstock;
                    $auditto = $auditDate . ' ' . $auditTime . ':00';
                
                    $skuName = $data['sku_name'][$skuId] ?? '';
                    $unitId = (int)($data['unit_id'][$skuId] ?? 0);
                    $unitName = $data['unit_name'][$skuId] ?? '';
                    $sku_price=$data['price'][$skuId] ?? 0;
                    
                    $auditItem = [
                        'sku_id' => $skuId,
                        'pos_audit_id' => $pos_audit_id,
                        'sku_name' => $skuName,
                        'item_type' => 'Semifinished',
                        'type' => 'DC',
                        'sku_unit' => $unitId,
                        'sku_unit_name' => $unitName,
                        'sku_price'=>$sku_price,
                        'openingstock' => $openingstock,
                        'closingstock' => 0,
                        'physicalstock' => $qty,
                        'variance' => $variance,
                        'auditfrom' => $auditfrom,
                        'auditto' => $auditto,
                        'remarks' => $remarks,
                        'status' => 1,
                        'created' => $createdTime,
                        'modified' => $createdTime
                    ];
                
                    $this->Audit_stock_items->create();
                    $this->Audit_stock_items->save($auditItem);
                
                    
                    $skuquantityForLedger = $qty;
                
                    $ledgerEntries = $this->Stock_ledger->find('all', [
                        'conditions' => [
                            'store_id' => $storeId,
                            'sku_id' => $skuId,
                            'item_type'=>'Semifinished',
                            'type' => 'DC',
                            'record_type !=' => 'audit_stock',
                            'created >' => $auditto
                        ],
                        'order' => ['created ASC'],
                        'recursive' => -1
                    ]);
                
                    if (!empty($ledgerEntries)) {
                        foreach ($ledgerEntries as $entry) {
                            $ledger = $entry['Stock_ledger'];
                            $prevQuantity = floatval($ledger['quantity']);
                            $quantityType = $ledger['quantity_type'];
                
                            $newBalance = ($quantityType === 'credit')
                                ? $skuquantityForLedger + $prevQuantity
                                : $skuquantityForLedger - $prevQuantity;
                
                            $this->Stock_ledger->id = $ledger['id'];
                            $this->Stock_ledger->save([
                                'variance' => $variance,
                                'actual_balance' => $newBalance,
                                'variance_type' => 'back_audit',
                                'variance_id' => $pos_audit_id,
                                'modified' => $createdTime
                            ]);
                
                            $skuquantityForLedger = $newBalance;
                        }
                    } else {
                        // Insert fresh ledger row
                        $this->Stock_ledger->create();
                        $this->Stock_ledger->save([
                            'store_id' => $storeId,
                            'sku_id' => $skuId,
                            'sku_name' => $skuName,
                            'sku_price'=>$sku_price,
                            'unit_id' => $unitId,
                            'unit_name' => $unitName,
                            'record_id' => $pos_audit_id,
                            'record_type' => 'audit_stock',
                            'quantity' => 0,
                            'balance_stock' => 0,
                            'variance' => $variance,
                            'actual_balance' => $qty,
                            'variance_type' => 'audit',
                            'variance_id' => $pos_audit_id,
                            'item_type' => 'Semifinished',
                            'type' => 'DC',
                            'quantity_type' => 'audit',
                            'created' => $auditto,
                            'modified' => $createdTime
                        ]);
                    }
                }
                
                // Save audit_stock header
                if ($this->Audit_stock->save($header)) {
                    $this->Flash->success(__('Audit submitted successfully.'));
                    return $this->redirect(['action' => 'semi_auditstock']);
                } else {
                    $this->Flash->error(__('Failed to submit audit.'));
                }
            }
        }
    }
    
    public function semi_view_audit()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		$id=$_REQUEST['id'];
    
        $indents = $this->Audit_stock->query("SELECT * FROM pos_auditstock where pos_audit_id=$id");
        $this->set(compact('indents'));
        
		$items = $this->Audit_stock_items->query("SELECT * FROM pos_auditstock_items where pos_audit_id=$id and status=1");
        
        $this->set(compact('items'));
        
        
	}
	
	public function kds_users() 
    {
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		$startDate = date('m/d/Y', strtotime('-12 months'));
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }   
        
        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;
                
        $params = [
            'start' => "$startdate 00:00:01",
            'end'   => "$enddate 23:59:59"
        ];
        
        $locationCondition = "";
        if ($userRole !== 'admin') {
            $locationCondition = " AND ku.location_id = :location_id";
            $params['location_id'] = $userLocationId; // assign normally, not using IN here
        }
        
        $sql = "
            SELECT ku.*,
                   GROUP_CONCAT(kusm.station_name) AS stations
            FROM kds_users ku
            LEFT JOIN kds_users_station_mapping kusm ON kusm.kds_id = ku.id
            WHERE 1=1
                  $locationCondition
                  AND ku.created BETWEEN :start AND :end
            GROUP BY ku.id
        ";
        
        $users = $this->Kds_user->query($sql, $params);


        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        
		$this->set(compact('users'));

	}
	
	public function create_kds_users()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
	    
	    $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;
        
        $conditions = ['status' => 1];
        if ($userRole !== 'admin') {
            $conditions['id IN'] = (array)$userLocationId; // works for single or multiple
        }
        
        $locations = $this->Location->find('all', [
            'conditions' => $conditions
        ]);
        $this->set(compact('locations'));
	    
	    $stations = $this->Pos_printer->find('all', array('conditions' => array('status' => 1)));
        $this->set(compact('stations'));
	    
	    
		if ($this->request->is(array('post', 'put'))) {
            
            $username = $this->data['User']['username'];
            $userdetail=$this->Kds_user->find('first',array('conditions'=>array('username'=>$username)));
	        if($userdetail){
	            $this->Flash->error(__('Username already exist'));
                return $this->redirect(array('action' => 'create_kds_users'));
	        }
            
            $password = $this->data['User']['password'];
            $password = AuthComponent::password($password);
            $location = $this->data['User']['location'];
            $role = $this->data['User']['role'];
            $locationdetail=$this->Location->find('first',array('conditions'=>array('Location.id'=>$location)));
	        $locationname=$locationdetail['Location']['name'];
            $data['Kds_user']=array(
    			'username'=>$username,
    			'password'=>$password,
    			'role'=>$role,
    			'location_id'=>$location,
    			'location_name'=>$locationname
    	    );
    	    
    	    if($this->Kds_user->save($data['Kds_user']))
    		{
    		    $kds_id = $this->Kds_user->id;
                
                foreach ($_POST['station_ids'] as $station_id) {
                    $stationdetail = $this->Pos_printer->find('first', [
                        'conditions' => ['Pos_printer.id' => $station_id],
                        'recursive' => -1
                    ]);
                
                    if (!$stationdetail) {
                        continue;
                    }
                
                    $data['Kds_users_station_mapping'] = [
                        'kds_id' => $kds_id,
                        'kds_username' => $username,
                        'station_id' => $station_id,
                        'station_name' => $stationdetail['Pos_printer']['name'],
                        'station_store_id' => $stationdetail['Pos_printer']['store_id'],
                        'station_store_name' => $stationdetail['Pos_printer']['store_name']
                    ];
                
                    if (!$this->Kds_users_station_mapping->saveAll($data['Kds_users_station_mapping'])) {
                        $this->Flash->error(__('KDS User Station Mapping could not be saved. Please, try again.'));
                    }
                }

    		    $this->Flash->success(__('Kds User has been saved.'));
				return $this->redirect(array('action' => 'kds_users'));
			} else {
				$this->Flash->error(__('kds User could not be saved. Please, try again.'));
			}
		}
	}
	
	public function kds_users_change_status() 
	{
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $Id = $this->request->data['_id'];
            
            $this->Kds_user->id = $Id;
            $newStatus = $this->Kds_user->field('status') == 1 ? 0 : 1;
            
            if ($this->Kds_user->save(['status' => $newStatus,'sync' => 0])) {
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }
    
    public function get_stations_by_location()
    {
        $this->autoRender = false;
        $locationId = $this->request->query('location_id');
    
        if (!$locationId) {
            echo json_encode(['status' => false, 'message' => 'Location ID missing']);
            return;
        }
    
        $stations = $this->Pos_printer->find('all', [
            'conditions' => [
                'Pos_printer.store_id' => $locationId,
                'Pos_printer.status' => 1
            ],
            'fields' => ['id', 'name']
        ]);
    
        $data = [];
        foreach ($stations as $station) {
            $data[] = [
                'id' => $station['Pos_printer']['id'],
                'name' => $station['Pos_printer']['name']
            ];
        }
    
        echo json_encode(['status' => true, 'stations' => $data]);
    }
    
    public function edit_kds_users()
    {
        if (!$this->Session->check('Auth.User.id')) {
            return $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = 'users';
        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;
        
           
        if (!empty($this->data['Catalog_product_branches']['id'])) {
            $id = $this->data['Catalog_product_branches']['id'];
            $username = trim($this->data['Catalog_product_branches']['username']);
            $password = trim($this->data['Catalog_product_branches']['password']);
            $location = (int)$this->data['Catalog_product_branches']['location'];
            $role = $this->data['Catalog_product_branches']['role'];
            
            if ($username === '') {
                $this->Flash->error(__('Username cannot be blank'));
                return $this->redirect(['action' => 'edit_kds_users', '?' => ['id' => $id]]);
            }
    
            $locationDetail = $this->Location->find('first', [
                'conditions' => ['Location.id' => $location],
                'recursive' => -1
            ]);
    
            $storeName = $locationDetail['Location']['name'] ?? '';
    
            // Update KDS user info
            $updateData = [
                'username' => $username,
                'role' => $role,
                'store_id' => $location,
                'store_name' => $storeName,
                'sync' => 0
            ];
        
            $this->Kds_user->id = $id;
            $this->Kds_user->save($updateData);
            
            // Update password if provided
            if (!empty($password)) {
                $hashedPassword = AuthComponent::password($password);
                $this->Kds_user->saveField('password', $hashedPassword);
            }
            // Remove existing station mapping
            $this->Kds_users_station_mapping->deleteAll(['kds_id' => $id]);
    
            // Save new station mappings
            //  print_r($this->request['data']['station_ids']);exit;
    
            if (!empty($this->request['data']['station_ids'])) {
                foreach ($this->request['data']['station_ids'] as $stationId) {
                    $stationDetail = $this->Pos_printer->find('first', [
                        'conditions' => ['id' => $stationId],
                        'recursive' => -1
                    ]);
    
                    if (!empty($stationDetail)) {
                        $mapData = [
                            'kds_id' => $id,
                            'kds_username' => $username,
                            'station_id' => $stationId,
                            'station_name' => $stationDetail['Pos_printer']['name'],
                            'station_store_id' => $stationDetail['Pos_printer']['store_id'],
                            'station_store_name' => $stationDetail['Pos_printer']['store_name']
                        ];
                        $this->Kds_users_station_mapping->create();
                        if (!$this->Kds_users_station_mapping->saveAll($mapData)) {
                            $this->Flash->error(__('Station mapping failed to save.'));
                        }
                    }
                }
            }
    
            $this->Flash->success(__('KDS User has been updated successfully.'));
            return $this->redirect(['action' => 'kds_users']);
        } else {
            $id = $_REQUEST['id'] ?? null;
            if (!$id) {
                $this->Flash->error(__('Invalid user ID.'));
                return $this->redirect(['action' => 'kds_users']);
            }
    
            $userDetail = $this->Kds_user->find('first', [
                'conditions' => ['id' => $id],
                'recursive' => -1
            ]);
            $this->set(compact('userDetail'));
            
            $locationCondition = ['status' => 1]; // always filter by active locations
        
            if ($userRole !== 'admin') {
                // If $userLocationId is a single ID, make it an array
                $userLocationIds = is_array($userLocationId) ? $userLocationId : [$userLocationId];
                $locationCondition['id'] = $userLocationIds; // CakePHP automatically handles IN
            }
            
            $locations=$this->Location->find('all',array('conditions'=>$locationCondition));
            $this->set(compact('locations'));
    
            $stationMappings = $this->Kds_users_station_mapping->find('list', [
                'fields' => ['station_id'],
                'conditions' => ['kds_id' => $id],
                'recursive' => -1
            ]);
            $this->set('selectedStations', array_values($stationMappings));
    
            $stations = $this->Pos_printer->find('all', [
                'conditions' => ['status' => 1],
                'recursive' => -1
            ]);
            $this->set(compact('stations'));
        }
    }
    
    public function unit_mapping() 
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		$startDate = date('m/d/Y', strtotime('-12 months'));
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
        }else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }   
        
		
		$users = $this->Catalog_unit_mapping->query("SELECT * FROM catalog_unit_mapping where created between '$startdate 00:00:01' and  '$enddate 23:59:59' ORDER BY id desc");
        $yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        
		$this->set(compact('users'));

	}
	
	public function create_unit_mapping()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
	
		$units = $this->Catalog_unit->find('all', ['conditions' => ['status' => 1]]);
        $this->set(compact('units'));
    
		
		if ($this->request->is(array('post', 'put'))) {
            
            $unit = $this->data['User']['unit'];
            if($unit==''){
                $this->Flash->error(__('The Unit could not be Blank'));
                return $this->redirect(array('action' => 'create_unit_mapping'));
            }
            $unit_id = (int)$unit;
            $unitData = $this->Catalog_unit->findById($unit_id);
            $unit_name = $unitData['Catalog_unit']['name'] ?? '';
            
            $con_unit = $this->data['User']['con_unit'];
            if($con_unit==''){
                $this->Flash->error(__('The Unit could not be Blank'));
                return $this->redirect(array('action' => 'create_unit_mapping'));
            }
            $con_unit_id = (int)$con_unit;
            $con_unitData = $this->Catalog_unit->findById($con_unit_id);
            $con_unit_name = $con_unitData['Catalog_unit']['name'] ?? '';
            
            $factor = $this->data['User']['factor'];
            
            $data['Catalog_unit_mapping']=array(
    			'unit_id'=>$unit,
    			'unit_name'=>$unit_name,
    			'mapped_unit_id'=>$con_unit,
    			'mapped_unit_name'=>$con_unit_name,
    			'conversion_factor'=>$factor
    	    );
    	    
    	    if($this->Catalog_unit_mapping->saveAll($data['Catalog_unit_mapping']))
    		{
    		    $this->Flash->success(__('Unit has been mapped.'));
				return $this->redirect(array('action' => 'unit_mapping'));
			} else {
				$this->Flash->error(__('Unit could not be mapped. Please, try again.'));
			}
		}
	}
	
	public function edit_unit_mapping() {
        if (!$this->Session->check('Auth.User.id')) {
            $this->redirect(['controller' => 'dashboard', 'action' => 'login']);
        }
    
        $this->layout = "users";
    
        $id = $this->request->query('id'); // safer than $_REQUEST
    
        // Load units for dropdowns
        $units = $this->Catalog_unit->find('all', ['conditions' => ['status' => 1]]);
        $this->set(compact('units'));
    
        // Load existing mapping record
        $mapping = $this->Catalog_unit_mapping->findById($id);
        if (!$mapping) {
            $this->Flash->error('Mapping not found');
            return $this->redirect(['action' => 'unit_mapping']);
        }
        $this->set('products', [$mapping]);  // your view uses $products[0]
    
        if ($this->request->is(['post', 'put'])) {
            // Update mapping record
            $unit_id = $this->data['User']['unit'];
            $unitData = $this->Catalog_unit->findById($unit_id);
            $unit_name = $unitData['Catalog_unit']['name'] ?? '';
            
            $con_unit_id = $this->data['User']['con_unit'];
            $con_unitData = $this->Catalog_unit->findById($con_unit_id);
            $con_unit_name = $con_unitData['Catalog_unit']['name'] ?? '';
            
            $this->Catalog_unit_mapping->id = $id;
            $data = [
                'unit_id' => $this->request->data['User']['unit'],
                'unit_name' => $unit_name,
                'mapped_unit_id' => $this->request->data['User']['con_unit'],
                'mapped_unit_name' => $con_unit_name,
                'conversion_factor' => $this->request->data['User']['factor'],
            ];
            
            if ($this->Catalog_unit_mapping->save($data)) {
                $this->Flash->success('Unit mapping has been updated.');
                return $this->redirect(['action' => 'unit_mapping']);
            } else {
                $this->Flash->error('Unable to update unit mapping.');
            }
        } else {
            // Populate form with existing data
            $this->request->data['User'] = [
                'unit' => $mapping['Catalog_unit_mapping']['unit_id'],
                'con_unit' => $mapping['Catalog_unit_mapping']['mapped_unit_id'],
                'factor' => $mapping['Catalog_unit_mapping']['factor'],
            ];
        }
    }

	
	public function unit_mapping_change_status() {
        $this->autoRender = false; // Disable view rendering
    
        if ($this->request->is('post')) {
            $Id = $this->request->data['_id'];
            
            $this->Catalog_unit_mapping->id = $Id;
            $newStatus = $this->Catalog_unit_mapping->field('status') == 1 ? 0 : 1;
            
            if ($this->Catalog_unit_mapping->save(['status' => $newStatus,'sync' => 0])) {
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }

    public function get_mapped_units() {
        $this->autoRender = false;  // no view
    
        $unit_id = $this->request->query('unit_id');
    
        if (!$unit_id) {
            echo json_encode([]);
            return;
        }
    
        // Fetch mapped units for the selected unit_id
        $mappedUnits = $this->Catalog_unit_mapping->find('all', [
            'conditions' => ['unit_id' => $unit_id, 'status' => 1],
            'fields' => ['mapped_unit_id', 'mapped_unit_name'],
            'recursive' => -1,
        ]);
    
        // Format for JSON
        $result = [];
        foreach ($mappedUnits as $mu) {
            $result[] = [
                'mapped_unit_id' => $mu['Catalog_unit_mapping']['mapped_unit_id'],
                'mapped_unit_name' => $mu['Catalog_unit_mapping']['mapped_unit_name'],
            ];
        }
    
        echo json_encode($result);
    }
    
    public function get_conversion_factor() {
        $this->autoRender = false;
    
        $unit_id = $this->request->query('unit_id');
        $mapped_unit_id = $this->request->query('mapped_unit_id');
    
        if (!$unit_id || !$mapped_unit_id) {
            echo json_encode([]);
            return;
        }
    
        $mapping = $this->Catalog_unit_mapping->find('first', [
            'conditions' => [
                'unit_id' => $unit_id,
                'mapped_unit_id' => $mapped_unit_id,
                'status' => 1
            ],
            'fields' => ['conversion_factor'],
            'recursive' => -1,
        ]);
    
        if ($mapping) {
            echo json_encode(['factor' => $mapping['Catalog_unit_mapping']['conversion_factor']]);
        } else {
            echo json_encode(['factor' => null]);
        }
    }
    
    public function kds_reports()
	{
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
        
	    $this->layout = "users";
		
		$startDate = date('m/d/Y', strtotime('-12 months'));
        $endDate = date('m/d/Y');
        
        if($this->request->is('post', 'put'))
        {
			$daterange= $this->request->data['daterange'];
            $dates = explode(" - ", $daterange);
            $start_date = trim($dates[0]);
            $startDate = date('m/d/Y', strtotime($start_date));
            $end_date = trim($dates[1]);
            $endDate = date('m/d/Y', strtotime($end_date));
            $startdate= date('Y-m-d', strtotime($start_date));
            $enddate= date('Y-m-d', strtotime($end_date));
		}else{
            $startdate= date('Y-m-d', strtotime($startDate));
            $enddate= date('Y-m-d', strtotime($endDate));
        }   
        
        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        
        if ($userRole !== 'admin') {
        
            $cashier_id= $this->request->data['Search']['cashier'];
            if(!$cashier_id){
            	$cashier_id = $authUser['location_ids'] ?? 0;
            }
            $users = $this->Kds_track->query("SELECT k.*, (SELECT name FROM pos_printers WHERE id = k.kds_station_id) AS station_name 
                FROM kds_tracks k
                 WHERE created BETWEEN '$startdate 00:00:01' AND '$enddate 23:59:59' and location_id=$cashier_id
                ORDER BY k.id DESC;
            ");
        }else{
            $users = $this->Kds_track->query("SELECT k.*, (SELECT name FROM pos_printers WHERE id = k.kds_station_id) AS station_name 
                FROM kds_tracks k
                 WHERE created BETWEEN '$startdate 00:00:01' AND '$enddate 23:59:59'
                ORDER BY k.id DESC;
            "); 
        }
    
		$yourStartDateValue=$startDate . ' - ' . $endDate;
        $this->set('startdate', $yourStartDateValue);
        
		$this->set(compact('users'));
		
		$userLocationId = $authUser['location_ids'] ?? 0;
        
        $locationCondition = ['status' => 1]; // always filter by active locations

        if ($userRole !== 'admin') {
            // Ensure it's always an array
            $userLocationIds = is_array($userLocationId) ? $userLocationId : [$userLocationId];
            $locationCondition['id'] = $userLocationIds; // CakePHP will auto-convert to IN()
        }
        
        $cashier_users = $this->Location->find('all', [
            'conditions' => $locationCondition
        ]);

	    $this->set(compact('cashier_users'));
	   // print_r($locationCondition);exit;

	}
	
	public function kds_reportexport() {
	    $date_range= $_GET['sdate'];
	    $dates = explode(" - ", $date_range);
        $start_date = trim($dates[0]);
        $end_date = trim($dates[1]);
        $startdate= date('Y-m-d', strtotime($start_date));
        $enddate= date('Y-m-d', strtotime($end_date));

        $cashier_id = isset($_GET['cashier']) ? $_GET['cashier'] : '';
    
        // Get transactions
        $conditions = array();
        $conditions[] = "created BETWEEN '$startdate 00:00:01' AND '$enddate 23:59:59'";
        if ($cashier_id) {
            $conditions[] = "cashier_id=" . (int)$cashier_id;
            $cashiernames = $this->User->find('first', array('conditions' => array('User.id' => $cashier_id)));
            $cashiername  = !empty($cashiernames['User']['name']) ? $cashiernames['User']['name'] : 'Unknown Cashier';
        } else {
            $cashiername = 'All Cashiers';
        }
        $where = implode(' AND ', $conditions);
    
        $transactions = $this->Kds_track->query("
            SELECT k.*, (SELECT name FROM pos_printers WHERE id = k.kds_station_id) AS station_name 
            FROM kds_tracks k
            WHERE $where
            ORDER BY k.id DESC
        ");
    
        // Prepare data for Excel
        $datas = array();
        foreach ($transactions as $user) {
            $statusLabel = '';
            switch ($user['k']['status']) {
                case 0: $statusLabel = 'Unfire'; break;
                case 1: $statusLabel = 'Fire'; break;
                case 2: $statusLabel = 'Hold'; break;
                case 3: $statusLabel = 'Start'; break;
                case 4: $statusLabel = 'Bump'; break;
                case 5: $statusLabel = 'Flag'; break;
                case 6: $statusLabel = 'Send to Table'; break;
                case 7: $statusLabel = 'Recall'; break;
                default: $statusLabel = 'Unknown'; break;
            }
            $datas[] = array(
                'Reference ID'   => $user['k']['order_reference_id'],
                'Group ID'       => $user['k']['kds_group_id'],
                'KDS Station'    => !empty($user[0]['station_name']) ? $user[0]['station_name'] : '',
                'Product Name'   => $user['k']['product_name'],
                'Role'           => $user['k']['role'],
                'Location Name'  => $user['k']['location_name'],
                'Status'         => $statusLabel,
                'Created'        => $user['k']['created'],
            );
        }
    
        // Load PHPExcel
        App::import('Vendor', 'PHPExcel', array('file' => 'PHPExcel/PHPExcel.php'));
        App::import('Vendor', 'PHPExcel_IOFactory', array('file' => 'PHPExcel/PHPExcel/IOFactory.php'));
        error_reporting(0);
    
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()->setCreator("Aether")
            ->setLastModifiedBy("Aether")
            ->setTitle("KDS Transaction Report")
            ->setSubject("Transaction Report")
            ->setDescription("Exported KDS transaction data.")
            ->setCategory("Export Data");
    
        // Set headers
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', "TRANSACTION REPORT FROM $startdate TO $enddate ($cashiername)");
        $objPHPExcel->getActiveSheet()->mergeCells('A1:H1');
        $objPHPExcel->getActiveSheet()->getStyle("A1:H1")->getFont()->setBold(true);
    
        // Column headings for Excel
        $headers = array('SR. NO.', 'Reference ID', 'Group ID', 'KDS Station', 'Product Name', 'Role', 'Location Name', 'Status', 'Created');
        foreach ($headers as $col => $heading) {
            $colLetter = PHPExcel_Cell::stringFromColumnIndex($col);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colLetter . '2', $heading);
            $objPHPExcel->getActiveSheet()->getStyle($colLetter . '2')->getFont()->setBold(true);
        }
    
        // Data rows
        $rowNum = 3;
        foreach ($datas as $idx => $dat) {
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A' . $rowNum, ($idx + 1));
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B' . $rowNum, $dat['Reference ID']);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C' . $rowNum, $dat['Group ID']);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('D' . $rowNum, $dat['KDS Station']);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E' . $rowNum, $dat['Product Name']);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('F' . $rowNum, $dat['Role']);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('G' . $rowNum, $dat['Location Name']);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('H' . $rowNum, $dat['Status']);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('I' . $rowNum, $dat['Created']);
            $rowNum++;
        }
    
        $objPHPExcel->getActiveSheet()->setTitle('Export Data');
        $objPHPExcel->setActiveSheetIndex(0);
    
        // Output to browser
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="kds_REPORT.xls"');
        header('Cache-Control: max-age=0');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Past date
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
        header('Cache-Control: cache, must-revalidate');
        header('Pragma: public');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

	
	
	public function view_kds_report()
    {
        // Session check (as before)
        if(!$this->Session->check('Auth.User.id')){
            $this->redirect(array('controller'=>'dashboard','action' => 'login'));     
        }
        $this->layout = "users";
        
        $id = $_REQUEST['id'];
    
        // Fetch with station name in result
        $flatProducts = $this->Kds_track->query(
            "SELECT *, (SELECT name FROM pos_printers WHERE id = kds_tracks.kds_station_id) AS station_name 
            FROM kds_tracks 
            WHERE order_reference_id = '$id'"
        );
        // Group by station_name and product_name
        $stations = [];
        foreach ($flatProducts as $row) {
            // Get station name
            $stationName = isset($row[0]['station_name']) ? $row[0]['station_name'] : $row['kds_tracks']['station_name'];
            // Get product data structure (may need to adjust based on your query result)
            $data = isset($row['kds_tracks']) ? $row['kds_tracks'] : (isset($row[0]) ? $row[0] : $row);
            // Get product name
            $productName = $data['product_name'];
            // Group by [station][product][]
            $stations[$stationName][$productName][] = $row;
        }
    
        $this->set(compact('stations'));
    }

    
    //bracnhes code
    //branches
    public function store_category() {
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
		$this->layout = "users";
		
		$authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;

        if($userRole == 'subadmin'){
            $id = $authUser['id'];                      
            $userLocationId = $this->User_location->find('list', [
                'conditions' => ['status' => 1, 'user_id' => $id],
                'fields' => ['location_id']
            ]);
        }
        
	    $conditions = [
            'status' => 1,
            'type'   => 'Outlet'
        ];
        
        if ($userRole !== 'admin') {
            // Always cast to array so CakePHP handles IN() automatically
            $userLocationIds = is_array($userLocationId) ? $userLocationId : [$userLocationId];
            $conditions['id IN'] = $userLocationIds;
        }
        $cashier_users = $this->Location->find('all', [
            'conditions' => $conditions
        ]);
	    $this->set(compact('cashier_users'));
	 
        $location_id = null;
        if (isset($this->request->data['Search'])) {
	        $location_id= $this->request->data['Search']['cashier'];
        }
        if (isset($this->request->query['location_id'])) {
            $location_id = $this->request->query['location_id'];
            $this->request->data['Search']['cashier'] = $location_id;
        }

        

        $users = $this->Catalog_category_branches->find('all', array(
            'conditions' => array('location_id' =>$location_id, 'status' => 1),
            'order' => array(
                'id' => 'DESC' 
            )
        ));
        
        // $dbo = $this->Catalog_category_branches->getDataSource();
        // $logs = $dbo->getLog();
        // $lastQuery = end($logs['log']);
        // debug($lastQuery);die;
        
        $this->set(compact('users'));

	}
    
    //Manage store categories
    public function manage_store_category() {
	    if(!$this->Session->check('Auth.User.id')){
			$this->redirect(array('controller'=>'dashboard','action' => 'login'));		
		}
		
		$authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_id'] ?? 0;
        
	    $this->layout = "users";
		
		$locationCondition = '';
        if ($userRole !== 'admin' || $userRole !== 'subadmin') {
            $locationCondition = "id = " . (int)$userLocationId;
        }

        $locationId = isset($this->request->query['loc_id']) ? $this->request->query['loc_id'] : null;
        $existingCategories = array();
        
        if ($locationId) {

            $locationname = $this->Location->field('name', array('id' => $locationId));
            
            $this->set(compact('locationname'));
            $this->set(compact('locationId'));

            $existingCategories = $this->Catalog_category_branches->find('list', array(
                'fields' => ['category_id', 'category_id'],
                'conditions' => array(
                    'location_id' => $locationId,
                    'status' => 1
                )
            ));
            if(!empty($existingCategories)){
                $allCategories = $this->Catalog_category->find('all', [
                    'fields' => ['id', 'name'],
                    'conditions' => ['status' => 1, 'NOT' => ['id' => $existingCategories]]
                ]);
            }
            else{
                $allCategories = $this->Catalog_category->find('all', [
                    'fields' => ['id', 'name'],
                    'conditions' => ['status' => 1]
                ]);
            }
            

            $this->set(compact('allCategories'));
        }
        

	}

    public function assign_categories_to_store(){
        $this->autoRender = false; 
    
        if ($this->request->is('post')) {
            $category_ids = $this->request->data['category_ids'];
            $store_id = $this->request->data['store_id'];
            $storename = $this->request->data['store_name'];

            $saveData = [];
            foreach ($category_ids as $catId) {
                $category_name = $this->Catalog_category->field('name', ['id' => $catId]);
                $saveData[] = [
                    'location_id' => $store_id,       
                    'category_id' => (int)$catId,   
                    'category_name' => $category_name,   
                    'location_name' => $storename
                ];
            }

            if ($this->Catalog_category_branches->saveAll($saveData)) {
                $this->Flash->success(__('Categories saved successfully.'));
                $this->autoRender = false;
                $this->response->type('json');
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }

    public function change_store_category_status() {
        $this->autoRender = false; 
    
        if ($this->request->is('post')) {
            $categoryId = $this->request->data['_id'];
            $location_id = $this->request->data['loc_row_id'];
              $category =  $this->Catalog_category_branches->updateAll(
                    ['status' => 0],          // fields to update
                    ['category_id' => $categoryId, 'location_id' => $location_id]  // condition
                );
                if ($category) {
                    echo json_encode(['status' => true]);
                } else {
                    echo json_encode(['status' => false]);
                }
           
        }
    }

    public function store_products() {
        $authUser = $this->Session->read('Auth.User');
        $userRole = $authUser['role'] ?? '';
        $userLocationId = $authUser['location_ids'] ?? 0;

        if($userRole == 'subadmin'){
            $id = $authUser['id'];                      
            $userLocationId = $this->User_location->find('list', [
                'conditions' => ['status' => 1, 'user_id' => $id],
                'fields' => ['location_id']
            ]);
        }
        
	    $this->layout = "users";
		$this->loadModel('Catalog_product_branches');

		$locationCondition = [
            'status' => 1,
            'type'   => 'Outlet'
        ]; // always filter by active outlets
        
        if ($userRole !== 'admin') {
            // Ensure it’s always an array
            $userLocationIds = is_array($userLocationId) ? $userLocationId : [$userLocationId];
            $locationCondition['id'] = $userLocationIds; // CakePHP will convert to IN()
        }
        
        $cashier_users = $this->Location->find('all', [
            'conditions' => $locationCondition
        ]);

	    $this->set(compact('cashier_users'));
        $location_id = null;
        if (isset($this->request->data['Search']['cashier'])) {
            $location_id = $this->request->data['Search']['cashier'];
        }
        if (isset($this->request->query['location_id'])) {
            $location_id = $this->request->query['location_id'];
            $this->request->data['Search']['cashier'] = $location_id;
        }

        $assignedCategories = [];
        
        $assignedCategories = $this->Catalog_product_branches->find('all', [
            'conditions' => ['location_id' => $location_id, 'status' => 1],
            'order' => ['id' => 'DESC']
        ]);
        $this->set(compact('assignedCategories'));
    }

    public function manage_store_products() {
        if(!$this->Session->check('Auth.User.id')){
            $this->redirect(array('controller'=>'dashboard','action' => 'login'));
        }

        $authUser = $this->Session->read('Auth.User');
        $this->layout = "users";
        
		$this->loadModel('Catalog_product_branches');

        $locationId = isset($this->request->query['loc_id']) ? $this->request->query['loc_id'] : null;
        if ($locationId) {
            $locationname = $this->Location->field('name', array('id' => $locationId));
            $this->set(compact('locationId'));
            $this->set(compact('locationname'));
        }

        $existingProducts = $this->Catalog_product_branches->find('list', array(
                'fields' => ['product_id', 'product_id'],
                'conditions' => array(
                    'location_id' => $locationId,
                    'status' => 1
                )
            ));
        
        if(!empty($existingProducts)){
            $products = $this->Catalog_product->find('all', [
                'fields' => ['id', 'name', 'cat_id', 'cat_name', 'subcat_id', 'subcat_name','unit', 'unit_name','price'],
                'conditions' => ['status' => 1, 'NOT' => ['id' => $existingProducts]]
            ]);
        } else {
            $products = $this->Catalog_product->find('all', [
                'fields' => ['id', 'name', 'cat_id', 'cat_name', 'subcat_id', 'subcat_name','unit', 'unit_name','price'],
                'conditions' => ['status' => 1]
            ]);
        }
       
        $this->set(compact('products'));


    }

    public function assign_products_to_store(){
        $this->autoRender = false; 
        
        if ($this->request->is('post')) {

            
		$this->loadModel('Catalog_product_branches');

            $product_ids = $this->request->data['product_ids'];
            $store_id = $this->request->data['store_id'];
            $storename = $this->request->data['store_name'];
            $prices = $this->request->data['prices'];

            $saveData = [];
            foreach ($product_ids as $prodId) {
                
                $products = $this->Catalog_product->find('all', [
                    'fields' => ['id', 'name', 'cat_id', 'cat_name', 'subcat_id', 'subcat_name','unit', 'unit_name','price'],
                    'conditions' => ['status' => 1, 'id' => $prodId]
                ]);
                if (!empty($products)) {

                    $product = $products[0]['Catalog_product'];
                    $price = isset($prices[$prodId]) ? floatval($prices[$prodId]) : $product['price'];

                    $saveData[] = [
                        'location_id' => $store_id,       
                        'location_name' => $storename,
                        'product_id' => (int)$prodId,   
                        'product_name' => $product['name'],   
                        'cat_id' => $product['cat_id'],
                        'cat_name' => $product['cat_name'],
                        'subcat_id' => $product['subcat_id'],
                        'subcat_name' => $product['subcat_name'],
                        'unit' => $product['unit'],
                        'unit_name' => $product['unit_name'],
                        'price' => $price
                    ];
                }
            }

            if ($this->Catalog_product_branches->saveAll($saveData)) {
                $this->Flash->success(__('Products assigned successfully.'));
                $this->autoRender = false;
                $this->response->type('json');
                echo json_encode(['status' => true]);
            } else {
                echo json_encode(['status' => false]);
            }
        }
    }
    
    public function change_store_product_status() {
        $this->autoRender = false; 
        
		$this->loadModel('Catalog_product_branches');
        if ($this->request->is('post')) {
            $product_id = $this->request->data['product_id'];
            $location_id = $this->request->data['loc_row_id'];
              $category =  $this->Catalog_product_branches->updateAll(
                    ['status' => 0],          // fields to update
                    ['product_id' => $product_id, 'location_id' => $location_id]  // condition
                );
                if ($category) {
                    echo json_encode(['status' => true]);
                } else {
                    echo json_encode(['status' => false]);
                }
           
        }
    }

    public function copy_store_categories() {
        $this->autoRender = false; 
        
        if ($this->request->is('post')) {
             $current_store_id = $this->request->data['store_id'];
             $copy_from_store = $this->request->data['copy_from_store'];

            $existingCategories = $this->Catalog_category_branches->find('list', array(
                'fields' => ['category_id', 'category_id'],
                'conditions' => array(
                    'location_id' => $current_store_id,
                    'status' => 1
                )
            ));
            if(!empty($existingCategories)){
                $data = $this->Catalog_category_branches->find('all', array(
                    'conditions' => array('location_id' =>$copy_from_store, 'status' => 1, 'NOT' => ['category_id' => $existingCategories]),
                    'order' => array(
                        'id' => 'DESC')
                ));
                
            }   
            else{
                $data = $this->Catalog_category_branches->find('all', array(
                    'conditions' => array('location_id' =>$copy_from_store, 'status' => 1),
                    'order' => array(
                        'id' => 'DESC')
                ));
            }
            
            $locationname = $this->Location->field('name', array('id' => $current_store_id));

            $saveData = [];
            foreach ($data as $item) {
                $saveData[] = [
                    'location_id' => $current_store_id,       
                    'category_id' => $item['Catalog_category_branches']['category_id'],   
                    'category_name' => $item['Catalog_category_branches']['category_name'],   
                    'location_name' => $locationname
                ];  
            }
            if (!empty($saveData)) {

                if ($this->Catalog_category_branches->saveAll($saveData)) {
                    $this->Flash->success(__('Categories copied successfully.'));
                    $this->redirect(array('action' => 'store_category','?'=>array('location_id'=>$current_store_id)));
                    $this->autoRender = false;
                } else {
                    $this->Flash->error(__('Categories could not be copied. Please, try again.'));
                    $this->redirect(array('action' => 'store_category','?'=>array('location_id'=>$current_store_id)));
                }
                        
            } else {
                $this->Flash->success(__('No categories to copy from the selected store.'));
                $this->redirect(array('action' => 'store_category','?'=>array('location_id'=>$current_store_id)));
            }
        }
    }

    public function copy_store_products() {
        $this->autoRender = false;
		$this->loadModel('Catalog_product_branches');

        if ($this->request->is('post')) {
             $current_store_id = $this->request->data['store_id'];
             $copy_from_store = $this->request->data['copy_from_store'];

            $existingProducts = $this->Catalog_product_branches->find('list', array(
                'fields' => ['product_id', 'product_id'],
                'conditions' => array(
                    'location_id' => $current_store_id,
                    'status' => 1
                )
            ));
                
            if(!empty($existingProducts)){
                $data = $this->Catalog_product_branches->find('all', array(
                    'conditions' => array('location_id' =>$copy_from_store, 'status' => 1, 'NOT' => ['product_id' => $existingProducts]),
                    'order' => array(
                        'id' => 'DESC' 
                    )
                ));
                
            }else{
                $data = $this->Catalog_product_branches->find('all', array(
                    'conditions' => array('location_id' =>$copy_from_store, 'status' => 1),
                    'order' => array(
                        'id' => 'DESC' 
                    )
                ));
            }
            
        
            $locationname = $this->Location->field('name', array('id' => $current_store_id));
            $saveData = [];
            foreach ($data as $item) {
                $saveData[] = [
                    'location_id' => $current_store_id,       
                    'location_name' => $locationname,
                    'product_id' => $item['Catalog_product_branches']['product_id'],   
                    'product_name' => $item['Catalog_product_branches']['product_name'],   
                    'cat_id' => $item['Catalog_product_branches']['cat_id'],   
                    'cat_name' => $item['Catalog_product_branches']['cat_name'],   
                    'subcat_id' => $item['Catalog_product_branches']['subcat_id'],   
                    'subcat_name' => $item['Catalog_product_branches']['subcat_name'],   
                    'price' => $item['Catalog_product_branches']['price'],   
                    'unit' => $item['Catalog_product_branches']['unit'],   
                    'unit_name' => $item['Catalog_product_branches']['unit_name']
                ];  
            }
            if (!empty($saveData)) {

                if ($this->Catalog_product_branches->saveAll($saveData)) {
                    $this->Flash->success(__('Products copied successfully.'));
                    $this->redirect(array('action' => 'store_products','?'=>array('location_id'=>$current_store_id)));
                    $this->autoRender = false;
                } else {
                    $this->Flash->error(__('Products could not be copied. Please, try again.'));
                    $this->redirect(array('action' => 'store_products','?'=>array('location_id'=>$current_store_id)));
                }
                        
            } else {
                $this->Flash->success(__('No Products to copy from the selected store.'));
                $this->redirect(array('action' => 'store_products','?'=>array('location_id'=>$current_store_id)));
            }
        }
    }
    

    
    public function map_location_list()
    {
        if (!$this->Session->check('Auth.User.id')) {
            $this->redirect(array('controller' => 'dashboard', 'action' => 'login'));
        }
        $this->layout = "users";
        $this->loadModel('LocationMapping');

        $mappings = $this->LocationMapping->query("
            SELECT LocationMapping.*, Store.name as store_name 
            FROM location_mapping as LocationMapping 
            LEFT JOIN locations as Store ON LocationMapping.store_id = Store.id 
            WHERE LocationMapping.status = 1
            ORDER BY LocationMapping.id DESC
        ");

        $this->set(compact('mappings'));
    }

    public function create_map_location()
    {
        if (!$this->Session->check('Auth.User.id')) {
            $this->redirect(array('controller' => 'dashboard', 'action' => 'login'));
        }
        $this->layout = "users";
        $this->loadModel('Location');
        $this->loadModel('LocationMapping');

        $stores = $this->Location->find('list', array(
            'conditions' => array('type' => 'Outlet', 'status' => 1),
            'fields' => array('id', 'name')
        ));
        $this->set(compact('stores'));

        if ($this->request->is(array('post', 'put'))) {
            $location_name = $this->data['LocationMapping']['group_name'];
            $store_ids = $this->data['LocationMapping']['store_id'];
            $is_combine = $this->data['LocationMapping']['is_combine'];

            if (empty($location_name)) {
                $this->Flash->error(__('Group Name cannot be blank'));
                return $this->redirect(array('action' => 'create_map_location'));
            }
            if (empty($store_ids) || !is_array($store_ids)) {
                $this->Flash->error(__('Please select at least one store'));
                return $this->redirect(array('action' => 'create_map_location'));
            }

            $maxIdResult = $this->LocationMapping->query("SELECT MAX(location_id) as max_id FROM location_mapping");
            $nextLocationId = (isset($maxIdResult[0][0]['max_id'])) ? $maxIdResult[0][0]['max_id'] + 1 : 1;

            $success = true;

            foreach ($store_ids as $store_id) {
                $data = array(
                    'LocationMapping' => array(
                        'location_name' => $location_name,
                        'store_id' => $store_id,
                        'location_id' => $nextLocationId,
                        'is_combine' => $is_combine,
                        'status' => 1
                    )
                );
                $this->LocationMapping->create();
                if (!$this->LocationMapping->save($data)) {
                    $success = false;
                }
            }

            if ($success) {
                $this->Flash->success(__('Group Location saved successfully.'));
                return $this->redirect(array('action' => 'map_location_list'));
            } else {
                $this->Flash->error(__('Some Groups could not be saved.'));
            }
        }
    }

    public function edit_map_location()
    {
        if (!$this->Session->check('Auth.User.id')) {
            $this->redirect(array('controller' => 'dashboard', 'action' => 'login'));
        }
        $this->layout = "users";
        $this->loadModel('Location');
        $this->loadModel('LocationMapping');

        $location_id = $this->request->query('location_id');

        if ($this->request->is(array('post', 'put'))) {
            $location_id = $this->data['LocationMapping']['location_id'];
            $location_name = $this->data['LocationMapping']['group_name'];
            $store_ids = $this->data['LocationMapping']['store_id'];
            $is_combine = $this->data['LocationMapping']['is_combine'];

            if (empty($location_name)) {
                $this->Flash->error(__('Group Name cannot be blank'));
                return $this->redirect(array('action' => 'edit_map_location?location_id=' . $location_id));
            }
            if (empty($store_ids) || !is_array($store_ids)) {
                $this->Flash->error(__('Please select at least one store'));
                return $this->redirect(array('action' => 'edit_map_location?location_id=' . $location_id));
            }

            $this->LocationMapping->deleteAll(array('LocationMapping.location_id' => $location_id), false);

            $success = true;
            foreach ($store_ids as $store_id) {
                $data = array(
                    'LocationMapping' => array(
                        'location_name' => $location_name,
                        'store_id' => $store_id,
                        'location_id' => $location_id,
                        'is_combine' => $is_combine,
                        'status' => 1
                    )
                );
                $this->LocationMapping->create();
                if (!$this->LocationMapping->save($data)) {
                    $success = false;
                }
            }

            if ($success) {
                $this->Flash->success(__('Group Location updated successfully.'));
                return $this->redirect(array('action' => 'map_location_list'));
            } else {
                $this->Flash->error(__('Could not update Group Location.'));
            }
        }

        $stores = $this->Location->find('list', array(
            'conditions' => array('type' => 'Outlet', 'status' => 1),
            'fields' => array('id', 'name')
        ));
        $this->set(compact('stores'));

        $existing = $this->LocationMapping->find('all', array(
            'conditions' => array('LocationMapping.location_id' => $location_id, 'LocationMapping.status' => 1)
        ));

        if (!$existing) {
            $this->Flash->error(__('Invalid Location ID.'));
            return $this->redirect(array('action' => 'map_location_list'));
        }

        $selected_stores = array();
        foreach ($existing as $item) {
            $selected_stores[] = $item['LocationMapping']['store_id'];
        }
        $is_combine = $existing[0]['LocationMapping']['is_combine'];

        $this->request->data = array(
            'LocationMapping' => array(
                'location_id' => $location_id,
                'group_name' => $existing[0]['LocationMapping']['location_name'],
                'store_id' => $selected_stores,
                'is_combine' => $is_combine,
            )
        );
        $this->render('create_map_location');
    }
    public function delete_map_location()
    {
        $this->loadModel('LocationMapping');
        $locationId = $this->request->query('location_id');
        $storeId = $this->request->query('store_id');

        if (empty($locationId)) {
            $this->Flash->error(__('Invalid location ID.'));
            return $this->redirect(['action' => 'map_location_list']);
        }

        $this->LocationMapping->updateAll(
            ['LocationMapping.status' => 0],
            [
                'LocationMapping.location_id' => $locationId,
                'LocationMapping.store_id' => $storeId,
                'LocationMapping.status !=' => 0
            ]
        );

        $affected = $this->LocationMapping->getAffectedRows();

        if ($affected > 0) {
            $this->Flash->success(__('Group Location deleted.'));
        } else {
            $this->Flash->warning(__('No records were updated.'));
        }

        return $this->redirect(['action' => 'map_location_list']);
    }


}
