<?php

class Dispatch_model extends CI_Model {

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

    function get_dispatch_list() {

        $this->db->select('*');
        $this->db->join('business_products bp', 'bp.id_business_products =  d.product_id');
        $this->db->join('staff s', 's.id_staff =  d.dispatch_to_staff');
        $this->db->where('d.business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('dispatch_notes d');

        return $query->result_array();
    }

    function get_staff() {

        $where = "(s.business_id=". $this->session->userdata('businessid') ." OR s.staff_shared = 'Yes') ";
        
        $this->db->select('s.id_staff, s.staff_fullname');
        $this->db->where($where);
        $this->db->where('s.staff_active', 'Y');
        $this->db->order_by('s.staff_fullname', 'ASC');
        $query = $this->db->get('staff s');

        return $query->result_array();
    }

    function get_product() {

        $this->db->select('bp.id_business_products, bp.product, bp.unit_type');
        $this->db->where('bp.business_id', $this->session->userdata('businessid'));
        //$this->db->where('bp.inhouse_stock >', 0);
        $this->db->where('bp.qty_per_unit >', 0);
        $this->db->where('bp.business_product_active', 'Yes');
        $this->db->order_by('bp.product', 'ASC');
        $query = $this->db->get('business_products bp');

        return $query->result_array();
    }

    function dispatch_measure_amount_cal() {
        if ($this->input->post('product_id', TRUE)) {
            $measure_amount = $this->input->post('measure_amount');
            $this->db->select('*');
            $this->db->where('id_business_products', $this->input->post('product_id', TRUE));
            $product = $this->db->get('business_products');
            $product = $product->row();
            if (!empty($product)) {
                $inhouse = $product->inhouse_stock;
                $qty_per_unit = $product->qty_per_unit;
                if ($qty_per_unit && $qty_per_unit > 0) {
                    if ($measure_amount) {// <= $qty_per_unit
                        $measure_fraction = $measure_amount / $qty_per_unit;
                        $remain_inhouse = $inhouse - $measure_fraction;
                        $used_unit_amount = $inhouse - $remain_inhouse;
                        return array(
                            'remain_qty' => round($remain_inhouse, 2),
                            'used_qty' => round($used_unit_amount, 2),
                            'inhouse_qty' => $inhouse
                        );
                    }
                }
            }
        }
    }

    function dispatch_unit_amount_cal() {
        if ($this->input->post('product_id', TRUE)) {
            $this->db->select('*');
            $this->db->where('id_business_products', $this->input->post('product_id', TRUE));
            $product = $this->db->get('business_products');
            $product = $product->row();
            return $product;
        }
    }

    function add_dispatch($data=null, $kit=null, $staff_name=null) {
        
        $mDate = date('Y-m-d H:i:s');
        if($this->input->post('dispatch_date')!=''){
            $mDate = $this->input->post('dispatch_date');
        }  
        $batch_id = $this->input->post('batch_id');
        $dispatch_to_staff = $this->input->post('dispatch_to_staff');
        $staff_name = $this->input->post('staff_name');
        $business_partner=3;
        
        if(null==$data){
            $request_id=0;
            if(null != $this->input->post('request_id')){
                $request_id=$this->input->post('request_id');
            }            
            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);
            }
        
        
            //echo $dispatch_unit;
            ///check the inventory in batch before proceeding
            $stopproduct='';
            
            $qty=0;
            $batch = $this->product_model->get_a_batch($this->input->post('batch_id'),$mDate, $this->session->userdata('businessid'));
            
            
            
            if($batch){
                $qty=$batch->total_stock;                
                if($qty < $dispatch_unit || $qty<=0){
                    $stopproduct=$batch->product;
                    return('error|Stock Qty was lower in batch '.$this->input->post('batch').' then the Dispatch Qty on '.$mDate);
                }

            } else {
                
                return('error|Stock Qty was lower in batch '.$this->input->post('batch').' then the Dispatch Qty on '.$mDate);
            }

            
            //exit();
        
            $data = array(
                'product_id'=> $this->input->post('product_id'),
                'dispatch_to_staff' => $this->input->post('dispatch_to_staff'),
                'dispatch_qty' => $dispatch_unit,
                'dispatch_measure' => $this->input->post('dispatch_measure'),
                'unit_type' => $this->input->post('unit_type'),
                'measure_unit' => $this->input->post('measure_unit'),
                'dispatch_date' => $mDate,
                'batch' => $this->input->post('batch'),
                'batch_id' => $this->input->post('batch_id'),
                '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
            );
        } else {
            
            $batch_id = $data['batch_id'];
            $dispatch_unit = $data['dispatch_qty'];
            $business_partner = 5;
            if(null == $staff_name){
                $staff_name = $this->session->userdata['business'];            
            }
            if(null == $data['dispatch_to_staff']){
                $this->db->select("id_staff");
                $this->db->where("staff_active", 'Y');
                $this->db->like("staff_designation", 'store'); 
                $this->db->where("business_id",$this->session->userdata('businessid'));
                $q = $this->db->get("staff");                
                $s=$q->row();
                if($q->num_rows() > 0){
                    $dispatch_to_staff= $q->id_staff;
                }else{
                    $this->db->select("id_staff");
                    $this->db->where("staff_active", 'Y');                    
                    $this->db->where("business_id",$this->session->userdata('businessid'));
                    $q = $this->db->get("staff");                
                    $s=$q->row();
                    $dispatch_to_staff= $q->id_staff;
                }
            }else{
                $dispatch_to_staff=$data['dispatch_to_staff'];
            }
            

        }
        $this->db->insert('dispatch_notes', $data);
        $dispatch_id = $this->db->insert_id();
        

