<?php

class Restaurantapi_model extends CI_Model {

    function __construct() {
        // Call the Model constructor
        parent::__construct(); 
    }

    public function getCategories($business_id) {
        $sql = "SELECT 
        business_products.category, 
        business_products.professional, 
        business_products.track_inventory ,
        ifnull( COUNT(*) , 0) AS product_count
    FROM `business_products` 
    WHERE business_products.business_product_active = 'Yes'"; 
            if($this->session->userdata('common_products') !='Yes'){ 
                $sql.="AND business_products.business_id = ?";
              } 
        $sql .=" AND professional = 'n'
        AND (
            (business_products.product_type = 'Compiled Kit' AND business_products.track_inventory = 'No') 
            OR 
            (business_products.product_type = 'Physical')
        )

    GROUP BY business_products.category";

        if($this->session->userdata('common_products')=='Yes'){ 
            $resp = $this->db->query($sql);
        }else{
            $resp = $this->db->query($sql, array($business_id));
        }
        $data = $resp->result();
        array_unshift($data,["category" => "All"]);
        return $data; 
    }
    public function getCategoryProduct($business_id,$category){   

        $sql = "SELECT 
                business_products.id_business_products,
                business_products.business_id,
                business_products.product,
                business_products.product_image as image,
                business_products.category,
                business_products.brand_id,
                business_products.sku,
                business_products.price,
                business_products.product_type,
                business_products.product_sales_tax, 
                business_products.track_inventory,
                business_products.professional,
                product_batch.id_batch,
                product_batch.batch_number,
                business_brands.business_brand_name,
                business_products.barcode_products 
            FROM `business_products`  
            left JOIN product_batch on  product_batch.product_id= business_products.id_business_products
            left join business_brands on business_brands.id_business_brands = business_products.business_id
            WHERE business_products.business_product_active = 'Yes'";  
              if($this->session->userdata('common_products') !='Yes'){ 
                $sql.="AND business_products.business_id = ?";
              }
                $sql.="
                AND professional = 'n'
                AND (
                    (business_products.product_type = 'Compiled Kit' AND business_products.track_inventory = 'No') 
                    OR 
                    (business_products.product_type = 'Physical')
                )";
        if($category != 'All'){
            $sql .= " and business_products.category = '".$category."'";
        }
        $sql .= " GROUP by business_products.id_business_products"; 
        if($this->session->userdata('common_products')=='Yes'){ 
            $resp = $this->db->query($sql);
        }else{
            $resp = $this->db->query($sql, array($business_id));
        }
        return $resp->result();
    }
    public function getCustomers($business_id){
        // $sql = "SELECT customers.id_customers,customers.business_id,customers.customer_name,customers.customer_cell 
        //         FROM `customers` 
        //         where business_id = ?";
        // $resp = $this->db->query($sql, array($business_id));
        $sql = "SELECT customers.id_customers,customers.business_id,customers.customer_name,customers.customer_cell 
                FROM `customers`";
        $resp = $this->db->query($sql);
        $data = $resp->result();
        return $data;
    }
    public function addCustomer(){
        $data = array(
            'business_id' => $this->input->post('businessid'),
            'customer_name' => $this->input->post('customer_name', TRUE),
            'customer_email' => $this->input->post('customer_email', TRUE),
            'customer_cell' => $this->input->post('customer_cell', TRUE),
            'customer_address' => $this->input->post('customer_address', TRUE),
            'customer_birthday' => $this->input->post('customer_bday', TRUE),
            'customer_birthmonth' => $this->input->post('customer_bmonth', TRUE),
            'profession' => $this->input->post('customer_profession', TRUE),
            'customer_careof' => $this->input->post('customer_co', TRUE),
            'customer_gender' => $this->input->post('customer_gender', TRUE),
            'referencing_staff' => $this->input->post('customer_refstaff', TRUE),
            'created_by' => $this->input->post('username')
        );
        if($this->db->field_exists('customer_area','customers')){
            $data['customer_area'] = $this->input->post('customer_area', TRUE);
        }
        $this->db->insert('customers', $data);
        return $this->db->insert_id();
    }
    public function getStaff(){
        $business_id = $this->input->get('businessid');
        $sql = "SELECT staff.id_staff,staff.staff_fullname,staff_cell FROM `staff` where business_id = ? and staff_active = 'Y'";
        $resp = $this->db->query($sql, array($business_id));
        $data = $resp->result();
        return $data;
    }
    public function getCities(){
        $business_id = $this->input->get('businessid');
        $sql = "SELECT * FROM `cities` 
                JOIN city_areas on city_areas.city_id = cities.id_cities
                where cities.business_id = ?";
        $resp = $this->db->query($sql, array($business_id));
        $data = $resp->result();
        return $data;
    }
    public function placeOrder(){
        $order_id_for_edit = $this->input->post('order_id_for_edit');
        $businessid = $this->input->post('businessid');
        $customer_id = $this->input->post('customer_id');
        $final_cart_total_qty = $this->input->post('final_cart_total_qty');
        $final_cart_total = $this->input->post('final_cart_total');
        $staff_id = $this->input->post('staff_id');
        $staff_name = $this->input->post('staff_name');
        $order_type = $this->input->post('order_type');
        $products = json_decode($this->input->post('products'));
        // $sql = "SELECT customers.id_customers,customers.customer_name FROM `customers` where id_customers = ? AND business_id = ?";
        // $resp = $this->db->query($sql, array($customer_id,$businessid));
        $sql = "SELECT customers.id_customers,customers.customer_name FROM `customers` where id_customers = ?";
        $resp = $this->db->query($sql, array($customer_id));
        $customers_data = $resp->row();
        $customer_name = $customers_data->customer_name; 

         $sql = "SELECT business_stores.id_business_stores 
        FROM business_stores 
        WHERE business_stores.business_id = ?";
        $resp = $this->db->query($sql, array($businessid));
        $stores_data = $resp->result();
        $store_ids_string ="";
        if (count($stores_data) > 0) {
            $store_ids = array_map(function ($store) {
                return $store->id_business_stores;
            }, $stores_data);
            $store_ids_string = implode(',', $store_ids);
        } 



        if($order_id_for_edit>0){
            $data = array(
                'business_id' => $businessid,
                'customer_id' => $customer_id,
                'order_type' => $order_type,
                'order_status' => 'open'
            );
            $this->db->where('id_customer_order', $order_id_for_edit);
            $this->db->update('customer_orders', $data);

            foreach($products as $item){
                $id_order_products = $item->id_order_products;
                $business_brand_id = $item->brand_id;
                $product_id = $item->product_id;
                $product_name = $item->product_name;
                $qty = $item->product_qty;
                $product_price = $item->product_price;
                $product_discount_amount = $item->product_discount;
                $product_sale_tax_percentage = $item->product_sale_tax_perc;
                $product_sale_tax_amount = $item->product_sale_tax_amount;
                $product_final_price = $item->product_final_price;
                $category = $item->category;
                $batch = $item->batch_number;
                $batch_id = $item->id_batch;
                if($id_order_products > 0){
                    $update_data = array(
                        'business_id' =>                    $businessid,
                        'customer_order_id' =>              $order_id_for_edit,
                        'business_brand_id' =>              $business_brand_id,
                        'product_id' =>                     $product_id,
                        'product_name' =>                   $product_name,
                        'qty' =>                            $qty,
                        'product_unit_price' =>             $product_price,
                        'product_discount_amount' =>        $product_discount_amount,
                        'product_sale_tax_percentage' =>    $product_sale_tax_percentage,
                        'product_sale_tax_amount' =>        $product_sale_tax_amount,
                        'product_final_price' =>            $product_final_price,
                        'staff_id' =>                       $staff_id,
                        'staff_name' =>                     $staff_name,
                        'category' =>                       $category,
                        'batch' =>                          $batch,
                        'batch_id' =>                       $batch_id
                    );

                    $this->db->where('id_order_products', $id_order_products);
                    $this->db->update('order_products', $update_data);
                }else{
                    $order_products_data = array(
                        'business_id' =>                    $businessid,
                        'customer_order_id' =>              $order_id_for_edit,
                        'business_brand_id' =>              $business_brand_id,
                        'product_id' =>                     $product_id,
                        'product_name' =>                   $product_name,
                        'qty' =>                            $qty,
                        'product_unit_price' =>             $product_price,
                        'product_discount_amount' =>        $product_discount_amount,
                        'product_sale_tax_percentage' =>    $product_sale_tax_percentage,
                        'product_sale_tax_amount' =>        $product_sale_tax_amount,
                        'product_final_price' =>            $product_final_price,
                        'staff_id' =>                       $staff_id,
                        'staff_name' =>                     $staff_name,
                        'category' =>                       $category,
                        'batch' =>                          $batch,
                        'batch_id' =>                       $batch_id
                    );
                    $this->db->insert('order_products', $order_products_data);
                }
            }
 
        }else{
                $data = array(
                    'business_id' => $businessid,
                    'customer_id' => $customer_id,
                    'order_type' => $order_type,
                    'customer_order_date' => date('Y-m-d H:i:s'),
                    'order_status' => 'open'
                );
                $this->db->insert('customer_orders', $data);
                $customer_order_id = $this->db->insert_id();
                // $sql = "SELECT customers.id_customers,customers.customer_name FROM `customers` where id_customers = ? AND business_id = ?";
                // $resp = $this->db->query($sql, array($customer_id,$businessid));
                $sql = "SELECT customers.id_customers,customers.customer_name FROM `customers` where id_customers = ?";
                $resp = $this->db->query($sql, array($customer_id));
                $customers_data = $resp->row();
                $customer_name = $customers_data->customer_name;
                foreach($products as $item){
                    $business_brand_id = $item->brand_id;
                    $product_id = $item->product_id;
                    $product_name = $item->product_name;
                    $qty = $item->product_qty;
                    $product_price = $item->product_price;
                    $product_discount_amount = $item->product_discount;
                    $product_sale_tax_percentage = $item->product_sale_tax_perc;
                    $product_sale_tax_amount = $item->product_sale_tax_amount;
                    $product_final_price = $item->product_final_price;
                    $category = $item->category;
                    $batch = $item->batch_number;
                    $batch_id = $item->id_batch;
                    $order_products_data = array(
                        'business_id' =>                    $businessid,
                        'customer_order_id' =>              $customer_order_id,
                        'business_brand_id' =>              $business_brand_id,
                        'product_id' =>                     $product_id,
                        'product_name' =>                   $product_name,
                        'qty' =>                            $qty,
                        'product_unit_price' =>             $product_price,
                        'product_discount_amount' =>        $product_discount_amount,
                        'product_sale_tax_percentage' =>    $product_sale_tax_percentage,
                        'product_sale_tax_amount' =>        $product_sale_tax_amount,
                        'product_final_price' =>            $product_final_price,
                        'staff_id' =>                       $staff_id,
                        'staff_name' =>                     $staff_name,
                        'category' =>                       $category,
                        'batch' =>                          $batch,
                        'batch_id' =>                       $batch_id
                    );
                    $this->db->insert('order_products', $order_products_data);
                } 
     }  

    
        // ===============================> Stock Validation Start From Here <========================================   

        $warning_msg_list =[];
        $sql = "SELECT 
        order_products.customer_order_id AS order_id,
        business_products.id_business_products AS productid,
        business_products.product AS productname,
        business_products.professional,
        business_products.product_type,
        business_products.track_inventory,
        business_products.unit_type,
        business_products.measure_unit,
        business_brands.id_business_brands,
        business_brands.business_brand_name AS brandname,
        business_products.purchase_price AS unitprice,
        order_products.product_final_price AS totalprice, 
        order_products.qty 
    FROM 
        order_products
        INNER JOIN business_products ON business_products.id_business_products = order_products.product_id
        LEFT JOIN business_brands ON business_brands.id_business_brands = order_products.business_brand_id
    WHERE 
        order_products.customer_order_id = ? 
        AND order_products.business_id = ?"; 
         if($order_id_for_edit>0){ 
            $resp = $this->db->query($sql, array($order_id_for_edit, $businessid));
         }else{ 
            $resp = $this->db->query($sql, array($customer_order_id, $businessid));
         }

        $tableData = $resp->result();
        $selected_batch_data =[];
        foreach($tableData as $product_data){
            $product_name =  $product_data->productname;
            $productid =  $product_data->productid;
            $product_type =  $product_data->product_type;
            $track_inventory =  $product_data->track_inventory;
            $unitprice =  $product_data->unitprice;
            $order_id =  $product_data->order_id;
            $unit_type =  $product_data->unit_type;
            $measure_unit =  $product_data->measure_unit;
            if($product_data->product_type =="Physical" && $product_data->track_inventory =="Yes"){
                $sql="SELECT *, 
                ifnull(e.addition, 0) as manualQty,
                ifnull(e.qty_purchased, 0) as purchasedQty,
                ifnull(e.transfer_in, 0) as transfer_in,
                ifnull(e.transfer_out, 0) as transfer_out,
                ifnull(e.sold,0) + ifnull(e.franchise_sale,0) as sold,
                ifnull(e.franchise_sale,0) as franchise_sale,
                ifnull(e.used,0) as used,
                ifnull(e.returned,0) as returned,
                (ifnull(e.addition, 0) + ifnull(e.qty_purchased, 0) + ifnull(e.transfer_in, 0)) - (ifnull(e.transfer_out, 0) + ifnull(e.sold, 0) + ifnull(e.used, 0) + ifnull(e.returned, 0) + ifnull(e.franchise_sale,0)) as total_stock,
                date_format(expiry_date, '%d-%m-%Y') as 'batch_expiry', 
                round(datediff(expiry_date, now())/30) as expiry,
                date_format(batch_date, '%d-%m-%Y') as 'bdate' , batch_amount
                FROM business_products
                LEFT JOIN
                (
                 select id_batch, batch_number, batch_date, expiry_date, batch_qty, qty_purchased,
                 product_batch.product_id, business_store, transfer_in, transfer_out,
                 sold, used, returned, batch_amount, addition, franchise_sale, store_id, business_stores.business_id
                 from 
             product_batch 
                        LEFT join business_stores on business_stores.id_business_stores = product_batch.store_id 
                        LEFT join(
                                SELECT batch_id, sum(adjustment_qty) as addition FROM adjustment_notes
                                group by batch_id
                        ) as adj
                        on adj.batch_id = product_batch.id_batch
                LEFT Join (
                    SELECT batch_id, product_id, sum(invoice_qty) as sold FROM invoice_products
                    join invoice on invoice.id_invoice = invoice_products.invoice_id
                    and invoice_status = 'valid'
                                and ifnull(reference_invoice_number,'') = ''
                    and batch_id is not null
                    group by batch_id, product_id
                ) as a
                on a.product_id = product_batch.product_id 
                and a.batch_id=product_batch.id_batch
                left join(
                    SELECT product_id, batch, batch_id, sum(ifnull(dispatch_qty,0)) as used 
                    FROM dispatch_notes                        
                    where status = 'Active'
                    and batch_id is not null
                    group by product_id, batch, batch_id
                ) as b
                on b.product_id = product_batch.product_id
                and b.batch_id = product_batch.id_batch
                left join(
                    SELECT product_id, batch_id, sum(ifnull(return_qty,0)) as returned
                    FROM return_notes
                    where return_status = 'Active'
                    and batch_id is not null
                    group by product_id,  batch_id
                ) as c
                on c.product_id = product_batch.product_id
                and c.batch_id = product_batch.id_batch
                        left join(
                    SELECT grn_product_id, grn_batch_id, sum(ifnull(grn_qty_received,0)) as qty_purchased
                    FROM grn_details
                    where grn_batch_id is not null
                    group by grn_product_id,  grn_batch_id
                ) as d
                on d.grn_product_id = product_batch.product_id
                and d.grn_batch_id = product_batch.id_batch
                        left join(
                    SELECT product_id, batch_id, sum(ifnull(tranfer_out_qty,0)) as transfer_out, sum(ifnull(tranfer_in_qty,0)) as transfer_in 
                    FROM transfer_notes
                    where batch_id is not null 
                                and transfer_notes.status='Active' 
                    group by product_id, batch_id
                ) as f
                        on f.product_id = product_batch.product_id
                and f.batch_id = product_batch.id_batch
                        left join(
                    SELECT product_id, batch_id, sum(ifnull(qty,0)) as franchise_sale
                    FROM franchise_orders
                                join franchise_order_products on franchise_orders.id_franchise_orders = franchise_order_products.franchise_order_id
                    where batch_id is not null
                                and (franchise_orders.order_status='Paid' OR franchise_orders.order_status='Invoiced')                         
                    group by product_id, batch_id
                                ) as h
                                on h.batch_id = product_batch.id_batch 
                                and  h.product_id = product_batch.product_id
                ) as e ON e.product_id = business_products.id_business_products WHERE id_business_products = ? "; 

                if($store_ids_string !=""){ 
                    $sql.="  AND  e.store_id in ($store_ids_string) ";
                }

                $resp = $this->db->query($sql, array($productid));
                $batchData = $resp->result();
                $batchDataCount = count($batchData);
                $each_product_qty =  $product_data->qty;
                if(  $batchDataCount  < 1){
                        $warning_msg_list[] =" $product_name =>  Available Stock: 0, Required Stock: $each_product_qty";
                }
                $unitprice =  $product_data->unitprice;
                $total_batches_sum=0;
                foreach($batchData as $batch_data){
                    if($batch_data->total_stock > 0){
                        $total_batches_sum+=$batch_data->total_stock;
                    }
                }
                if($total_batches_sum < $each_product_qty){
                    $warning_msg_list[] = " $product_name =>  Available Stock: $total_batches_sum, Required Stock: $each_product_qty";
                }
                foreach($batchData as $batch_data){
                    if($each_product_qty==0){
                        break;
                    }
                    $total_stock = $batch_data->total_stock;
                    $id_batch =  $batch_data->id_batch;
                    $batch_number =  $batch_data->batch_number;
                    $store_id =  $batch_data->store_id;
                    if($total_stock >= $each_product_qty){
                        $total_price = $unitprice * $each_product_qty;
                        $selected_batch_data[]=[
                            "product_name"=>$product_name,
                            "qty"=>$each_product_qty,
                            "productid"=>$productid,
                            "batch_id"=>$id_batch,
                            "batch_number"=>$batch_number,
                            "store_id"=>$store_id,
                            "total_price"=>$total_price ,
                            "product_type"=>"Physical",
                            "unit_type"=> $unit_type,
                            "measure_unit"=>$measure_unit ,
                        ];
                        $each_product_qty=0;
                        break;
                    }elseif( $total_stock < $each_product_qty &&  $total_stock > 0){
                        //   $qty_after_subtraction = $each_product_qty-$total_stock;
                        $each_product_qty=$each_product_qty-$total_stock;
                        $total_price = $unitprice * $total_stock;
                        $selected_batch_data[]=[
                            "product_name"=>$product_name,
                            "qty"=>$total_stock,
                            "productid"=>$productid,
                            "batch_id"=>$id_batch,
                            "batch_number"=>$batch_number,
                            "store_id"=>$store_id,
                            "total_price"=>$total_price ,
                            "product_type"=>"Physical",
                            "unit_type"=> $unit_type,
                            "measure_unit"=>$measure_unit ,
                        ];
                    }
                }
            }elseif($product_data->product_type =="Compiled Kit" && $product_data->track_inventory =="No"){
                $sql="SELECT `kit_config`.`business_product_id` ,  `kit_config`.`kit_qty` ,  `kit_config`.`kit_measure_qty` , `kit_config`.`kit_id`,business_products.purchase_price,business_products.brand_id ,business_products.product ,business_products.unit_type  ,business_products.measure_unit     FROM `kit_config` 
                inner join business_products on business_products.id_business_products = `kit_config`.`business_product_id`  where kit_id=?";
                $resp = $this->db->query($sql, array($productid));
                $kit_inner_products  = $resp->result();
                $kit_inner_products_count   = count($kit_inner_products);
                if( $kit_inner_products_count < 1){
                    $warning_msg_list[]  = "$product_name => kit  doesn't have any physical Products";
                }
                foreach( $kit_inner_products  as $kit_product_data ){
                    $business_product_id =  $kit_product_data->business_product_id;
                    $kit_qty =  $kit_product_data->kit_qty;
                    $unit_price_inner_kit_product =  $kit_product_data->purchase_price;
                    $product_name =  $kit_product_data->product;
                    $unit_type =  $kit_product_data->unit_type;
                    $measure_unit =  $kit_product_data->measure_unit;
                    $sql="SELECT *, 
                  ifnull(e.addition, 0) as manualQty, 
                  ifnull(e.qty_purchased, 0) as purchasedQty,
                  ifnull(e.transfer_in, 0) as transfer_in,
                  ifnull(e.transfer_out, 0) as transfer_out,
                  ifnull(e.sold,0) + ifnull(e.franchise_sale,0) as sold,
                  ifnull(e.franchise_sale,0) as franchise_sale,
                  ifnull(e.used,0) as used,
                  ifnull(e.returned,0) as returned,
                  (ifnull(e.addition, 0) + ifnull(e.qty_purchased, 0) + ifnull(e.transfer_in, 0)) - (ifnull(e.transfer_out, 0) + ifnull(e.sold, 0) + ifnull(e.used, 0) + ifnull(e.returned, 0) + ifnull(e.franchise_sale,0)) as total_stock,
                  date_format(expiry_date, '%d-%m-%Y') as 'batch_expiry', 
                  round(datediff(expiry_date, now())/30) as expiry,
                  date_format(batch_date, '%d-%m-%Y') as 'bdate' , batch_amount
                  FROM business_products
                  LEFT JOIN
                  (
                   select id_batch, batch_number, batch_date, expiry_date, batch_qty, qty_purchased,
                   product_batch.product_id, business_store, transfer_in, transfer_out,
                   sold, used, returned, batch_amount, addition, franchise_sale, store_id, business_stores.business_id
                   from 
               product_batch 
                          LEFT join business_stores on business_stores.id_business_stores = product_batch.store_id 
                          LEFT join(
                                  SELECT batch_id, sum(adjustment_qty) as addition FROM adjustment_notes
                                  group by batch_id
                          ) as adj
                          on adj.batch_id = product_batch.id_batch
                  LEFT Join (
                      SELECT batch_id, product_id, sum(invoice_qty) as sold FROM invoice_products
                      join invoice on invoice.id_invoice = invoice_products.invoice_id
                      and invoice_status = 'valid'
                                  and ifnull(reference_invoice_number,'') = ''
                      and batch_id is not null
                      group by batch_id, product_id
                  ) as a
                  on a.product_id = product_batch.product_id 
                  and a.batch_id=product_batch.id_batch
                  left join(
                      SELECT product_id, batch, batch_id, sum(ifnull(dispatch_qty,0)) as used 
                      FROM dispatch_notes                        
                      where status = 'Active'
                      and batch_id is not null
                      group by product_id, batch, batch_id
                  ) as b
                  on b.product_id = product_batch.product_id
                  and b.batch_id = product_batch.id_batch
                  left join(
                      SELECT product_id, batch_id, sum(ifnull(return_qty,0)) as returned
                      FROM return_notes
                      where return_status = 'Active'
                      and batch_id is not null
                      group by product_id,  batch_id
                  ) as c
                  on c.product_id = product_batch.product_id
                  and c.batch_id = product_batch.id_batch
                          left join(
                      SELECT grn_product_id, grn_batch_id, sum(ifnull(grn_qty_received,0)) as qty_purchased
                      FROM grn_details
                      where grn_batch_id is not null
                      group by grn_product_id,  grn_batch_id
                  ) as d
                  on d.grn_product_id = product_batch.product_id
                  and d.grn_batch_id = product_batch.id_batch
                          left join(
                      SELECT product_id, batch_id, sum(ifnull(tranfer_out_qty,0)) as transfer_out, sum(ifnull(tranfer_in_qty,0)) as transfer_in 
                      FROM transfer_notes
                      where batch_id is not null 
                                  and transfer_notes.status='Active' 
                      group by product_id, batch_id
                  ) as f
                          on f.product_id = product_batch.product_id
                  and f.batch_id = product_batch.id_batch
                          left join(
                      SELECT product_id, batch_id, sum(ifnull(qty,0)) as franchise_sale
                      FROM franchise_orders
                                  join franchise_order_products on franchise_orders.id_franchise_orders = franchise_order_products.franchise_order_id
                      where batch_id is not null
                                  and (franchise_orders.order_status='Paid' OR franchise_orders.order_status='Invoiced')                         
                      group by product_id, batch_id
                                  ) as h
                                  on h.batch_id = product_batch.id_batch 
                                  and  h.product_id = product_batch.product_id
                  ) as e ON e.product_id = business_products.id_business_products WHERE id_business_products = ? "; 

                    if($store_ids_string !=""){ 
                        $sql.="  AND  e.store_id in ($store_ids_string) ";
                    }

                    $resp = $this->db->query($sql, array($business_product_id));
                    $batchData = $resp->result();

                    $batchDataCount = count($batchData);
                    $each_product_qty =  $product_data->qty*$kit_qty;
                    if($batchDataCount  < 1){
                        $warning_msg_list[]  = " $product_name =>  Available Stock: 0, Required Stock: $each_product_qty";
                    }
                    $unitprice =   $unit_price_inner_kit_product;
                    $total_batches_sum=0;
                    foreach($batchData as $batch_data){
                        if($batch_data->total_stock > 0){
                            $total_batches_sum+=$batch_data->total_stock;
                        }
                    }
                    if($total_batches_sum < $each_product_qty){
                        $warning_msg_list[]  =   " $product_name =>  Available Stock: $total_batches_sum, Required Stock: $each_product_qty";
                    }

                    foreach($batchData as $batch_data){
                        if($each_product_qty==0){
                            break;
                        }
                        $total_stock = $batch_data->total_stock;
                        $id_batch =  $batch_data->id_batch;
                        $batch_number =  $batch_data->batch_number;
                        $store_id =  $batch_data->store_id;
                        if($total_stock >= $each_product_qty){
                            $total_price =  $unit_price_inner_kit_product * $each_product_qty;
                            $selected_batch_data[]=[
                                "product_name"=>$product_name,
                                "qty"=>$each_product_qty,
                                "productid"=>$business_product_id,
                                "batch_id"=>$id_batch,
                                "batch_number"=>$batch_number,
                                "store_id"=>$store_id,
                                "total_price"=>$total_price ,
                                "product_type"=>"Compiled Kit",
                                "unit_type"=>$unit_type,
                                "measure_unit"=>$measure_unit,
                            ];
                            $each_product_qty=0;
                            break;
                        }elseif( $total_stock < $each_product_qty &&  $total_stock >0){
                            $qty_after_subtraction = $each_product_qty-$total_stock;
                            $each_product_qty=$each_product_qty-$total_stock;
                            $total_price = $unit_price_inner_kit_product * $total_stock;
                            $selected_batch_data[]=[
                                "product_name"=>$product_name,
                                "qty"=>$total_stock,
                                "productid"=>$business_product_id,
                                "batch_id"=>$id_batch,
                                "batch_number"=>$batch_number,
                                "store_id"=>$store_id,
                                "total_price"=>$total_price ,
                                "product_type"=>"Compiled Kit",
                                "unit_type"=>$unit_type,
                                "measure_unit"=>$measure_unit,
                            ];
                        }
                    }
                }
            }
        }
        
        //================================> Stock Validation ENd  Here <============================================== 

      // ===================================>  Getting Runing Order Start  <=================================================  
                $sql = "SELECT 
                customer_orders.id_customer_order as order_id, 
                customer_orders.customer_order_date as order_date,
                customer_orders.order_status as status,
                customers.customer_name,
                staff.staff_fullname,
                sum(order_products.qty) as total_qty,
                sum(order_products.product_final_price) as total
                FROM customer_orders
                JOIN customers on customers.id_customers = customer_orders.customer_id
                JOIN order_products on order_products.customer_order_id = customer_orders.id_customer_order
                LEFT JOIN staff on staff.id_staff = order_products.staff_id
                WHERE customer_orders.order_status = 'open'
                AND customer_orders.business_id = ?
                GROUP BY customer_orders.id_customer_order order by order_id desc ";
            $resp = $this->db->query($sql, array($businessid));
            $running_order_data = $resp->result(); 
     // ===================================>  Getting Runing Order ENd   <=================================================   

        if($order_id_for_edit>0){ 
            $response_data['order_id'] = $order_id_for_edit;
            $response_data['flag'] = "Update"; 
            $response_data['order_date'] = date('Y-m-d H:i:s');
            $response_data['status'] = 'open';
            $response_data['customer_name'] = $customer_name;
            $response_data['staff'] = $staff_name;
            $response_data['total_qty'] = $final_cart_total_qty;
            $response_data['total'] = $final_cart_total;
            $response_data['inventry_warning_msg'] = $warning_msg_list;
            $response_data['running_order_data'] = $running_order_data;
            
        }else{  
            $response_data['order_id'] = $customer_order_id; 
            $response_data['flag'] = "Added"; 
            $response_data['order_date'] = date('Y-m-d H:i:s');
            $response_data['status'] = 'open';
            $response_data['customer_name'] = $customer_name;
            $response_data['staff'] = $staff_name;
            $response_data['total_qty'] = $final_cart_total_qty;
            $response_data['total'] = $final_cart_total;
            $response_data['inventry_warning_msg'] = $warning_msg_list;
            $response_data['running_order_data'] = $running_order_data;
        } 

        return $response_data;
    }
    public function runningOrder(){
        $business_id = $this->input->get('businessid');
        $sql = "SELECT 
                    customer_orders.id_customer_order as order_id, 
                    customer_orders.customer_order_date as order_date,
                    customer_orders.order_status as status,
                    customers.customer_name,
                    staff.staff_fullname,
                    sum(order_products.qty) as total_qty,
                    sum(order_products.product_final_price) as total
                    FROM customer_orders
                    JOIN customers on customers.id_customers = customer_orders.customer_id
                    JOIN order_products on order_products.customer_order_id = customer_orders.id_customer_order
                    LEFT JOIN staff on staff.id_staff = order_products.staff_id
                    WHERE customer_orders.order_status = 'open'
                    AND customer_orders.business_id = ?
                    GROUP BY customer_orders.id_customer_order order by order_id desc ";
        $resp = $this->db->query($sql, array($business_id));
        $data = $resp->result();
        return $data;
    } 

