<?php

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

class Productkits_controller extends CI_Controller {

    public function __construct() {
        parent::__construct();
        // Your own constructor code
        $this->load->model('product_model');
         $this->load->model('transfernotes_model');
        $this->load->model('accounting_model');
        $this->load->model('productkits_model');
        $this->load->model('supplier_model');
        $this->load->model('business_model');
        $this->load->model('dispatch_model');
        
        if ($this->session->userdata('role') == '') {
            redirect('logout');
        }
    }
    
    public function product_kits($businessid="") {
         
        $query = $this->business_model->getbusinessdetails(); 
        $data['unit_types']=$this->product_model->get_unittypes();
        $data['product_types'] = $this->product_model->get_product_types();
        $data['measurement_unit'] = $this->product_model->get_measurement_unit();
        $data['brands'] = $this->product_model->get_all_brands();
        
        $isho = $query[0]['ho'];
        
        if($this->session->userdata('common_products')=='No'){
            $businessid=$this->session->userdata('businessid');            
        } else if($businessid=="" && $isho=="No") {
            $businessid=$this->session->userdata('businessid');
        }
      
        $data['kits']= $this->productkits_model->getallkits($businessid);
        
//        echo '<pre>';
//        print_r($data['kits']);
//        exit();
        
        
        
        $this->load->view('includes/header', $data);
        $this->load->view('setting/product_kits_view');
        $this->load->view('includes/footer');
     }
    
    public function add_kits() {

        $this->productkits_model->add_kit();        

        redirect('product_kits');
        
    }
    
     public function update_kits(){
        
        $a = $this->productkits_model->update_kit();        

        redirect('product_kits');
        
    }
    
    public function add_kit_products() {

        
        $this->productkits_model->add_kit_products();        

        redirect('product_kits');
        
    }
    
    public function remove_kit_products() {

        
        $a = $this->productkits_model->remove_kit_products();        

        echo 'success|'.$a;
        
    }
    
   public function get_kit_config(){
       $kitid=$this->input->post('product_id');       
       
       $data = $this->productkits_model->get_kit_config($kitid);        

        echo json_encode($data);
       
    }

    public function add_kit_batch(){
        $kitid = $this->input->post('kit_id');
        $kitname = $this->input->post('kit_name');
        $products = $this->input->post('TableData'); 
        //print_r($products); exit();

        //check the all kit product batches to have enough inventory
        $dispatchdata=[]; $enough = 'No';
        foreach($products as $product){
            $p_batches = $this->product_model->get_all_batches($product['productid'], $business_id=$this->session->userdata['businessid'], '');            
            foreach($p_batches as $p_batch){
                if($p_batch['total_stock'] >= $product['kit_qty']){
                    $enough = 'Yes';
                    array_push($dispatchdata, array(
                        'product_id'=> $product['productid'],
                        'dispatch_to_staff' => 0,
                        'dispatch_qty' => round((float)$product['kit_qty'] * (float)$this->input->post('batch_qty', TRUE),2),
                        'dispatch_measure' =>  round(((float)$this->input->post('batch_qty', TRUE) * floatval($product['kit_qty'])) * floatval($product['qty_per_unit']),2),
                        'unit_type' => $product['unit_type'],
                        'measure_unit' => $product['measure_unit'],
                        'dispatch_date' => date('Y-m-d H:i:s'),
                        'batch' => $p_batch['batch_number'],
                        'batch_id' => $p_batch['id_batch'],
                        'business_id' => $this->session->userdata('businessid'),
                        'created_by' => $this->session->userdata('username'),
                        'dispatch_comment'=> 'Used in Creating Kit Unit For '.$kitname,
                        'visit_id'=> 0,
                        'visit_service_id'=> 0,
                        'request_id'=>0
                    ));                   
                    break;
                } else {
                    $enough = 'Quantity is less then required for Product '.$p_batch['product'];                    
                }
            }           
        }
        
        if(sizeof($products) == sizeof($dispatchdata)){
             //add the new batch for the kit    
             $batchdata = array(
                'batch_number' => $this->input->post('batch_number', TRUE),
                'product_id' => $this->input->post('kit_id', TRUE),
                'batch_date' => $this->input->post('batch_date', TRUE),
                'expiry_date' => $this->input->post('batch_expiry', TRUE),
                'batch_qty' => $this->input->post('batch_qty', TRUE),
                'store_id' => $this->input->post('store_id', TRUE),
                'batch_amount' => $this->input->post('unit_price', TRUE)
            );
            $this->db->insert('product_batch', $batchdata);        
            $batch_id = $this->db->insert_id();


            //dispatch the products
            foreach($dispatchdata as $data){
                // $this->db->insert('dispatch_notes', $data);
                // $dispatch_id = $this->db->insert_id();
                $dispatch_id = $this->dispatch_model->add_dispatch($data, 'kit');
            }
            ////

            //adjustment note data
            $adjustment=[];
            $adjdata = array(
                'batch_id' => $batch_id,
                'product_id' => $kitid,
                'adjustment_qty' => $this->input->post('batch_qty'),
                'unit_price' => $this->input->post('unit_price'),
                'remarks' => 'New batch added with opening qty for '.$kitname,
                'adjustment_date' => $this->input->post('batch_date', TRUE),                
                'created_on' => date('Y-m-d H:i:s'),
                'created_by' => $this->session->userdata('username')
            );
            array_push($adjustment, $adjdata);
            //$this->db->insert('adjustment_notes', $adjdata);
            //$adjustment_id=$this->db->insert_id();
            $a = $this->product_model->add_adjustment_note($adjustment, 'kit'); 

            echo 'success|'.$batch_id;
            
        } else {

            echo 'error|'.$enough;
        }
    }

