<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
App::uses('UtilityController', 'Controller');
App::uses('AppController', 'Controller');
App::uses('CakeTime', 'Utility');
/**
 * CakePHP ApisController
 * @author aetherss
 */
class CronController extends AppController {
    public function beforeFilter() {
            parent::beforeFilter();
            // Allow users to register and logout.
            $this->Auth->allow();
            $this->layout = false;
            $this->autoRender = false;
            error_reporting(0);
        }
        
    public function index()
    {
        echo "Welcome to PhyloPos";
    }
 
    public function close_open_table()
    {
        $this->autoRender = false;
        $this->layout = false;
        $this->loadModel('Order_table');
        $currentTime = date('Y-m-d H:i:s');

        try {
            $result = $this->Order_table->query("UPDATE order_tables SET status = '1', modified='$currentTime'  WHERE status = 2");
    
            $response = [
                'status' => true,
                'message' => 'done..!',
            ];
        } catch (Exception $e) {
            $response = [
                'status' => false,
                'message' => 'Failed: ' . $e->getMessage(),
            ];
        }
    
        echo json_encode($response);
        exit;
    }
   
    public function sync_to_pos()
    {
        // Get all unprocessed online orders
        $webhooks = $this->Online_order->find('all', [
            'conditions' => ['Online_order.cron_run' => 0],
            'limit' => 10,
            'order' => ['Online_order.id' => 'ASC']
        ]);
    
        foreach ($webhooks as $webhook) {
            $remarks = [];
            $data = [];
    
            $response = json_decode($webhook['Online_order']['response']);
            $txnid = $webhook['Online_order']['reference_id'];
    
            if (empty($response->order->items)) {
                $remarks[] = "Missing order items for txn $txnid";
                continue;
            }
            
            $trxchk=$this->Order_transaction->query("SELECT id FROM `order_transactions` WHERE reference_id='$txnid'");
            if(empty($trxchk)){
            
                $items = $response->order->items;
                $details = $response->order->details;
                $store = $response->store;
                $payments = $response->order->payment ?? [];
        
                $deliverydatetime = date("Y-m-d H:i:s", $details->delivery_datetime / 1000);
                $created = date("Y-m-d H:i:s", $details->created / 1000);
        
                // Initialize totals
                $total_tax_value = 0;
                $total_pack_charge = 0;
                $total_pack_taxes= 0;
                
                // Calculate packaging charges
                if (!empty($details->charges)) {
                    foreach ($details->charges as $char) {
                        $title = strtolower($char->title);
                        if ($title === 'packaging charge' || $title === 'restaurant packaging charges') {
                            $total_pack_charge += $char->value;
                            foreach ($char->taxes as $char_taxes) {
                                $total_pack_taxes += $char_taxes->value;
                            }
                        }
                    }
                }
                
                // Process each item
                $total_amount=0;
                foreach ($items as $item) {
                    $item_tax_value = 0;
                    $item_tax_rate = 0;
        
                    // Sum item taxes
                    if (!empty($item->taxes)) {
                        foreach ($item->taxes as $tax) {
                            $item_tax_value += $tax->value;
                            $item_tax_rate += $tax->rate;
                        }
                    }
                    $total_tax_value += $item_tax_value;
        
                    // Total price per item after discount
                    $ttlprice = ($item->price * $item->quantity) - ($item->discount ?? 0);
                    $total_amount += $ttlprice;
                    // Save order history
                    // $orderHistoryData = [
                    //     'reference_id'         => $txnid,
                    //     'cashier_id'           => 0,
                    //     'category'             => $item->category->id?$item->category->id:0,
                    //     'category_name'        => $item->category->name?$item->category->name:'',
                    //     'product_id'           => $item->merchant_id?$item->merchant_id:0,
                    //     'product_name'         => $item->title?$item->title:'',
                    //     'quantity'             => $item->quantity?$item->quantity:0,
                    //     'price'                => $item->price?$item->price:0,
                    //     'total_tax'            => $item_tax_value?$item_tax_value:0,
                    //     'total_tax_percentage' => $item_tax_rate?$item_tax_rate:0,
                    //     'total_price'          => $ttlprice?$ttlprice:0,
                    //     'discount'             => $item->discount ?? 0,
                    //     'status'               => 2
                    // ];
                    $orderHistoryData = [
                        'reference_id'         => $txnid,
                        'cashier_id'           => 2,
                        'category'             => $item->category->id?$item->category->id:0,
                        'category_name'        => $item->category->name?$item->category->name:'',
                        'product_id'           => $item->merchant_id?$item->merchant_id:0,
                        'product_name'         => $item->title?$item->title:'',
                        'quantity'             => $item->quantity?$item->quantity:0,
                        'price'                => $item->price?$item->price:0,
                        'total_tax'            => 0,
                        'total_tax_percentage' => 0,
                        'total_price'          => $ttlprice?$ttlprice:0,
                        'discount'             => $item->discount ?? 0,
                        'status'               => 2,
                        'created'              => $created
                    ];
                    
                    $this->Order_orderhistory->create();
                    $this->Order_orderhistory->save($orderHistoryData);
                    $lastorder_id = $this->Order_orderhistory->getLastInsertID();
    
                    $discount_percentage= ( $item->discount * 100 ) / $item->price ;
                    // Save taxes per item
                    
                    $ordertaxData = [
                        'orderhistory_id' => $lastorder_id, // Fill after saving order history if needed
                        'cashier_id'      => 2,
                        'product_id'      => $item->merchant_id ?? 0,
                        'product_name'    => $item->title ?? '',
                        'price'           => $item->price ?? 0,
                        'taxable_price'   => $ttlprice ?? 0,
                        'cat_id'          => $item->category->id ?? 0,
                        'cat_name'        => $item->category->name ?? '',
                        'discount_percentage' => round($discount_percentage,2),
                        'quantity'        => $item->quantity ?? 0,
                        'tax_id'          => 0,
                        'tax_name'        => 'Online',
                        'tax_percentage'  => 0,
                        'tax_value'       => 0,
                        'reference_id'    => $txnid ?? 0,
                        'status'          => 2,
                        'created'         => $created
                    ];
                    $this->Order_tax->create();
                    $this->Order_tax->save($ordertaxData);
                }
                    
                $currenttime = date("H:i:s", $details->delivery_datetime / 1000);
                
                $finalamount = round($total_amount);        
                $round_amount = round($total_amount,2)-round($total_amount);
                
                $todayDate = date("Y-m-d");
                $tdaytrx=$this->Order_transaction->query("SELECT COUNT(id) as tkn FROM `order_transactions` WHERE date(created)='$todayDate'");
                $token=$tdaytrx['0']['0']['tkn']+1;
                
                $deliveryother=0;
				$deliveryother=round((($details->total_charges)-$total_pack_charge),2);


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

    public function food_cost_product_update()
    {
        $this->autoRender = false;
        $this->layout = false;
        
        $currentTime = date('Y-m-d H:i:s');
        
        // $costprices = $this->Inventory_linking->query("WITH RECURSIVE bom AS (SELECT l.parent_id AS product_id, l.component_type, l.component_id, l.component_name, CAST(l.quantity AS DECIMAL(18,6)) AS qty FROM inventory_linking l WHERE l.parent_type = 'Product' UNION ALL SELECT bom.product_id, l.component_type, l.component_id, l.component_name, bom.qty * CAST(l.quantity AS DECIMAL(18,6)) AS qty FROM bom JOIN inventory_linking l ON l.parent_type = 'Semifinished' AND l.parent_id = bom.component_id ) SELECT bom.product_id, ROUND(SUM(bom.qty * COALESCE(s.price / NULLIF(p.yield, 0), 0)), 2) AS total_sku_cost FROM bom JOIN inventory_skus s ON bom.component_type = 'SKU' AND bom.component_id = s.id JOIN catalog_product p  ON bom.product_id = p.id GROUP BY bom.product_id ORDER BY bom.product_id");
        $costprices = $this->Inventory_linking->query("SELECT il.parent_id AS product_id, ROUND(SUM( CASE WHEN il.component_type = 'SKU' THEN il.quantity * COALESCE(s.price, 0) WHEN il.component_type = 'Semifinished' THEN il.quantity * COALESCE(sf.food_cost, 0) ELSE 0 END ), 2) AS total_component_cost FROM inventory_linking il LEFT JOIN inventory_skus s ON il.component_type = 'SKU' AND il.component_id = s.id LEFT JOIN inventory_semifinished sf ON il.component_type = 'Semifinished' AND il.component_id = sf.id WHERE il.parent_type = 'Product' GROUP BY il.parent_id ORDER BY il.parent_id; ");
        // print_r($costprices);exit;
        foreach($costprices as $costprice){
            $product_id= $costprice['il']['product_id'];
            $total_sku_cost= $costprice[0]['total_component_cost'];
            
            $this->Catalog_product->id = $product_id;
            
            if ($this->Catalog_product->exists()) {
                $saved  = $this->Catalog_product->save([
                    'id' => $product_id,
                    'food_cost' => $total_sku_cost,
                    'modified' => $currentTime
                ]);
                
                $response[] = [
                    'product_id' => $product_id,
                    'food_cost' => $total_sku_cost,
                    'status' => $saved ? 'updated' : 'failed'
                ];
            } else {
                
            }

            
        }
        
        echo json_encode([
            'status' => true,
            'message' => 'Food cost updated for products',
            'data' => $response
        ]);
        exit;
    }
    
    public function food_cost_semifinished_update()
    {
        
        $this->autoRender = false;
        $this->layout = false;
        
        $currentTime = date('Y-m-d H:i:s');
        
        // $costprices = $this->Inventory_linking->query("WITH RECURSIVE bom AS (SELECT l.parent_id AS semifinished_id, l.component_type, l.component_id, l.component_name, CAST(l.quantity AS DECIMAL(18,6)) AS qty FROM inventory_linking l WHERE l.parent_type = 'Semifinished' UNION  SELECT bom.semifinished_id, l.component_type, l.component_id, l.component_name, bom.qty * CAST(l.quantity AS DECIMAL(18,6)) AS qty FROM bom JOIN inventory_linking l ON l.parent_type = 'Semifinished' AND l.parent_id = bom.component_id ) SELECT bom.semifinished_id, ROUND(SUM(bom.qty * COALESCE(s.price / NULLIF(sf.yield, 0), 0)), 2) AS total_cost FROM bom JOIN inventory_skus s ON bom.component_type = 'SKU' AND bom.component_id = s.id JOIN inventory_semifinished sf ON bom.semifinished_id = sf.id GROUP BY bom.semifinished_id ORDER BY bom.semifinished_id");
        $costprices = $this->Inventory_linking->query("WITH RECURSIVE bom AS ( SELECT l.parent_id AS semifinished_id, l.component_type, l.component_id, l.component_name, CAST(l.quantity AS DECIMAL(18,6)) AS qty FROM inventory_linking l WHERE l.parent_type = 'Semifinished' UNION ALL SELECT bom.semifinished_id, l.component_type, l.component_id, l.component_name, bom.qty * CAST(l.quantity AS DECIMAL(18,6)) AS qty FROM bom JOIN inventory_linking l ON l.parent_type = 'Semifinished' AND l.parent_id = bom.component_id ) SELECT bom.semifinished_id, ROUND(SUM(bom.qty * COALESCE(s.price, 0)) / NULLIF(sf.yield, 0), 2) AS cost_per_unit FROM bom JOIN inventory_skus s ON bom.component_type = 'SKU' AND bom.component_id = s.id JOIN inventory_semifinished sf ON bom.semifinished_id = sf.id GROUP BY bom.semifinished_id, sf.yield; ");
        foreach($costprices as $costprice){
            $product_id= $costprice['bom']['semifinished_id'];
            $total_sku_cost= $costprice[0]['cost_per_unit'];
            
            $this->Inventory_semifinished->id = $product_id;
            // print_r($costprice);exit;
        
            if ($this->Inventory_semifinished->exists()) {
                
                $saved  = $this->Inventory_semifinished->saveAll([
                    'id' => $product_id,
                    'food_cost' => $total_sku_cost,
                    'modified' => $currentTime
                ]);
                
                $response[] = [
                    'semifinished_id' => $product_id,
                    'food_cost' => $total_sku_cost,
                    'status' => $saved ? 'updated' : 'failed'
                ];
            } else {
                
            }

            
        }
        
        echo json_encode([
            'status' => true,
            'message' => 'Food cost updated for semifinished',
            'data' => $response
        ]);
        exit;
    
    }
   
    public function fire_order()
    {
        $this->autoRender = false;
        $this->layout = false;
        $currentTime = date('Y-m-d H:i:s');

        $fire_items = $this->Order_orderhistory->find('all', [
            'conditions' => ['Order_orderhistory.kds_status' => 0,'Order_orderhistory.fire_at <= ' => $currentTime],
            'order' => ['Order_orderhistory.id' => 'ASC']
        ]);
        
        foreach ($fire_items as $fire_item) {
            
            $txnid = $fire_item['Order_orderhistory']['id'];
            $reference_id = $fire_item['Order_orderhistory']['reference_id'];
            $cashier_id = $fire_item['Order_orderhistory']['cashier_id'];
            
            $store_id='';
            $stores = $this->User->find('first', [
                'conditions' => [
                    'User.id' => $cashier_id,
                    'User.role' => 'cashier',
                    'User.status' => 1
                ],
                'recursive' => 1
            ]);
            $store_id=$stores['User']['location_id'];
            $store_name=$stores['User']['location_name'];
        
            $data['Kds_track'][] = [
                'order_history_id'   => $txnid,
                'order_reference_id' => $reference_id,
                'kds_group_id'       => $fire_item['Order_orderhistory']['group_id'],
                'kds_user_id'        => 0,
                'kds_station_id'     => $fire_item['Order_orderhistory']['kds'],
                'kds_username'       => 'auto-fire',
                'product_id'         => $fire_item['Order_orderhistory']['product_id'],
                'product_name'       => $fire_item['Order_orderhistory']['product_name'],
                'role'               => 'auto-fire',
                'table_no'           => $fire_item['Order_orderhistory']['table_number'],
                'cashier_id'         => $fire_item['Order_orderhistory']['cashier_id'],
                'location_id'        => $store_id,
                'location_name'      => $store_name,
                'status'             => 1
            ];
            
            
            $this->Kds_track->create();
            $this->Kds_track->saveAll($data['Kds_track']);
            $track_id = $this->Kds_track->id; // last inserted id
        
            $this->Order_orderhistory->updateAll(
                [
                    'Order_orderhistory.kds_status'   => 1,
                    'Order_orderhistory.kds_track_id'   => $track_id,
                ],
                ['Order_orderhistory.id' => $txnid]
            );
            $response='done';
        }
        echo json_encode($response);
        
    }
   
    
            
}