    public function gettingOrdersWithBalance(){
        $business_id = $this->input->get('businessid');
        $sql="SELECT 
                    customer_orders.id_customer_order as order_id, 
                    customer_orders.customer_order_date as order_date,
                    customer_orders.order_status as status,
                    customers.customer_name,
                    staff.staff_fullname,
                    sum(order_products.qty) as total_qty,
                    sum(order_products.product_final_price) as total ,
                    invoice.net_amount,
                    SUM(invoice.paid_amount),
                    invoice.balance ,
                    MIN(invoice.id_invoice) as invoice_id
                    FROM customer_orders
                    JOIN customers on customers.id_customers = customer_orders.customer_id
                    JOIN order_products on order_products.customer_order_id = customer_orders.id_customer_order
                    left Join staff on staff.id_staff = order_products.staff_id
                    join invoice on invoice.visit_id = customer_orders.id_customer_order
                    WHERE customer_orders.business_id = ?  and invoice.invoice_status !='cancelled' 
                    GROUP BY customer_orders.id_customer_order HAVING invoice.net_amount > SUM(invoice.paid_amount) ORDER BY customer_orders.id_customer_order DESC;"; 

            $resp = $this->db->query($sql, array($business_id));
            $data = $resp->result();
            return $data;
    }

    public function getting_recent_invoices(){ 
        $business_id = $this->input->get('businessid');
        
        $sql="SELECT 
                    customer_orders.id_customer_order as order_id, 
                    customer_orders.customer_order_date as order_date,
                    customer_orders.order_status as status,
                    staff.staff_fullname,
                    invoice.invoice_number,
                    invoice.invoice_date,
                    invoice.sub_total,
                    invoice.discount,
                    invoice.gross_amount,
                    invoice.tax_total,
                    invoice.net_amount,
                    invoice.paid_amount,
                    invoice.balance,
                    invoice.customer_name,
                    invoice.id_invoice as invoice_id
                    FROM customer_orders
                    JOIN customers on customers.id_customers = customer_orders.customer_id
                    JOIN order_products on order_products.customer_order_id = customer_orders.id_customer_order
                    LEFT JOIN staff on staff.id_staff = order_products.staff_id
                    join invoice on invoice.visit_id = customer_orders.id_customer_order
                    WHERE customer_orders.business_id = ?  and invoice.invoice_status !='cancelled' 
                    Group BY  invoice.id_invoice  ORDER BY  invoice.id_invoice DESC LIMIT 10;";

                    $resp = $this->db->query($sql, array($business_id));
                    $data = $resp->result();
                    return $data;
    }