        /////get the batch amount
        $this->db->select('*');
        $this->db->where('id_batch', $batch_id);
        $query = $this->db->get('product_batch');
        $batch = $query->row();
        
        $batch_amount = (float)$batch->batch_amount * $dispatch_unit;
        
        //create inventory and cost of goods voucher/////////////////////////////////
        if($this->session->userdata('auto_voucher')=='Yes' && $kit==null){
            $debit_accounts=[];
            $credit_accounts=[];
            
            $account_heads = $this->accounting_model->get_mapped_accounts(23);
            //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' => 'Cost of Goods Used through Dispatch against dispatch note ID '. $dispatch_id . ' on '. $mDate.' to '.$staff_name ,
                'voucher_date' => $mDate,
                'voucher_amount' => $batch_amount,
                'voucher_status' => 'Active',
                'created_by' => $this->session->userdata('username'),
                'cost_center'=> '1',
                'cost_center_name'=> 'Front Desk',
                'business_partner'=> $business_partner,
                'business_partner_id'=> $dispatch_to_staff,
                'business_partner_name'=>$staff_name,
                'voucher_type'=>3,
                //'payment_mode'=>$paymentmode,
                //'bank_name'=>$bank_name,
                'dispatch_id'=>$dispatch_id,
                'visit_id'=>$this->input->post('visit_id'),
                'auto_voucher'=>'Yes',
                //'sale_type'=>'sale'
            );

