<?php

class Order_model extends CI_Model {

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

    function get_orders() {
        $today = date('Y-m-d');
        $this->db->select('*');
        $this->db->join('customers', 'customers.id_customers = customer_orders.customer_id');
       // $this->db->where('customer_visit_date >', $today);
        $this->db->where('order_status !=', 'invoiced');
        $this->db->where('customer_orders.business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('customer_orders');
       
        return $query->result_array();
    }
    
    function get_open_orders($status=null, $start= null, $end=null){
        $this->db->select('*, date_format(customer_order_date,"%d-%m-%Y %H:%i") as "mDate"');
        $this->db->join('customers', 'customers.id_customers = customer_orders.customer_id');
        $this->db->join('order_products', 'customer_orders.id_customer_order = order_products.customer_order_id');
        $this->db->join('business_products', 'order_products.product_id = business_products.id_business_products');
        $this->db->join('business_brands', 'business_products.brand_id = business_brands.id_business_brands');

        if($status != null){            
            $this->db->where('order_status', $status);
        } else { //get open orders
            $this->db->where('order_status =', 'open');
        }

        if($start != null && $end != null){
            $this->db->where('date(customer_order_date) >=', $start);
            $this->db->where('date(customer_order_date) <=', $end);
        }
       
        
        $this->db->where('customer_orders.business_id', $this->session->userdata('businessid'));
        $this->db->group_by('customer_orders.id_customer_order');
        if($status !== null){            
            $this->db->limit(100);
        }


        $query = $this->db->get('customer_orders');
        return $query->result_array();
    }

    
    function add_order(){
        // Unescape the string values in the JSON array
        $tableData = stripcslashes($_POST['orderdata']);

        // Decode the JSON array
        $tableData = json_decode($tableData,TRUE);

        // now $tableData can be accessed like a PHP array
        // echo $tableData[0]['servicename'];
        
        //add new customer_visit
         $order = array(
            'business_id' => $this->session->userdata('businessid'),
            'customer_id' => $tableData[0]['customerid'],
            'order_extra'=> $this->input->post('order_extra')
        );
        $this->db->insert('customer_orders', $order);
        $order_id = $this->db->insert_id();
        
        $data = [];
        
        foreach($tableData as $row){
           
            $data = array(
                'business_id' => $this->session->userdata('businessid'),
                'customer_order_id' => $order_id,
                'product_id' => $row['productid'],
                'product_name' => $row['productname'],
                'category' => $row['category'],
                'staff_id' => $row['staffid'],
                'staff_name' => $row['staff'],
                'qty' => $row['qty'],
                'stockfrom' => $row['stockfrom'],
                'batch' => $row['batch'],
                'batch_id' => $row['batch_id']
            );
            
            $this->db->insert('order_products', $data);
            
           
        }
        return $order_id;
       
    }
    
    function check_order_status($order_id){
        $this->db->select('*');
        $this->db->where('id_customer_order', $order_id);
       // $this->db->where('business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('customer_orders');
        return $query->row();
    }
    
    function update_order(){
       //echo $this->input->post('orderstatus', TRUE); exit();
        $customerid="";
        
         // Unescape the string values in the JSON array
        $tableData = stripcslashes($_POST['orderdata']);

        // Decode the JSON array
        $tableData = json_decode($tableData,TRUE);
        
        
        $stopproduct='';
        if($this->input->post('orderstatus', TRUE)!=='cancelled'){
            foreach($tableData as $row){
                $qty=0;
                $batches = $this->product_model->get_all_batches($row['productid'], $this->session->userdata('businessid'));
                foreach($batches as $batch){
                    if($batch['id_batch']==$row['batch_id']){
                        $qty=$batch['total_stock'];
                        if($qty < $row['qty']){
                            $stopproduct=$row['productname'];
                            return('error|Stock Qty is lower then the Ordered Qty for '.$stopproduct);
                        }
                    }
                }
            }
        }
        
        
        //update customer_order status
        $status= '';
        $this->db->select('*');
        $this->db->where('id_customer_order', $this->input->post('orderid', TRUE));
        $query = $this->db->get('customer_orders');
        $order = $query->row();
        
        $customerid = $tableData[0]['customerid'];
        if($customerid !==""){
            //update customer_order_products
            $this->db->where('customer_order_id', $this->input->post('orderid', TRUE));
            $this->db->delete('order_products');

            foreach($tableData as $row){
                $data = array(
                    'business_id' => $this->session->userdata('businessid'),
                    'customer_order_id' => $this->input->post('orderid', TRUE),
                    'product_id' => $row['productid'],
                    'product_name' => $row['productname'],
                    'category' => $row['category'],
                    'staff_id' => $row['staffid'],
                    'staff_name' => $row['staff'],
                    'qty' => $row['qty'],
                    'stockfrom' => $row['stockfrom'],
                    'batch'=> $row['batch'],
                    'batch_id'=> $row['batch_id']
                );

                $this->db->insert('order_products', $data);

                if($this->input->post('orderstatus', TRUE)=='cancelled') {
                     //delete all  adjustment notes of the order
                    $this->db->where('adjustment_order_id', $this->input->post('orderid', TRUE));
                    $this->db->delete('adjustment_notes');
                } else if ($order->order_status == 'open' && $this->input->post('orderstatus', TRUE)!=='open' ){
                    //create adjustment note for removing from inventory
                    $adjdata=array(                   
                        'batch_id' => $row['batch_id'],
                        'product_id' => $row['productid'],
                        'adjustment_qty' => $row['qty']*-1,
                        'adjustment_date' => date('Y-m-d H:i:s'),
                        'adjustment_remarks' => 'Shipped against order '.$this->input->post('orderid', TRUE),
                        'unit_price' => $row['price'] ,
                        'created_by' => 'System', 
                        'created_on' =>  date('Y-m-d H:i:s'),
                        'adjustment_order_id' =>  $this->input->post('orderid', TRUE)
                    );
                     $this->db->insert('adjustment_notes', $adjdata);

                } else if ($order->order_status !== 'open' && $this->input->post('orderstatus', TRUE)=='open'){
                    //delete all  adjustment notes of the order
                    $this->db->where('adjustment_order_id', $this->input->post('orderid', TRUE));
                    $this->db->delete('adjustment_notes');
                } 
            }
            
//            $this->db->where('id_customer_order', $this->input->post('orderid', TRUE));
//            $this->db->update('customer_orders', array('customer_id' => $customerid));
        
            if(null !== $this->input->post('orderstatus')){
                $this->db->where('id_customer_order', $this->input->post('orderid', TRUE));
                $this->db->set('order_status', $this->input->post('orderstatus', TRUE));
                $this->db->update('customer_orders');
            }
        }
        
        
        
        return "success|".$this->input->post('orderid');
    }
    
    function getopenorderbyid($orderid){
        
        $this->db->select('*');
        $this->db->join('customers', 'customers.id_customers = customer_orders.customer_id');
        $this->db->join('order_products', 'order_products.customer_order_id = customer_orders.id_customer_order');
        $this->db->join('business_products', 'business_products.id_business_products = order_products.product_id');
        $this->db->where('customer_order_id =', $orderid);
        $this->db->where('order_status !=', 'invoiced');
        if($this->session->userdata('common_products')=='No'){
            $this->db->where('customer_orders.business_id', $this->session->userdata('businessid'));
        }
        $query = $this->db->get('customer_orders');
      // echo $query; exit();
        
        return $query->result_array();
    }
    
    function getinvoicedorderbyid($orderid){
        
        $this->db->select('*');
        $this->db->join('customers', 'customers.id_customers = customer_orders.customer_id');
        $this->db->join('order_products', 'order_products.customer_order_id = customer_orders.id_customer_order');
        $this->db->where('customer_order_id =', $orderid);
        $this->db->where('order_status =', 'invoiced');
        if($this->session->userdata('common_products')=='No'){
        $this->db->where('customer_orders.business_id', $this->session->userdata('businessid'));
        }
        $query = $this->db->get('customer_orders');
       
        return $query->result_array();
    }
    
    function getorderbyid($orderid){
        
        $this->db->select('*');
        $this->db->join('customers', 'customers.id_customers = customer_orders.customer_id');
        $this->db->join('order_products', 'order_products.customer_order_id = customer_orders.id_customer_order');
        $this->db->join('business_products', 'business_products.id_business_products = order_products.product_id');
        $this->db->join('business_brands', 'business_brands.id_business_brands = business_products.brand_id');
        $this->db->where('order_products.customer_order_id =', $orderid);
        if($this->session->userdata('common_products')=='No'){
            $this->db->where('customer_orders.business_id', $this->session->userdata('businessid'));
        }
        $query = $this->db->get('customer_orders');
       
        //echo $query; exit();
        return $query->result_array();
    }
    
    function getorderbycid($customer_id){
        $this->db->select('*');
        $this->db->where('customer_id =', $customer_id);
        $this->db->where('order_status !=', 'invoiced');
        if($this->session->userdata('common_products')=='No'){
        $this->db->where('customer_orders.business_id', $this->session->userdata('businessid'));
        }
        $query = $this->db->get('customer_orders');
       
        return $query->result_array();
    }
    
    function getorderproducts($ids, $orderid){
 
        $this->db->select('*');
        $this->db->join('business_brands', 'business_brands.id_business_brands = business_products.brand_id');
        $this->db->join('order_products', 'order_products.product_id = business_products.id_business_products');
        $this->db->where_in('id_business_products', $ids);
        $this->db->where('order_products.customer_order_id', $orderid);
        if($this->session->userdata('common_products')=='No'){
            $this->db->where('business_products.business_id', $this->session->userdata('businessid'));
        }
        $query = $this->db->get('business_products');
        
        return $query->result_array();
    }
    
    function getlast4orders($customerid){
        $this->db->select('*, date_format(customer_order_date,"%d-%m-%Y") as order_date');
        $this->db->join('order_products', 'order_products.customer_order_id = customer_orders.id_customer_order');
        if($this->session->userdata('common_products')=='No'){
        $this->db->where('customer_orders.business_id', $this->session->userdata('businessid'));
        }
        $this->db->where('order_status =', 'invoiced');
        $this->db->where('customer_orders.customer_id', $customerid);
        $this->db->order_by('customer_orders.id_customer_order DESC, product_id ASC');
        $query = $this->db->get('customer_orders');
                
        return $query->result_array();
    }


    function get_order_by_id($id){
        $this->db->select('*');
        $this->db->where('id_customer_order', $id);
        $query = $this->db->get('customer_orders');
        return $query->row();
    }

    function get_product_orders($status, $start_date, $end_date){

      $sql = "SELECT customer_orders.*, group_concat(Concat(business_brands.business_brand_name, ' ', business_products.product, ' x ', qty) SEPARATOR  '<br> ') as product_name,         
            customer_orders.order_status, sum(order_products.qty) as qty, sum(product_unit_price) as price,            
            date_format(customer_orders.customer_order_date, '%d-%m-%Y') as mDate, 
            customers.customer_name, customers.customer_cell, 
                invoice.balance as balance, id_invoice, invoice.visit_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
                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                
                LEFT JOIN (select id_invoice, visit_id, sum(invoice.balance) as balance
                    from invoice 
                    where invoice.invoice_type = 'sale'
                    and invoice.business_id =  ".$this->session->userdata('businessid')." 
                    and invoice.invoice_status = 'valid'
                    and invoice.is_recovery = 'Yes'
                    group by visit_id
                    ) as invoice on invoice.visit_id =  customer_orders.id_customer_order
                where customer_orders.business_id = ".$this->session->userdata('businessid')."
                and date(customer_orders.customer_order_date) >= '".$start_date."'
                and date(customer_orders.customer_order_date) <= '".$end_date."'
                group by customer_orders.id_customer_order
                order by id_customer_order desc";

        $query = $this->db->query($sql);
        // /echo $sql;
        return $query->result_array();
    }
}