    public function orderDetails(){
        $business_id = $this->input->get('businessid');
        $order_id = $this->input->get('order_id');
        $sql = "SELECT 
                    customer_orders.id_customer_order as order_id, 
                    customer_orders.customer_order_date as order_date,
                    customer_orders.order_status as status,
                    customer_orders.order_type, 
                    customers.customer_name,
                    customers.id_customers,
                    staff.staff_fullname,
                    staff.id_staff,
                    sum(order_products.qty) as total_qty,
                    sum(order_products.product_unit_price*order_products.qty) as sub_total_amount,
                    sum(order_products.product_sale_tax_amount) as total_tax_amount,
                    sum(order_products.product_discount_amount) as total_discount_amount,
                    sum(order_products.product_final_price) as total
                    FROM customer_orders
                    JOIN customers on customers.id_customers = customer_orders.customer_id
                    JOIN order_products on order_products.customer_order_id = customer_orders.id_customer_order
                    LEFT JOIN staff on staff.id_staff = order_products.staff_id
                    WHERE customer_orders.order_status = 'open'
                    AND customer_orders.business_id = ?
                    AND customer_orders.id_customer_order = ?
                    GROUP BY customer_orders.id_customer_order";
        $resp = $this->db->query($sql, array($business_id,$order_id));
        $order_data = $resp->row();
        $sql = "SELECT * FROM `order_products` where customer_order_id = ?";
        $resp = $this->db->query($sql, array($order_id));
        $products_data = $resp->result();
        $order_data->products = $products_data;
        return $order_data;
    }
    public function createInvoice(){

        $business_id = $this->input->post('businessid');  

        $sql = "SELECT business_stores.id_business_stores 
                FROM business_stores 
                WHERE business_stores.id_business_stores = ?";
        $resp = $this->db->query($sql, array($business_id));
        $stores_data = $resp->result();
        $store_ids_string ="";
        if (count($stores_data) > 0) {
            $store_ids = array_map(function ($store) {
                return $store->id_business_stores;
            }, $stores_data);
            $store_ids_string = implode(',', $store_ids);
        } 

        $order_id = $this->input->post('order_id');
        $sql = "SELECT 
        order_products.customer_order_id AS order_id,
        business_products.id_business_products AS productid,
        business_products.product AS productname,
        business_products.professional,
        business_products.product_type,
        business_products.track_inventory,
        business_products.unit_type,
        business_products.measure_unit,
        business_brands.id_business_brands,
        business_brands.business_brand_name AS brandname,
        business_products.purchase_price AS unitprice,
        order_products.product_final_price AS totalprice, 
        order_products.qty 
    FROM 
        order_products
        INNER JOIN business_products ON business_products.id_business_products = order_products.product_id
        LEFT JOIN business_brands ON business_brands.id_business_brands = order_products.business_brand_id
    WHERE 
        order_products.customer_order_id = ? 
        AND order_products.business_id = ?";
        $resp = $this->db->query($sql, array($order_id, $business_id));
        $tableData = $resp->result();
        $selected_batch_data =[];
        foreach($tableData as $product_data){
            $product_name =  $product_data->productname;
            $productid =  $product_data->productid;
            $product_type =  $product_data->product_type;
            $track_inventory =  $product_data->track_inventory;
            $unitprice =  $product_data->unitprice;
            $order_id =  $product_data->order_id;
            $unit_type =  $product_data->unit_type;
            $measure_unit =  $product_data->measure_unit;
            if($product_data->product_type =="Physical" && $product_data->track_inventory =="Yes"){
                $sql="SELECT *, 
                ifnull(e.addition, 0) as manualQty,
                ifnull(e.qty_purchased, 0) as purchasedQty,
                ifnull(e.transfer_in, 0) as transfer_in,
                ifnull(e.transfer_out, 0) as transfer_out,
                ifnull(e.sold,0) + ifnull(e.franchise_sale,0) as sold,
                ifnull(e.franchise_sale,0) as franchise_sale,
                ifnull(e.used,0) as used,
                ifnull(e.returned,0) as returned,
                (ifnull(e.addition, 0) + ifnull(e.qty_purchased, 0) + ifnull(e.transfer_in, 0)) - (ifnull(e.transfer_out, 0) + ifnull(e.sold, 0) + ifnull(e.used, 0) + ifnull(e.returned, 0) + ifnull(e.franchise_sale,0)) as total_stock,
                date_format(expiry_date, '%d-%m-%Y') as 'batch_expiry', 
                round(datediff(expiry_date, now())/30) as expiry,
                date_format(batch_date, '%d-%m-%Y') as 'bdate' , batch_amount
                FROM business_products
                LEFT JOIN
                (
                 select id_batch, batch_number, batch_date, expiry_date, batch_qty, qty_purchased,
                 product_batch.product_id, business_store, transfer_in, transfer_out,
                 sold, used, returned, batch_amount, addition, franchise_sale, store_id, business_stores.business_id
                 from 
             product_batch 
                        LEFT join business_stores on business_stores.id_business_stores = product_batch.store_id 
                        LEFT join(
                                SELECT batch_id, sum(adjustment_qty) as addition FROM adjustment_notes
                                group by batch_id
                        ) as adj
                        on adj.batch_id = product_batch.id_batch
                LEFT Join (
                    SELECT batch_id, product_id, sum(invoice_qty) as sold FROM invoice_products
                    join invoice on invoice.id_invoice = invoice_products.invoice_id
                    and invoice_status = 'valid'
                                and ifnull(reference_invoice_number,'') = ''
                    and batch_id is not null
                    group by batch_id, product_id
                ) as a
                on a.product_id = product_batch.product_id 
                and a.batch_id=product_batch.id_batch
                left join(
                    SELECT product_id, batch, batch_id, sum(ifnull(dispatch_qty,0)) as used 
                    FROM dispatch_notes                        
                    where status = 'Active'
                    and batch_id is not null
                    group by product_id, batch, batch_id
                ) as b
                on b.product_id = product_batch.product_id
                and b.batch_id = product_batch.id_batch
                left join(
                    SELECT product_id, batch_id, sum(ifnull(return_qty,0)) as returned
                    FROM return_notes
                    where return_status = 'Active'
                    and batch_id is not null
                    group by product_id,  batch_id
                ) as c
                on c.product_id = product_batch.product_id
                and c.batch_id = product_batch.id_batch
                        left join(
                    SELECT grn_product_id, grn_batch_id, sum(ifnull(grn_qty_received,0)) as qty_purchased
                    FROM grn_details
                    where grn_batch_id is not null
                    group by grn_product_id,  grn_batch_id
                ) as d
                on d.grn_product_id = product_batch.product_id
                and d.grn_batch_id = product_batch.id_batch
                        left join(
                    SELECT product_id, batch_id, sum(ifnull(tranfer_out_qty,0)) as transfer_out, sum(ifnull(tranfer_in_qty,0)) as transfer_in 
                    FROM transfer_notes
                    where batch_id is not null 
                                and transfer_notes.status='Active' 
                    group by product_id, batch_id
                ) as f
                        on f.product_id = product_batch.product_id
                and f.batch_id = product_batch.id_batch
                        left join(
                    SELECT product_id, batch_id, sum(ifnull(qty,0)) as franchise_sale
                    FROM franchise_orders
                                join franchise_order_products on franchise_orders.id_franchise_orders = franchise_order_products.franchise_order_id
                    where batch_id is not null
                                and (franchise_orders.order_status='Paid' OR franchise_orders.order_status='Invoiced')                         
                    group by product_id, batch_id
                                ) as h
                                on h.batch_id = product_batch.id_batch 
                                and  h.product_id = product_batch.product_id
                ) as e ON e.product_id = business_products.id_business_products WHERE id_business_products = ? "; 
                
                if($store_ids_string !=""){ 
                    $sql.="  AND  e.store_id in ($store_ids_string) ";
                }

                $resp = $this->db->query($sql, array($productid));
                $batchData = $resp->result();
                $batchDataCount = count($batchData);
                if(  $batchDataCount  < 1){
                    $response = array(
                        'warning_msg' => "The current inventory for $product_name is insufficient to fulfill your required quantity. Total stock available: 0"
                    );
                    return  $response;
                }
                $each_product_qty =  $product_data->qty;
                $unitprice =  $product_data->unitprice;
                $total_batches_sum=0;
                foreach($batchData as $batch_data){
                    if($batch_data->total_stock > 0){
                        $total_batches_sum+=$batch_data->total_stock;
                    }
                }
                if($total_batches_sum < $each_product_qty){
                    $response = array(
                        'warning_msg' => "The current inventory for $product_name is insufficient to fulfill your required quantity. Total stock available: $total_batches_sum"
                    );
                    return  $response;
                }
                foreach($batchData as $batch_data){
                    if($each_product_qty==0){
                        break;
                    }
                    $total_stock = $batch_data->total_stock;
                    $id_batch =  $batch_data->id_batch;
                    $batch_number =  $batch_data->batch_number;
                    $store_id =  $batch_data->store_id;
                    if($total_stock >= $each_product_qty){
                        $total_price = $unitprice * $each_product_qty;
                        $selected_batch_data[]=[
                            "product_name"=>$product_name,
                            "qty"=>$each_product_qty,
                            "productid"=>$productid,
                            "batch_id"=>$id_batch,
                            "batch_number"=>$batch_number,
                            "store_id"=>$store_id,
                            "total_price"=>$total_price ,
                            "product_type"=>"Physical",
                            "unit_type"=> $unit_type,
                            "measure_unit"=>$measure_unit ,
                        ];
                        $each_product_qty=0;
                        break;
                    }elseif( $total_stock < $each_product_qty &&  $total_stock > 0){
                        //   $qty_after_subtraction = $each_product_qty-$total_stock;
                        $each_product_qty=$each_product_qty-$total_stock;
                        $total_price = $unitprice * $total_stock;
                        $selected_batch_data[]=[
                            "product_name"=>$product_name,
                            "qty"=>$total_stock,
                            "productid"=>$productid,
                            "batch_id"=>$id_batch,
                            "batch_number"=>$batch_number,
                            "store_id"=>$store_id,
                            "total_price"=>$total_price ,
                            "product_type"=>"Physical",
                            "unit_type"=> $unit_type,
                            "measure_unit"=>$measure_unit ,
                        ];
                    }
                }
            }elseif($product_data->product_type =="Compiled Kit" && $product_data->track_inventory =="No"){
                $sql="SELECT `kit_config`.`business_product_id` ,  `kit_config`.`kit_qty` ,  `kit_config`.`kit_measure_qty` , `kit_config`.`kit_id`,business_products.purchase_price,business_products.brand_id ,business_products.product ,business_products.unit_type  ,business_products.measure_unit     FROM `kit_config` 
                inner join business_products on business_products.id_business_products = `kit_config`.`business_product_id`  where kit_id=?";
                $resp = $this->db->query($sql, array($productid));
                $kit_inner_products  = $resp->result();
                $kit_inner_products_count   = count($kit_inner_products);
                if( $kit_inner_products_count < 1){
                    $response = array(
                        'warning_msg' => "The current inventory for $product_name is insufficient to fulfill your required quantity. Total stock available: 0"
                    );
                    return  $response ;
                }
                foreach( $kit_inner_products  as $kit_product_data ){

                    $business_product_id =  $kit_product_data->business_product_id;
                    $kit_qty =  $kit_product_data->kit_qty;
                    $unit_price_inner_kit_product =  $kit_product_data->purchase_price;
                    $product_name =  $kit_product_data->product;
                    $unit_type =  $kit_product_data->unit_type;
                    $measure_unit =  $kit_product_data->measure_unit;
                    $sql="SELECT *, 
                  ifnull(e.addition, 0) as manualQty,
                  ifnull(e.qty_purchased, 0) as purchasedQty,
                  ifnull(e.transfer_in, 0) as transfer_in,
                  ifnull(e.transfer_out, 0) as transfer_out,
                  ifnull(e.sold,0) + ifnull(e.franchise_sale,0) as sold,
                  ifnull(e.franchise_sale,0) as franchise_sale,
                  ifnull(e.used,0) as used,
                  ifnull(e.returned,0) as returned,
                  (ifnull(e.addition, 0) + ifnull(e.qty_purchased, 0) + ifnull(e.transfer_in, 0)) - (ifnull(e.transfer_out, 0) + ifnull(e.sold, 0) + ifnull(e.used, 0) + ifnull(e.returned, 0) + ifnull(e.franchise_sale,0)) as total_stock,
                  date_format(expiry_date, '%d-%m-%Y') as 'batch_expiry', 
                  round(datediff(expiry_date, now())/30) as expiry,
                  date_format(batch_date, '%d-%m-%Y') as 'bdate' , batch_amount
                  FROM business_products
                  LEFT JOIN
                  (
                   select id_batch, batch_number, batch_date, expiry_date, batch_qty, qty_purchased,
                   product_batch.product_id, business_store, transfer_in, transfer_out,
                   sold, used, returned, batch_amount, addition, franchise_sale, store_id, business_stores.business_id
                   from 
               product_batch 
                          LEFT join business_stores on business_stores.id_business_stores = product_batch.store_id 
                          LEFT join(
                                  SELECT batch_id, sum(adjustment_qty) as addition FROM adjustment_notes
                                  group by batch_id
                          ) as adj
                          on adj.batch_id = product_batch.id_batch
                  LEFT Join (
                      SELECT batch_id, product_id, sum(invoice_qty) as sold FROM invoice_products
                      join invoice on invoice.id_invoice = invoice_products.invoice_id
                      and invoice_status = 'valid'
                                  and ifnull(reference_invoice_number,'') = ''
                      and batch_id is not null
                      group by batch_id, product_id
                  ) as a
                  on a.product_id = product_batch.product_id 
                  and a.batch_id=product_batch.id_batch
                  left join(
                      SELECT product_id, batch, batch_id, sum(ifnull(dispatch_qty,0)) as used 
                      FROM dispatch_notes                        
                      where status = 'Active'
                      and batch_id is not null
                      group by product_id, batch, batch_id
                  ) as b
                  on b.product_id = product_batch.product_id
                  and b.batch_id = product_batch.id_batch
                  left join(
                      SELECT product_id, batch_id, sum(ifnull(return_qty,0)) as returned
                      FROM return_notes
                      where return_status = 'Active'
                      and batch_id is not null
                      group by product_id,  batch_id
                  ) as c
                  on c.product_id = product_batch.product_id
                  and c.batch_id = product_batch.id_batch
                          left join(
                      SELECT grn_product_id, grn_batch_id, sum(ifnull(grn_qty_received,0)) as qty_purchased
                      FROM grn_details
                      where grn_batch_id is not null
                      group by grn_product_id,  grn_batch_id
                  ) as d
                  on d.grn_product_id = product_batch.product_id
                  and d.grn_batch_id = product_batch.id_batch
                          left join(
                      SELECT product_id, batch_id, sum(ifnull(tranfer_out_qty,0)) as transfer_out, sum(ifnull(tranfer_in_qty,0)) as transfer_in 
                      FROM transfer_notes
                      where batch_id is not null 
                                  and transfer_notes.status='Active' 
                      group by product_id, batch_id
                  ) as f
                          on f.product_id = product_batch.product_id
                  and f.batch_id = product_batch.id_batch
                          left join(
                      SELECT product_id, batch_id, sum(ifnull(qty,0)) as franchise_sale
                      FROM franchise_orders
                                  join franchise_order_products on franchise_orders.id_franchise_orders = franchise_order_products.franchise_order_id
                      where batch_id is not null
                                  and (franchise_orders.order_status='Paid' OR franchise_orders.order_status='Invoiced')                         
                      group by product_id, batch_id
                                  ) as h
                                  on h.batch_id = product_batch.id_batch 
                                  and  h.product_id = product_batch.product_id
                  ) as e ON e.product_id = business_products.id_business_products WHERE id_business_products = ?  "; 

                    if($store_ids_string !=""){ 
                        $sql.="  AND  e.store_id in ($store_ids_string) ";
                    } 

                    $resp = $this->db->query($sql, array($business_product_id));
                    $batchData = $resp->result();

                    $batchDataCount = count($batchData);
                    if($batchDataCount  < 1){
                        $response = array(
                            'warning_msg' => "The current inventory for $product_name is insufficient to fulfill your required quantity. Total stock available: 0"
                        );
                        return   $response;
                    }
                    $each_product_qty =  $product_data->qty*$kit_qty;
                    $unitprice =   $unit_price_inner_kit_product;
                    $total_batches_sum=0;
                    foreach($batchData as $batch_data){
                        if($batch_data->total_stock > 0){
                            $total_batches_sum+=$batch_data->total_stock;
                        }
                    }
                    if($total_batches_sum < $each_product_qty){
                        $response = array(
                            'warning_msg' => "The current inventory for $product_name is insufficient to fulfill your required quantity. Total stock available: $total_batches_sum"
                        );
                        return   $response;
                    }

                    foreach($batchData as $batch_data){
                        if($each_product_qty==0){
                            break;
                        }
                        $total_stock = $batch_data->total_stock;
                        $id_batch =  $batch_data->id_batch;
                        $batch_number =  $batch_data->batch_number;
                        $store_id =  $batch_data->store_id;
                        if($total_stock >= $each_product_qty){
                            $total_price =  $unit_price_inner_kit_product * $each_product_qty;
                            $selected_batch_data[]=[
                                "product_name"=>$product_name,
                                "qty"=>$each_product_qty,
                                "productid"=>$business_product_id,
                                "batch_id"=>$id_batch,
                                "batch_number"=>$batch_number,
                                "store_id"=>$store_id,
                                "total_price"=>$total_price ,
                                "product_type"=>"Compiled Kit",
                                "unit_type"=>$unit_type,
                                "measure_unit"=>$measure_unit,
                            ];
                            $each_product_qty=0;
                            break;
                        }elseif( $total_stock < $each_product_qty &&  $total_stock >0){
                            $qty_after_subtraction = $each_product_qty-$total_stock;
                            $each_product_qty=$each_product_qty-$total_stock;
                            $total_price = $unit_price_inner_kit_product * $total_stock;
                            $selected_batch_data[]=[
                                "product_name"=>$product_name,
                                "qty"=>$total_stock,
                                "productid"=>$business_product_id,
                                "batch_id"=>$id_batch,
                                "batch_number"=>$batch_number,
                                "store_id"=>$store_id,
                                "total_price"=>$total_price ,
                                "product_type"=>"Compiled Kit",
                                "unit_type"=>$unit_type,
                                "measure_unit"=>$measure_unit,
                            ];
                        }
                    }
                }
            }
        }
        $paymentmode=$this->input->post('payment_mode');
        $paid=$this->input->post('paid')-$this->input->post('returnamount');
        $discount = $this->input->post('total_discount_amount');
        $taxtotal = $this->input->post('total_tax_amount');
        $gross_amount = $this->input->post('sub_total');
        $org_subtotal = $this->input->post('sub_total');
        $net_amount = $this->input->post('net_amount');
        $created_by = $this->input->post('created_by');
        $instrumentnumber = $paymentmode=='Online' ? 'Online '.$this->input->post('instrument_number', TRUE) :  $this->input->post('instrument_number', TRUE);
        $balance = $this->input->post('balance');
        $returnamount = $this->input->post('returnamount');
        $instrument_no = $this->input->post('instrument_no');
        $cc_charge = 0;
        $advance_amount = 0;
        $other_charges = 0;
        $totaladdition = 0;
        $retained_used = 0;
        $retained_amount_used = 0;
        $voucherpaid = 0;
        $totalpayable = $this->input->post('totalpayable');
        $cashpaid = 0;
        $cardpaid = 0;
        $checkpaid = 0;
        $total_service_additions=0;
        $taxes=$this->input->post('taxes', TRUE);
        if($paymentmode=="Cash"){$cashpaid=$paid; $totalpaidnow = $this->input->post('paid');}
        else if($paymentmode=="Card"){$cardpaid=$paid; $totalpaidnow = $this->input->post('paid');}
        else if($paymentmode=="Check"){$checkpaid=$paid; $totalpaidnow = $this->input->post('paid');}
        else if($paymentmode=="Online"){$checkpaid=$paid; $paymentmode='Check'; $totalpaidnow = $this->input->post('paid');}
        else if($paymentmode=="Voucher"){$voucherpaid=$paid; $totalpaidnow = $this->input->post('paid');}
        else if($paymentmode=="Mixed"){
            $cashpaid=$this->input->post('cash_paid', TRUE);
            $cardpaid=$this->input->post('card_paid', TRUE);
            $totalpaidnow = $cashpaid + $cardpaid;
        }
        $this->db->select('*');
        $this->db->join('customers', 'customers.id_customers = customer_orders.customer_id');
        $this->db->where('customer_orders.id_customer_order', $order_id);
        $this->db->where('customer_orders.business_id', $business_id);
        $customerorders = $this->db->get('customer_orders');
        $customerorder = $customerorders->row();
        $invoice_date=date('Y-m-d H:i:s');
        $visittime=$invoice_date;
        $customername=$customerorder->customer_name;
        $customerid = $customerorder->id_customers;
        $data = array(
            'customer_id'=>$customerid,
            'invoice_number'=>'999',
            'business_id'=>$business_id,
            'customer_name'=> $customerorder->customer_name,
            'customer_cell'=> $customerorder->customer_cell,
            'customer_email'=> $customerorder->customer_email,
            'customer_address'=> $customerorder->customer_address,
            'tax_total'=>$taxtotal,
            'paid_amount' => $paid,
            'paid_cash' => $cashpaid,
            'paid_card' => $cardpaid,
            'paid_voucher' => $voucherpaid,
            'paid_check' => $checkpaid,
            'discount' => $discount,
            'gross_amount' => $gross_amount + $taxtotal,
            'gross_wo_tax' => $gross_amount,
            'net_amount' => $net_amount,
            'visit_id' => $order_id,
            'order_id' => $order_id,
            'visit_time' => $visittime,
            'sub_total' => $org_subtotal ,
            'invoice_type'=>'sale',
            'payment_mode'=>$paymentmode,
            'instrument_number'=>$instrumentnumber,
            'cc_charge'=>$cc_charge,
            'balance'=>$balance,
            'is_recovery' => $balance > 0 ? 'Yes' : 'No',
            'discount_remarks' => $this->input->post('discount_remarks'),
            'returnamount' => $returnamount,
            'loyalty_used'=> 0,
            'advance_amount'=>$advance_amount,
            'other_charges'=>$other_charges + $totaladdition,
            'invoice_date'=>$invoice_date,
            'retained_used'=>$retained_used,
            'retained_amount_used'=>$retained_amount_used,
            'retained_amount'=>0,
            'cctip'=>0,
            'loyalty_earned'=> 0,
            'total_payable'=>$totalpayable,
            'instrument_number'=>$instrument_no,
            'created_by' => $created_by
        );
        $this->db->insert('invoice', $data);
        $invoiceid =  $this->db->insert_id();
        //make sure invoice number is correct
        $today=date('Y-m-d');
        $seq=1;
        $sql = "select max(invoice_seq)+1 as 'seq'
            from invoice where day(invoice_date)= day('".$today."') 
            and month(invoice_date)= month('".$today."') and year(invoice_date)= year('".$today."')";
        $query = $this->db->query($sql);
        $invoice_seq =  $query->row();
        $update_invoice = array(
            'invoice_number' => date('Y-m').'-'.$invoiceid,
            'invoice_seq' => $seq
        );
        $this->db->where(array(
            'business_id' => $business_id,
            'id_invoice' => $invoiceid
        ));
        $this->db->update('invoice', $update_invoice);
        if(isset($invoice_seq) && null !== $invoice_seq->seq){$seq=$invoice_seq->seq;}
        $sql ="SELECT business_brands.id_business_brands,
                       business_brands.business_brand_name,
                       business_products.product,
                       order_products.product_id,
                       order_products.category,
                       order_products.staff_name,
                       order_products.staff_id,
                       order_products.qty,
                       order_products.product_discount_amount,
                       order_products.product_final_price,
                       order_products.product_sale_tax_amount,
                       business_products.price,
                       business_products.id_business_products AS product_id,
                       business_products.category AS category,
                       order_products.batch,
                       order_products.batch_id,
                       order_status, 
                       business_products.commission,
                       business_products.product_type,
                       business_products.product_sales_tax ,
                       business_products.purchase_price 
                FROM order_products
                JOIN business_products ON business_products.id_business_products = order_products.product_id
                JOIN business_brands ON business_brands.id_business_brands = business_products.brand_id
                JOIN customer_orders ON customer_orders.id_customer_order = order_products.customer_order_id
                WHERE order_products.customer_order_id = ?
                  AND order_products.business_id = ?";
        $resp = $this->db->query($sql, array($order_id,$business_id));
        $orderproducts = $resp->result();
        $staff_id_for_dispatch=0;
        $staff_name_for_dispatch='';
        //insert product sales tax
        foreach($orderproducts  as $row){
            $data=array(
                'invoice_id'=>$invoiceid,
                'business_id'=>$this->session->userdata('businessid'),
                'invoice_tax_name'=> 'Sales Tax',
                'invoice_tax'=>$row->product_sale_tax_amount
            );
            $this->db->insert('invoice_taxes', $data);
        }
        // insert invoice taxes
        if(isset($taxes)){
            foreach($taxes as $tax){
                $data=array(
                    'invoice_id'=>$invoiceid,
                    'business_id'=>$this->session->userdata('businessid'),
                    'invoice_tax_name'=>$tax['taxname'],
                    'invoice_tax'=>$tax['tax']
                );
                $this->db->insert('invoice_taxes', $data);
            }
        }
        foreach($orderproducts as $row){
            $staff_id_for_dispatch = $row->staff_id;
            $staff_name_for_dispatch = $row->staff_name;
            if($row->product_type =="Physical"){
                $discount_price_per_qty = $row->product_discount_amount/ $row->qty;
                $row->product_discount_amount;
                foreach($selected_batch_data as $item){
                    $product_type =  $item['product_type'];
                     if($product_type == "Physical"){
                        $product_name = $item['product_name'];
                        $productid = $item['productid'];
                        $batch_id = $item['batch_id'];
                        $batch_number =  $item['batch_number'];
                        $store_id =  $item['store_id'];
                        $total_price = $item['total_price'];
                        if($productid == $row->product_id){
                            $product_actual_price = $row->price;
                            $qty =  $item['qty'];
                            $total_discount_amount = $discount_price_per_qty * $qty;
                            $price_after_qty_and_discount = ($product_actual_price*$qty)-$total_discount_amount;
                            $tax_amount = ($price_after_qty_and_discount * $row->product_sales_tax) / 100;
                            $totalPrice = $price_after_qty_and_discount + $tax_amount;
                            $cos_g_amount_for_invoice =  $row->purchase_price*$qty;
                            $products= array(
                                'invoice_id'=>$invoiceid,
                                'business_id'=>$business_id,
                                'brand_name'=>$row->business_brand_name,
                                'product_name'=>$row->product,
                                'staff_name'=>$row->staff_name,
                                'staff_id'=>$row->staff_id,
                                'invoice_qty'=>$qty,
                                'price'=>$row->price,
                                'service_addition'=>0,
                                'discount'=> $total_discount_amount,
                                'discounted_price'=>$price_after_qty_and_discount,
                                'invoice_discount'=>0,
                                'final_price'=>$totalPrice,
                                'taxes'=>$tax_amount,
                                'paid'=>$totalPrice,
                                'product_id'=>$row->product_id,
                                'category'=>$row->category,
                                'batch' =>$batch_number,
                                'batch_id'=>$batch_id,
                                'commission'=>0 ,
                                'cog_amount'=>$cos_g_amount_for_invoice
                            );
                            $this->db->insert('invoice_products', $products);
                            $invoice_detail_id=$this->db->insert_id();
                        }
                    }
                }
            }elseif($row->product_type =="Compiled Kit"){
                     $products= array(
                        'invoice_id'=>$invoiceid,
                        'business_id'=>$business_id,
                        'brand_name'=>$row->business_brand_name,
                        'product_name'=>$row->product,
                        'staff_name'=>$row->staff_name,
                        'staff_id'=>$row->staff_id,
                        'invoice_qty'=>$row->qty,
                        'price'=>$row->price,
                        'service_addition'=>0,
                        'discount'=>$row->product_discount_amount,
                        'discounted_price'=>($row->price*$row->qty)- $row->product_discount_amount,
                        'invoice_discount'=>0,
                        'final_price'=>$row->product_final_price,
                        'taxes'=>$row->product_sale_tax_amount,
                        'paid'=>$row->product_final_price,
                        'product_id'=>$row->product_id,
                        'category'=>$row->category,
                        'batch' => 0,
                        'batch_id'=>0,
                        'commission'=>0
                    );
                $this->db->insert('invoice_products', $products);
                $invoice_detail_id=$this->db->insert_id();
            }
        }
        $sql = "UPDATE `customer_orders` SET `order_status`='invoiced' WHERE id_customer_order = ?";
        $this->db->query($sql, array($order_id));
        ///create retail sale voucher start
        $debit_accounts=[];
        $credit_accounts=[];
        $sql="SELECT account_head_id, transaction_type, entity_name, description FROM account_event_mapping
        where account_event_id = 1 and business_id=".$business_id.";";
        $query=$this->db->query($sql);
        $account_heads = $query->result_array();
        //var_dump ($account_heads); exit();
        foreach($account_heads as $ah){
            if($ah['transaction_type']=='debit'){
                array_push($debit_accounts,$ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
            } else {
                array_push($credit_accounts, $ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
            }
        }
        $bank_name='';
        //if(null!==$this->input->post('bank_accounts')){$bank_name=$this->input->post('bank_accounts');}
        $data = array(
            'business_id' => $this->session->userdata('businessid'),
            'description' => 'Retail Sale Voucher against invoice ' . $invoiceid . ' on '. date('d-m-Y').', for '.$customername.' customer ID : '. $customerid,
            'voucher_date' => date('Y-m-d H:i:s'),
            'voucher_amount' => $totalpayable,
            'voucher_status' => 'Active',
            'created_by' => $this->session->userdata('username'),
            'cost_center'=> '1',
            'cost_center_name'=> 'Front Desk',
            'business_partner'=> 1,
            'business_partner_id'=>$customerid,
            'business_partner_name'=>$customername,
            'voucher_type'=>2,
            'payment_mode'=>$paymentmode,
            'bank_name'=>$bank_name,
            'invoice_id'=>$invoiceid,
            'auto_voucher'=>'Yes',
            'sale_type'=>'sale'
        );
        $this->db->insert('account_vouchers', $data);
        $account_voucherid =  $this->db->insert_id();
        //enter debit entries
        foreach($debit_accounts as $debit_account){
            $debitamount=0;
            $debit = explode("|", $debit_account);
            //check entity
            if($debit[2]=="paid_cash" && $cashpaid > 0){$debitamount=  $cashpaid;}
            if($debit[2]=="paid_card" && $cardpaid > 0){$debitamount= $cardpaid;}
            if($debit[2]=="paid_check" && $checkpaid > 0){$debitamount=  $checkpaid;}

            if($debit[2]=="balance"){$debitamount= $balance;}
            if($debit[2]=="sale_discount_retail"){$debitamount=  $discount;}
            if($debit[2]=="retained_amount_used"){$debitamount= $retained_amount_used;}

            // if($debit[2]=="advance_adjusted"){
            //     if($retained_amount_used==0 && $advance_amount > 0){
            //         $debitamount= $advance_amount;
            //     } elseif($retained_amount_used>0 && $advance_amount > 0) {
            //         $debitamount= $advance_amount-$retained_amount_used;
            //     }
            // }

            // if($debit[2]=="rounded_adjustment"){
            //     if($roundedadjustment < 0){

            //         $debitamount=$roundedadjustment*-1;
            //     }

            // }
            // if(defined('LOYALTY_VOUCHER')){
            //     if(LOYALTY_VOUCHER==TRUE){
            //         if($debit[2]=="loyalty_amount"){
            //             if($loyaltyused>0){ //if discount is actually loyalty points
            //                 $debitamount= 0;

            //                 //see if we need to bring the loyalty points in from HO
            //                 $my_business = $this->check_if_ho();
            //                 //bring the points from ho
            //                 if($my_business != $this->session->userdata('businessid')){
            //                     $this->bring_in_ho_points($my_business, $loyaltyused, $loyaltyearned, $customerid, $customername, $invoiceid);
            //                 }

            //                 $this->create_loyalty_used_voucher($this->session->userdata('businessid'),$loyaltyused, $loyaltyearned, $customerid, $customername, $invoiceid);
            //                 $debitamount= 0; // make sure
            //             }
            //         }
            //     }
            // }
            $data_detail=array(
                'account_voucher_id' => $account_voucherid,
                'account_head_id' => $debit[0],
                'instrument_number' => $instrumentnumber,
                'debit' => round($debitamount,2),
                'credit' => 0
            );
            //insert debit detail
            if($debitamount>0){
                $this->db->insert('account_voucher_detail', $data_detail);
            }
        }
        //enter credit entries
        foreach($credit_accounts as $credit_account){
            $creditamount=0;
            $credit = explode("|", $credit_account);
            //check entity
            if($credit[2]=="grosstotal_retail"){$creditamount= $org_subtotal + $total_service_additions;}
            if($credit[2]=="sales_tax"){$creditamount= $taxtotal;}
            if($credit[2]=="cc_fee"){$creditamount= $cc_charge;}
            if($credit[2]=="retained_amount"){$creditamount= 0;}
            // if($credit[2]=="cc_tip"){$creditamount= $cctip;}
            //if($credit[2]=="additional_charges"){$creditamount= $totaladdition;}

            if($totalpaidnow > $totalpayable){
                if($credit[2]=="return_cash"){$creditamount=  $returnamount;}
            }
            // if($credit[2]=="rounded_adjustment"){
            //     if($roundedadjustment > 0){

            //         $creditamount=$roundedadjustment;
            //     }
            // }
            $data_detail=array(
                'account_voucher_id' => $account_voucherid,
                'account_head_id' => $credit[0],
                'instrument_number' => $instrumentnumber,
                'debit' => 0,
                'credit' => round($creditamount,2)
            );
            //insert credit detail
            if($creditamount>0){
                $this->db->insert('account_voucher_detail', $data_detail);
            }
        }
        ///create retail sale voucher End

        // ======================> Creating Cost Of good Voucher Start <=====================================

        foreach ($selected_batch_data as $item) {

            $product_name = $item['product_name'];
            $qty =  $item['qty'];
            $productid = $item['productid'];
            $batch_id = $item['batch_id'];
            $batch_number =  $item['batch_number'];
            $store_id =  $item['store_id'];
            $total_price = $item['total_price'];
            $product_cog[$batch_id] = $total_price;
            $batch_amount = $total_price;
            $debit_accounts=[];
            $credit_accounts=[];
            $sql="SELECT account_head_id, transaction_type, entity_name, description FROM account_event_mapping
               where account_event_id = 23 and business_id=".$business_id.";";
            $query=$this->db->query($sql);
            $account_heads = $query->result_array();
            //var_dump ($account_heads); exit();
            foreach($account_heads as $ah){
                if($ah['transaction_type']=='debit'){
                    array_push($debit_accounts,$ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                } else {
                    array_push($credit_accounts, $ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                }
            }
            $bank_name='';
            $batch_amount = round($batch_amount,2);
            //if(null!==$this->input->post('bank_accounts')){$bank_name=$this->input->post('bank_accounts');}
            $data = array(
                'business_id' => $this->session->userdata('businessid'),
                'description' => 'Cost of Goods Solds Voucher against reference voucher ID '. $account_voucherid . ' invoice ' . $invoiceid . ' on '. date('d-m-Y').', for '.$customername.' customer ID : '. $customerid,
                'voucher_date' => date('Y-m-d H:i:s'),
                'voucher_amount' => $batch_amount,
                'voucher_status' => 'Active',
                'created_by' => $this->session->userdata('username'),
                'cost_center'=> '1',
                'cost_center_name'=> 'Front Desk',
                'business_partner'=> 1,
                'business_partner_id'=>$customerid,
                'business_partner_name'=>$customername,
                'voucher_type'=>3,
                'payment_mode'=>$paymentmode,
                'bank_name'=>$bank_name,
                'invoice_id'=>$invoiceid,
                'auto_voucher'=>'Yes',
                //'sale_type'=>'sale'
            );
            $this->db->insert('account_vouchers', $data);
            $cogs_voucherid =  $this->db->insert_id();
            //enter debit entries
            $total_cog = 0;
            foreach($debit_accounts as $debit_account){
                $debitamount=0;
                $debit = explode("|", $debit_account);
                //check entity
                if($debit[2]=="cogs"){
                    //    foreach($tableData as $row){
                    $debitamount= $product_cog[$batch_id];
                    $total_cog = $total_cog + $product_cog[$batch_id];
                    // $debitamount= $debitamount * $product_cog[$row['batch_id']];
                    $data_detail=array(
                        'account_voucher_id' => $cogs_voucherid,
                        'account_head_id' => $debit[0],
                        'instrument_number' => $instrumentnumber,
                        'detail_remarks' =>$product_name,
                        'debit' => round($debitamount,2),
                        'credit' => 0
                    );
                    //insert debit detail
                    if($debitamount>0){
                        $this->db->insert('account_voucher_detail', $data_detail);
                    }
                }
                //    }
            }
            //enter credit entries
            foreach($credit_accounts as $credit_account){
                $creditamount=0;
                $credit = explode("|", $credit_account);
                //check entity
                //if($credit[2]=="inventory"){$creditamount= $batch_amount;}
                if($credit[2]=="inventory"){$creditamount= $total_cog;}
                $data_detail=array(
                    'account_voucher_id' => $cogs_voucherid,
                    'account_head_id' => $credit[0],
                    'instrument_number' => $instrumentnumber,
                    'debit' => 0,
                    'credit' => round($creditamount,2)
                );
                //insert credit detail
                if($creditamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }

            // ======================>  Add dispatch intery  <==========================================

            $product_name = $item['product_name'];
            $qty =  $item['qty'];
            $productid = $item['productid'];
            $batch_id = $item['batch_id'];
            $batch_number =  $item['batch_number'];
            $store_id =  $item['store_id'];
            $total_price = $item['total_price'];
            $unit_type  = $item['unit_type'];
            $measure_unit = $item['measure_unit'];

            $product_type = $item['product_type'];
            if($product_type == "Compiled Kit"){
                $data = array(
                    'product_id'=> $productid,
                    'dispatch_to_staff' =>     $staff_id_for_dispatch,
                    'dispatch_qty' => $qty,
                    'dispatch_measure' => $this->input->post('dispatch_measure'),
                    'unit_type' => $unit_type,
                    'measure_unit' =>$measure_unit,
                    'dispatch_date' => date('Y-m-d H:i:s'),
                    'batch' =>$batch_number,
                    'batch_id' =>  $batch_id,
                    'business_id' => $business_id,
                    'created_by' => $this->session->userdata('username'),
                    'dispatch_comment'=> "Cost Of Good for kit",
                    'order_id'=> $order_id,
                    // 'visit_id'=> $this->input->post('visit_id'),
                    // 'visit_service_id'=> $this->input->post('visit_service_id'),
                    // 'request_id'=>$request_id
                );
                $this->db->insert('dispatch_notes', $data);

            }
        }
        // ======================> Creating Cost Of good Voucher End <=====================================
        $sql = "SELECT 
                    `invoice`.`customer_name`, 
                    `invoice`.`visit_id`, 
                    `invoice`.`sub_total`, 
                    `invoice`.`discount`, 
                    `invoice`.`tax_total`, 
                    `invoice`.`net_amount`, 
                    `invoice`.`paid_amount`, 
                    `invoice`.`paid_cash`, 
                    `invoice`.`paid_card`, 
                    `invoice`.`payment_mode`, 
                    `invoice`.`returnamount`, 
                    `business`.`business_address`,
                    `business`.`business_logo`,
                    `business`.`business_phone1`,
                    `invoice`.`invoice_date`,
                    `invoice`.`id_invoice`,
                      0 as warning_msg
                FROM 
                    `invoice`
                INNER JOIN 
                    `business` ON `business`.`id_business` = `invoice`.`business_id`
                WHERE  
                    `invoice`.`id_invoice` = ? AND
                    `invoice`.`business_id` = ?";
        $resp = $this->db->query($sql, array($invoiceid , $business_id));
        $order_data = $resp->row();
        $sql = "SELECT invoice_products.* FROM `invoice` 
                INNER join invoice_products on `invoice`.`id_invoice`= invoice_products.invoice_id where invoice.id_invoice = ? And invoice.business_id=?;";
        $resp = $this->db->query($sql, array($invoiceid , $business_id));
        $products_data = $resp->result();
        $order_data->products = $products_data;
        return $order_data;
    }
    public function cancelOrder(){
        $business_id = $this->input->post('businessid');
        $order_id = $this->input->post('order_id');
        $sql = "update `customer_orders`  set order_status ='Cancelled' where id_customer_order=? and business_id=?";
        $this->db->query($sql, array($order_id ,$business_id));
        return   $order_id ;
    }
    public function deleteOrderRow(){
        $id_order_products = $this->input->post('id_order_products');
        $order_id = $this->input->post('order_id');

        $sql = "DELETE FROM order_products WHERE id_order_products =? AND customer_order_id =?";
        $this->db->query($sql, array($id_order_products,$order_id));
        return   $order_id ;
    }

} 