    public function update_kit_batch(){

        $kitid = $this->input->post('kit_id');
        $kitname = $this->input->post('kit_name');
        $products = $this->input->post('kit_data'); 
        $adjustments = $this->input->post('adjustments');
        $adjustments = json_decode($adjustments, TRUE);
        $adj_qty = 0;
        foreach ($adjustments as $adj){
            $adj_qty = $adj_qty + floatval($adj['adjustment_qty']);
        }
        if($adj_qty > 0){ //compile kits
            //check the all kit product batches to have enough inventory
            $dispatchdata=[]; $enough = 'No';
            foreach($products as $product){
                $p_batches = $this->product_model->get_all_batches($product['productid'], $business_id=$this->session->userdata['businessid'], '');            
                foreach($p_batches as $p_batch){
                    if($p_batch['total_stock'] >= $product['kit_qty']){
                        $enough = 'Yes';
                        array_push($dispatchdata, array(
                            'product_id'=> $product['productid'],
                            'dispatch_to_staff' => 0,
                            'dispatch_qty' => floatval($product['kit_qty']) * $adj_qty,
                            'dispatch_measure' => (floatval($product['kit_qty']) * $adj_qty) * floatval($product['qty_per_unit']),
                            'unit_type' => $product['unit_type'],
                            'measure_unit' => $product['measure_unit'],
                            'dispatch_date' => date('Y-m-d H:i:s'),
                            'batch' => $p_batch['batch_number'],
                            'batch_id' => $p_batch['id_batch'],
                            'business_id' => $this->session->userdata('businessid'),
                            'created_by' => $this->session->userdata('username'),
                            'dispatch_comment'=> 'Batch updated with Adjustment Quantity For '.$kitname,
                            'visit_id'=> 0,
                            'visit_service_id'=> 0,
                            'request_id'=>0
                        ));                   
                        break;
                    } else {
                        $enough = 'No';                    
                    }
                }           
            }

            if(sizeof($products) == sizeof($dispatchdata)){
                foreach($dispatchdata as $data){
                    // $this->db->insert('dispatch_notes', $data);               
                    // $dispatch_id = $this->db->insert_id();
                    $dispatch_id = $this->dispatch_model->add_dispatch($data, 'kit', null);
                }

                $result  = $this->product_model->update_batch();         
                $a = $this->product_model->add_adjustment_note(null, 'kit'); 

            } else {
                echo 'error|Not enough quantity in one of the kit products';
            }
            echo('success|' . $result);
            die;
        } else { //uncompile kits
            //get batch numbers for the products of the kits
            echo('error|Value less then zero is Not Allowed');

        }
       
    }
    
}