            $this->db->insert('account_vouchers', $data);
            $cogs_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]=="cogu"){$debitamount= $batch_amount;}
                
                $data_detail=array(
                    'account_voucher_id' => $cogs_voucherid,
                    'account_head_id' => $debit[0],
                    '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;}
                
                $data_detail=array(
                    'account_voucher_id' => $cogs_voucherid,
                    'account_head_id' => $credit[0],
                    'debit' => 0,
                    'credit' => round($creditamount,2)
                );
                //insert credit detail
                if($creditamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }
        
        }
        return "success|".$dispatch_unit;
    }

    
    public function add_dispatch_request($visitid){
        //echo $visitid; exit();
        //if(AUTODISPATCH == true){
            
            //Get all services for the visit
            $this->db->select('*, date_format(visit_service_start, "%Y-%m-%d %H:%i:%s") as visit_date');
            $this->db->join('visit_services', 'visit_services.customer_visit_id = customer_visits.id_customer_visits and visit_services.visit_service_status="Active"');
            $this->db->join('visit_service_staffs', 'visit_service_staffs.visit_service_id = visit_services.id_visit_services and visit_service_staffs.visit_service_staff_status="Active" and visit_service_staffs.additional_staff="NO"', false);
            $this->db->join('services_products', 'services_products.business_service_id = visit_services.service_id');
            $this->db->join('business_products', 'business_products.id_business_products = services_products.business_product_id');
            $this->db->where('id_customer_visits', $visitid);
            $this->db->where('visit_service_start !=', null);
            
            $query = $this->db->get('customer_visits');
            //echo $query; exit();
            $visitdata=$query->result_array();
            //print_r($visitdata); exit();
            $x=0;
            foreach($visitdata as $vd){
                $x++;
                $data = array(
                    'dispatch_request_date'=> $vd['visit_date'],
                    'customer_visit_id'=> $visitid,
                    'customer_id'=> $vd['customer_id'],
                    'service_id'=>$vd['service_id'],
                    'visit_service_id'=> $vd['id_visit_services'],
                    'visit_service_staff_id'=> $vd['id_visit_service_staffs'],
                    'visit_service_staff_id'=> $vd['id_visit_service_staffs'],
                    'created_by'=> $this->session->userdata('username'),
                    'dispatch_request_status'=> 'Active',
                    'product_id'=> $vd['id_business_products'],
                    'product_name'=> $vd['product'],
                    'product_qty'=> $vd['usage_qty'],
                    'product_unit'=> $vd['measure_unit']
                );
                
                $this->db->select('visit_service_id');
                $this->db->where('visit_service_id', $vd['id_visit_services']);
                $this->db->where('product_id', $vd['id_business_products']);
                $this->db->where('dispatch_request_status','Active');
                $q = $this->db->get('dispatch_request');
                $exists=$q->row();
                if(null == $exists){                
                    $this->db->insert('dispatch_request', $data);
                }
                
            }
            
            return $x;
        //}
        
        
    }
    
    function cancel_dispatch_request($visit_service_id, $visit_id=0){
        if($visit_id==0){
            //remove request
            $this->db->where('visit_service_id', $visit_service_id);        
            $this->db->set('dispatch_request_status', 'Cancelled');
            $this->db->set('cancelled_by', $this->session->userdata('username'));
            $this->db->set('cancelled_on', date('Y-m-d H:i:s'));
            $this->db->update('dispatch_request');
            
            //remove dispatch_note
            $this->db->where('visit_service_id', $visit_service_id);
            $this->db->set('status', 'Cancelled');
            $this->db->set('cancelled_by', $this->session->userdata('username'));
            $this->db->set('cancelled_on', date('Y-m-d H:i:s'));
            $this->db->update('dispatch_notes');
            
            //change account voucher status      
            $sql = "update account_vouchers
                    set cancelled_on = now(), cancelled_by='".$this->session->userdata('username')."'
                    , account_vouchers.voucher_status='cancelled'
                    where account_vouchers.dispatch_id in (
                    SELECT id_dispatch_note FROM dispatch_notes
                    where visit_service_id=".$visit_service_id.")";
            $voucher_update = $this->db->query($sql);
            
        } else {
            $this->db->where('customer_visit_id', $visit_id);        
            $this->db->set('dispatch_request_status', 'Cancelled');
            $this->db->set('cancelled_by', $this->session->userdata('username'));
            $this->db->set('cancelled_on', date('Y-m-d H:i:s'));
            $this->db->update('dispatch_request');
            
            //remove dispatch_note
            $this->db->where('visit_id', $visit_id);
            $this->db->set('status', 'Cancelled');
            $this->db->set('cancelled_by', $this->session->userdata('username'));
            $this->db->set('cancelled_on', date('Y-m-d H:i:s'));
            $this->db->update('dispatch_notes');
            
            //change account voucher status      
            $sql = "update account_vouchers
                    set cancelled_on = now(), cancelled_by='".$this->session->userdata('username')."'
                    , account_vouchers.voucher_status='cancelled'
                    where account_vouchers.dispatch_id in (
                    SELECT id_dispatch_note FROM dispatch_notes
                    where visit_id=".$visit_id.")";
            $voucher_update = $this->db->query($sql);
            
        }
        
    }
    
    
    function cancel_dispatch() {
        
        $this->db->select('dispatch_qty');
        $this->db->where('id_dispatch_note', $this->input->post('dispatch_note_id', TRUE));
        
        $query=$this->db->get('dispatch_notes');
        $row = $query->row();
        
        $this->db->where('id_dispatch_note', $this->input->post('dispatch_note_id', TRUE));
        $this->db->update('dispatch_notes', array('status' => 'Cancelled', 'cancelled_by' => $this->session->userdata('username'), 'cancelled_on' => date('Y-m-d H:i:s')));

        $dispatch_qty =$row->dispatch_qty;
        
        //change account voucher status
        $this->db->where('dispatch_id',  $this->input->post('dispatch_note_id', TRUE));
        $this->db->update('account_vouchers', array('voucher_status' => 'cancelled', 'cancelled_by' => $this->session->userdata('username'), 'cancelled_on' => date('Y-m-d H:i:s')));

        
        return $dispatch_qty;
    }
    
    function visit_service_dispatches($visit_service_id, $product_id){
        
        $sql = "select visit_service_id, round(sum(dispatch_measure) + sum(dispatch_qty)) as already_dispatched, measure_unit, unit_type                
                from dispatch_notes where dispatch_notes.status='Active' and visit_service_id = ".$visit_service_id." and product_id = ".$product_id." group by visit_service_id";
        
        $query = $this->db->query($sql);
        return $query->row();
                
    }
    
    function check_history(){
        $date2= date('Y-m-d');
        $date = date_create($date2);        
        $date1 = date_sub($date, date_interval_create_from_date_string("183 days"));                
        $start = date_format($date1,"Y-m-d");        
        $end = $date2;
        
        $this->db->select('*, date_format(dispatch_date, "%d-%m-%Y %h:%i") as d');
        $this->db->join('business_products bp', 'bp.id_business_products =  d.product_id');
        $this->db->join('business_brands bb', 'bp.brand_id=  bb.id_business_brands');
        $this->db->join('staff s', 's.id_staff =  d.dispatch_to_staff');
        $this->db->where('d.business_id', $this->session->userdata('businessid'));
        $this->db->where('d.status','Active');
        $this->db->where('d.product_id',$this->input->post('product_id'));
        $this->db->where('date(d.dispatch_date) >=', $start);
        $this->db->where('date(d.dispatch_date) <=', $end);
        $query = $this->db->get('dispatch_notes d');

        return $query->result_array();
        
    }

    function get_active_dispatch_requests(){
        
        $sql = "SELECT dispatch_request.*, business_products.unit_type, business_products.measure_unit, 
                business_products.qty_per_unit, 
                customers.customer_name, visit_services.service_name, visit_service_staffs.staff_id, visit_service_staffs.staff_name,
                a.already_dispatched, business_products.measure_unit, business_products.unit_type
                FROM dispatch_request
               join customers on customers.id_customers= dispatch_request.customer_id
               join customer_visits on customer_visits.id_customer_visits = dispatch_request.customer_visit_id
               join visit_services on visit_services.id_visit_services = dispatch_request.visit_service_id
               join visit_service_staffs on visit_service_staffs.id_visit_service_staffs = dispatch_request.visit_service_staff_id               
               join business_products on business_products.id_business_products = dispatch_request.product_id
               left join(
                    select visit_service_id, product_id, round(sum(dispatch_measure) + sum(dispatch_qty)) as already_dispatched, 
                    measure_unit, unit_type                
                    from dispatch_notes where dispatch_notes.status='Active' 
                    group by visit_service_id, product_id
                
                ) as a on a.visit_service_id = dispatch_request.visit_service_id and a.product_id=dispatch_request.product_id 
               Where dispatch_request_status = 'Active'
               and customer_visits.business_id = ".$this->session->userdata('businessid')."
               and date(visit_services.visit_service_start)='".date('Y-m-d')."'
                order by id_customer_visits, service_id desc";
        
        $query = $this->db->query($sql);
        
        $dispatch_requests = $query->result_array();
        
        return $dispatch_requests;
        
    }
    
    function get_dispatch_request($visit_id){
        
        $sql = "SELECT dispatch_request.*, business_products.unit_type, business_products.measure_unit, 
                business_products.qty_per_unit, 
                customers.customer_name, visit_services.service_name, visit_service_staffs.staff_id, visit_service_staffs.staff_name
                FROM dispatch_request
               join customers on customers.id_customers= dispatch_request.customer_id
               join customer_visits on customer_visits.id_customer_visits = dispatch_request.customer_visit_id
               join visit_services on visit_services.id_visit_services = dispatch_request.visit_service_id
               join visit_service_staffs on visit_service_staffs.id_visit_service_staffs = dispatch_request.visit_service_staff_id               
               join business_products on business_products.id_business_products = dispatch_request.product_id
               Where and dispatch_request.customer_visit_id = ".$visit_id.";";
        
        $query = $this->db->query($sql);
        
        $dispatch_requests = $query->result_array();

        return $dispatch_requests;
        
    }
    
    function get_dispatch_note($dispatch_id, $visit_id=0){
        
        $sql = "select * from dispatch_notes
            join business_products on business_products.id_business_products = dispatch_notes.product_id
            left 
            join (
            select id_visit_services, id_customer_visits, customers.customer_name, 
            customers.customer_cell, visit_services.service_name            
            from visit_services            
            join customer_visits on customer_visits.id_customer_visits = visit_services.customer_visit_id
            join customers on customers.id_customers=customer_visits.customer_id
             ";
        if($visit_id > 0){
            $sql .=" where id_customer_visits =".$visit_id;
        }
        
        $sql .= " ) as a on a.id_visit_services = dispatch_notes.visit_service_id
            join staff on staff.id_staff = dispatch_notes.dispatch_to_staff";
        if($visit_id > 0){
            $sql .= " where dispatch_notes.visit_id =".$visit_id;
        }else{
            $sql .= " where id_dispatch_note =".$dispatch_id;
        }
        //echo $sql; exit();
        $query = $this->db->query($sql);
        
        $dispatch_note = $query->result();

        return $dispatch_note;
        
    }
}
