<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Dispatch_controller extends CI_Controller {

    public function __construct() {

        parent::__construct();

        // Your own constructor code

        $this->load->model('dispatch_model');
        $this->load->model('accounting_model');
        $this->load->model('product_model');
        $this->load->model('visits_model');
        $this->load->model('store_model');
        

        if ($this->session->userdata('role') == '') {

            redirect('logout');
        }
    }

    public function dispatch_list_view() {
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            $data['nav'] = 'procurement';
            $data['subnav'] = 'dispatch';

            //echo $this->input->post('showoutofstock');

            //exit();
            $data['showoutofstock']="No";
            if(null!==$this->input->post('showoutofstock') && $this->input->post('showoutofstock')=="on"){
                $data['showoutofstock']="Yes";
            }

            //$data['dispatch_list'] = $this->dispatch_model->get_dispatch_list();
            $data['staff'] = $this->dispatch_model->get_staff();
            //$data['product'] = $this->dispatch_model->get_product();
            $data['todayvisits']=$this->visits_model->get_valid_visits();


            $this->load->view('includes/header', $data);
            $this->load->view('setting/dispatch_view_new');
            $this->load->view('includes/footer');
        }
    }
    
    
    public function add_dispatch_request($visitid){
        
        $this->db->select('*');
        $this->db->where('customer_visit_id', $visitid);
        $this->db->where('dispatch_request_status', 'Active');
        $query = $this->db->get('dispatch_request');
        if($query->num_rows > 0){
            echo 'info|Request Already Entered';
        }else{
            $this->dispatch_model->add_dispatch_request($visitid);
            echo 'success|New Request Entered!';
        }
        //redirect(dispatch_request_view);
    }
    
    public function update_request(){
        
        $requestid = $this->input->post('id_dispatch_request');
        $newproduct = $this->input->post('newproduct');
        
        $np = explode(",",$newproduct);
        
        $this->db->where('id_dispatch_request', $requestid);
        $this->db->set('product_id', $np[0]);
        $this->db->set('product_name', $np[2]);
        $a = $this->db->update("dispatch_request");
        
        echo $a;
        
    }

    public function add_request_product()  {
        $requestid = $this->input->post('id_dispatch_request');
        $newproduct = $this->input->post('addproduct');        
        $np = explode(",",$newproduct);
        $product_id = $np[0];
        $product_name = $np[2];
        $measure_unit = $np[6];

        $customer_id= $this->input->post('id_customer');
        $id_service= $this->input->post('id_service');
        $id_visit = $this->input->post('id_visit');
        $id_visit_service = $this->input->post('id_visit_service');
        $id_visit_service_staff = $this->input->post('id_visit_service_staff');
        $dispatchqty= $this->input->post('addproductqty');

        $this->db->set('dispatch_request_date', date('Y-m-d H:i-s'));
        $this->db->set('customer_visit_id', $this->input->post('id_visit'));
        $this->db->set('customer_id', $this->input->post('id_customer'));
        $this->db->set('service_id', $this->input->post('id_service'));        
        $this->db->set('visit_service_id', $this->input->post('id_visit_service'));
        $this->db->set('visit_service_staff_id', $this->input->post('id_visit_service_staff'));
        $this->db->set('created_by', $this->session->userdata('username'));
        $this->db->set('product_qty', $this->input->post('addproductqty'));
        $this->db->set('product_unit', $np[7]);
        $this->db->set('product_id', $np[0]);
        $this->db->set('product_name', $np[2]);
        $this->db->insert("dispatch_request");
        $a = $this->db->insert_id();
        echo $a;
    }
    
    
    public function dispatch_requests_view() {
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            $data['nav'] = 'procurement';
            $data['subnav'] = 'dispatchrequests';

            //echo $this->input->post('showoutofstock');

            //exit();
            $data['showoutofstock']="No";
            if(null!==$this->input->post('showoutofstock') && $this->input->post('showoutofstock')=="on"){
                $data['showoutofstock']="Yes";
            }

            
            $data['staff'] = $this->dispatch_model->get_staff();            
            $data['dispatch_requests']=$this->dispatch_model->get_active_dispatch_requests();
            $data['stores']= $this->store_model->get_business_stores();
            

            $this->load->view('includes/header', $data);
            $this->load->view('setting/dispatch_requests_view');
            $this->load->view('includes/footer');
        }
    }
    
    public function dispatch_request_view($visit_id) {
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            $data['nav'] = 'procurement';
            $data['subnav'] = 'dispatchrequests';

            //exit();

            $data['staff'] = $this->dispatch_model->get_staff();            
            $data['dispatch_requests']=$this->dispatch_model->get_dispatch_request($visit_id);
            $data['stores']= $this->store_model->get_business_stores();
            

            $this->load->view('includes/header', $data);
            $this->load->view('setting/dispatch_requests_view');
            $this->load->view('includes/footer');
        }
    }

    
    public function getproducts() {

        $showoutofstock="No";
        $showinhouse="Yes";
        $showprofessional="Yes";
        
        if(null!==$this->input->get('showoutofstock')){
            $showoutofstock=$this->input->get('showoutofstock');
        }
               
        if($showoutofstock!=="Yes" && $this->session->userdata('role')!='Super User' && $this->session->userdata('role')!='Admin'){
            $data = $this->product_model->get_searched_products($showinhouse, $showprofessional,"",$this->session->userdata('businessid')); // to hide 0 qty products
        } else {
            $data = $this->product_model->get_searched_products($showinhouse, $showprofessional, "dispatch", $this->session->userdata('businessid'));
        }
        
        echo(json_encode($data));
    }
    
    public function searchproduct(){
        $phrase=  strtoupper( $this->input->get('productname'));
        $match = explode(' ',$phrase);
        
        $phrase =  str_replace(' ','%',$phrase);
        
        $business = $this->input->get('businessid');
        if(!null == $business && $business!==""){
            $business_id=$business;
        }
        $sql = "select *, id_business_products as id, product as text, ifnull(unit_type,'') unit_type, ifnull(measure_unit,'') measure_unit, ifnull(qty_per_unit,'') qty_per_unit,
                IFNULL(business_products.category, '') as mcategory from business_products
                JOIN `business_brands` ON `business_brands`.`id_business_brands` = `business_products`.`brand_id`
                
                where business_product_active = 'Yes' and business_brand_active='Yes' ";
        if($this->session->userdata('common_products')=='No'){
            $sql.=" AND `business_products`.`business_id` = ".$this->session->userdata('businessid')." ";
        } else {
            $q = $this->db->query('select id_business from business where common_products="Yes"');
            $b = $q->result_array();
            $businessids='';
            $x=0;
            foreach ($b as $bid){
                if($x>0){
                    $businessids .= ",".$bid['id_business'];
                }else{
                    $businessids .= $bid['id_business'];
                }
                $x++;
            }
            
            $sql.=" AND `business_products`.`business_id` in (".$businessids.") ";
        }
        
        $sql .=" And (
                upper(concat(business_brand_name,' ', product,' ', IFNULL(business_products.category, '') )) LIKE '%".$phrase."%' 
                OR  upper(concat(product,' ', business_brand_name,' ', IFNULL(business_products.category, '') )) LIKE '%".$phrase."%' 
                OR  upper(concat(product,' ', IFNULL(business_products.category, '') ,' ', business_brand_name)) LIKE '%".$phrase."%' 
                OR  upper(concat(IFNULL(business_products.category, '') , ' ', product, ' ', business_brand_name)) LIKE '%".$phrase."%' 
                OR  upper(concat(business_brand_name, ' ', IFNULL(business_products.category, '') , ' ', product)) LIKE '%".$phrase."%' 
                OR  IFNULL(business_products.barcode_products, '') like '%".$phrase."%'
                OR  IFNULL(business_products.sku, '') like '%".$phrase."%'    
                OR  upper(id_business_products) LIKE '%".$phrase."%'    
                ) 
                ORDER BY `business_products`.`brand_id` ASC, `business_products`.`product` ASC, `business_products`.`category` ASC 
                ";
        //echo $sql; exit();
        $query = $this->db->query($sql);
        $data = $query->result_array();
        
        echo(json_encode($data));
        
    }
    
    public function getproductbatches(){
        
        $product_id=$this->input->post('product_id');
        if($this->input->post('store_id')!=''){
            $store_id = $this->input->post('store_id');
        }else{
            $store_id = '';
        }
        

        $data = $this->product_model->get_all_batches($product_id, $this->session->userdata('businessid') , $store_id);
        
        echo(json_encode($data));
    }
    
    public function select_batch_add_dispatch(){
        
        $request_id= $this->input->post('request_id');
        $product_id= $this->input->post('product_id');
        $dispatch_to_staff= $this->input->post('dispatch_to_staff');
        $staff_name= $this->input->post('staff_name');
        
        if($this->input->post('dispatch_unit')!=='' && (float)$this->input->post('dispatch_unit') > 0)  {
            $dispatch_unit = (float)$this->input->post('dispatch_unit');
        } else {
            $dispatch_unit = round((float)$this->input->post('dispatch_measure') / (float)$this->input->post('qty_per_unit'), 6);
        }
       
        $dispatch_measure= $this->input->post('dispatch_measure');
        $unit_type= $this->input->post('unit_type');
        $measure_unit= $this->input->post('measure_unit');
        $dispatch_date= date('Y-m-d H:i:s');
        $batch= $this->input->post('batch');
        $batch_id= $this->input->post('batch_id');
        $qty_per_unit= $this->input->post('qty_per_unit');
        $visit_id= $this->input->post('visit_id');
        $visit_service_id= $this->input->post('visit_service_id');
       
        //get the batches here
        $this->db->select('*');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('business_stores');
        $stores = $query->result_array();
        //$batches=[];
        $remaining_qty = $dispatch_unit;
        $totaldispatched=0;
        
        foreach($stores as $store){
            $data =  $this->product_model->get_all_batches($product_id, '', $store['id_business_stores'], "false");     
           
            foreach($data as $d){
                ///check the inventory in batch before proceeding
                $qty=0;
                $batch = $this->product_model->get_a_batch($d['id_batch'], $dispatch_date, $this->session->userdata('businessid'));
                
                if($batch){
                    $qty=$batch->total_stock;    
                                              
                    if($remaining_qty > 0 && $qty > 0){                //still need to dispatch and batch qty is available         
                        if($qty < $dispatch_unit){                            
                            $dispatch_now = $qty; 
                            $remaining_qty = $dispatch_unit - $qty;                           
                            
                        }elseif ($qty >= $dispatch_unit){
                            $dispatch_now = $dispatch_unit;
                            $remaining_qty = 0;
                            
                        }
                        
                        $dispatch_measure = round($dispatch_now * $this->input->post('qty_per_unit'));
                        //create dispatch note
                        $data = array(
                            'product_id'=> $this->input->post('product_id'),
                            'dispatch_to_staff' => $this->input->post('dispatch_to_staff'),
                            'dispatch_qty' => $dispatch_now,
                            'dispatch_measure' => $dispatch_measure,
                            'unit_type' => $this->input->post('unit_type'),
                            'measure_unit' => $this->input->post('measure_unit'),
                            'dispatch_date' => $dispatch_date,
                            'batch' => $batch->batch_number,
                            'batch_id' => $batch->id_batch,
                            'business_id' => $this->session->userdata('businessid'),
                            'created_by' => $this->session->userdata('username'),
                            'dispatch_comment'=> $this->input->post('dispatch_comment'),
                            'visit_id'=> $this->input->post('visit_id'),
                            'visit_service_id'=> $this->input->post('visit_service_id'),
                            'request_id'=>$request_id,
                            'dispatch_to_staff'=>$dispatch_to_staff
                            
                        );
                        $response = $this->dispatch_model->add_dispatch($data, null, $staff_name);
                        $remaining_qty = $dispatch_unit-$dispatch_now;
                       $totaldispatched = $totaldispatched+$dispatch_now;
                    }                  
                }               
            }
            //print_r ($response);
        }

        if($totaldispatched < $dispatch_unit){
            echo "info|Complete qty is not available, Required ".$dispatch_unit - $totaldispatched;
            exit();
        }elseif($totaldispatched == $dispatch_unit){
            echo "success|".$dispatch_unit;
            exit();
        }elseif($totaldispatched > $dispatch_unit){
            echo "error|Extra qty has been dispatched please check the dispatch notes ".$totaldispatched;
            exit();
        }
    }


    public function add_dispatch() {
        $data = $this->dispatch_model->add_dispatch();
        echo $data;
        exit();
    }

    public function dispatch_measure_amount_cal() {
        $data = $this->dispatch_model->dispatch_measure_amount_cal();
        if ($data !== "") {
            echo (json_encode($data));
            exit();
        }
    }
    
    public function dispatch_unit_amount_cal() {
        $data = $this->dispatch_model->dispatch_unit_amount_cal();
        if ($data !== "") {
            echo (json_encode($data));
            exit();
        }
    }

    public function cancel_dispatch() {
        $data = $this->dispatch_model->cancel_dispatch();
        echo "success|" . $data;
        exit();
    }

    public function check_history(){
        
        $data=$this->dispatch_model->check_history();
       
        echo(json_encode($data));
    }
    
    public function dispatch_note_print($dispatch_id, $visit_id=0){
        
        if($this->session->userdata('role')=='' || $this->session->userdata('role')=='Sh-Users'){
            $this->load->view('login_view');
        } else {
            $data['nav'] = 'procurement';
            $data['subnav'] = 'dispatchrequests';

            //exit();
            $data['dispatch_note']=$this->dispatch_model->get_dispatch_note($dispatch_id, $visit_id);
            
            //print_r($data['dispatch_note']); ;exit();
            
            $this->load->view('includes/header', $data);
            $this->load->view('setting/dispatch_note_print');
            $this->load->view('includes/footer');
        }
        
    }
    
}
