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

class Quotation_Controller extends CI_Controller {

        public function __construct() {
        parent::__construct();
        $this->load->model('Product_model');
        $this->load->model('Common_model');
        $this->load->model('General');
         
         /* if(!isset($this->session->userdata['login_data']['username'])) { 
                
                        redirect('Login_controller'); 
                        exit();
            }*/
        }
        
        function testt(){
            echo $out = $this->Common_model->outstand(1012);
            echo "<br>";
           echo $out = $this->Common_model->outstandqto(2069);
           echo "<br>";
           echo $out = $this->Common_model->outstandqto_(6508);
           echo "<br>";
        }
        
    function index(){
       
            
            $columns_arr= array("*");            
            //$where_arr = array('sup_status!='=> 0);                     
            $resultagent = $this->General->getData('mes_termcat',$columns_arr);
            $data['tccatdetails'] = $resultagent;
            
            $data['category'] = $this->Product_model->cat_list();
           
            $data['curren'] = $this->Product_model->currency_list();
            $data['unit'] = $this->Product_model->unit_list();
            $data['tax'] = $this->Product_model->tax_list();
            
           
           $id = $this->General->getqtnlast_id();
            if(empty($id)){$num = 0;}else{$num = $id[0]->po_id;}
            $data['temp_id'] = ($num + 1);
      
           
             $data['content'] = "pages/quotation";        
            $this->load->view('template',$data);
        }
        
    function dispch(){
        
         if(!isset($this->session->userdata['login_data']['username']) && ($this->session->userdata['login_data']['username'] !=9) ) { 
                
                        redirect('login'); 
                        exit();
            }
            
                    $this->db->select('po_dispatch');
                    $this->db->from('mes_qto');
                    $this->db->where('po_id',  $this->input->post('id'));
                    $hasil=$this->db->get();
                    $sls= $hasil->result(); 
                    
                    if($sls[0]->po_dispatch == 1){
                        $this->db->set('po_dispatch', 0);
                        $this->db->where('po_id',  $this->input->post('id'));
                        $this->db->update('mes_qto');
                        
                        $data = "Cancel";
                        
                         $dat = array(
               
                'disp_invid'  => $this->input->post('id'),
                'disp_user'  => $this->session->userdata['login_data']['username'],
                'disp_type'  => $data,
                'disp_cdate'  => date('Y-m-d H:i:s')
                
                     );
                $this->db->insert('mes_dispatch',$dat);
                        
                    }else{
                        $this->db->set('po_dispatch', 1);
                        $this->db->where('po_id',  $this->input->post('id'));
                        $this->db->update('mes_qto');
                       
                       $data = "Proceed"; 
                       
                       $dat = array(
               
                'disp_invid'  => $this->input->post('id'),
                'disp_user'  => $this->session->userdata['login_data']['username'],
                'disp_type'  => $data,
                'disp_cdate'  => date('Y-m-d H:i:s')
                
                     );
                $this->db->insert('mes_dispatch',$dat);
                        
                    }
            
                          echo json_encode($data);
    }
        
    function getpart(){
        
        if(!isset($this->session->userdata['login_data']['username'])) { 
                
                        redirect('login'); 
                        exit();
            }
        $item = $this->input->post('itm_id');
        
                $this->db->select('user_depoid');
                    $this->db->from('mes_user');
                    $this->db->where('user_id',$this->input->post('sale'));
                    $hasil=$this->db->get();
                    $sls= $hasil->result(); 
                    
                    $this->db->select('dpstock_qty');
                    $this->db->from('mes_depot_stock');
                    $this->db->where('dpstock_dpoid',$sls[0]->user_depoid);
                    $this->db->where('dpstock_itemid',$item);
                    $hasill=$this->db->get();
                    $stk= $hasill->result();
                    
                    
                           if($sls[0]->user_depoid==0){
                                    $this->db->select("*");    
                                    $this->db->from('mes_stock');
                                    $this->db->where('stc_itemid', $item);
                                    $query = $this->db->get();
                                    $sdata = $query->result();
                                    //$stqty = $sdata[0]->stc_qty;
                                    $stqty = $sdata[0]->stc_actqty;
                                    
                                    
                                }else{
                                    $this->db->select("*");    
                                                $this->db->from('mes_depot_stock');
                                                $this->db->where('dpstock_itemid', $item);
                                                $this->db->where('dpstock_dpoid', $sls[0]->user_depoid);
                                                $query = $this->db->get();
                                                $sdata = $query->result();
                                                $stqty = $sdata[0]->dpstock_qty;
                                                
                                }
                                
                $this->db->select('product,MAX(`buying_price`) as buying,MAX(`selling_price`) as selling,MAX(`retail_price`) as retail');
                $this->db->from('batch');
                $this->db->where('avl_qty>', 0);
                $this->db->where('product', $item);
                $this->db->order_by("batch.batch_id", "asc");
                $hasil=$this->db->get();
                $stockk= $hasil->result();
              
                    
            if(0 < $stqty){
                $data['item']=  $this->Product_model->single_product($item);
                $new = array_push($data['item'], $stqty);
                $new = array_push($data['item'], $stockk[0]->selling);
            }else{
                $data = "error";
            }    
                
            
            echo json_encode($data);
    }
        
    function get_cus(){
            if(!isset($this->session->userdata['login_data']['username'])) { 
                
                        redirect('Login_controller'); 
                        exit();
            }
        // $data =   $this->Product_model->customer_list();
         $data = $this->Product_model->customer_list();
         for($i=0; $i<count($data); $i++){
             
             $cust[] = array($data[$i]->cust_id,$data[$i]->cust_company);
         }
         
         $sup[0] = $cust;
         
       
        
             
                    $this->db->select('*');
                    $this->db->from('mes_user');
                    if($this->session->userdata['login_data']['userlevel']==20){
                    $this->db->where('user_name',$this->session->userdata['login_data']['username']); }
                    $this->db->where('user_lvl>',9);
                    $this->db->where('user_status',1);
                    $hasil=$this->db->get();
                    $sls= $hasil->result();
        
         
                     
         
         $sup[1] = $sls;
            echo json_encode($sup);
        }
        
    function get_cusdetail(){
        if(!isset($this->session->userdata['login_data']['username'])) { 
                
                        redirect('Login_controller'); 
                        exit();
            }
            $sup = $this->input->post('sup_id');
            
            $this->db->select("mes_currancy.curr_symble as cu_symbol,mes_currancy.curr_id as cu_id,
                                mes_customer.cust_type as custo_type, mes_customer.cust_tax as custo_tax, cust_address.*");
                $this->db->from('mes_customer');
                $this->db->where('mes_customer.cust_id', $sup);
                $this->db->join( "cust_address", "cust_address.cusad_cusid = mes_customer.cust_id", 'left');
                $this->db->join( "mes_currancy", "mes_customer.cust_currency  = mes_currancy.curr_id");
                 
                $this->db->where('cust_status','1');
                $all = $this->db->get();
                $data['sup'] = $all->result();
                
                $this->db->select('po_id as id,po_code as code');
                    $this->db->from('mes_qto');
                    $this->db->where('po_status',1);
                    $this->db->where('po_auth',0);
                    $this->db->where('po_recieved',0);
                    $this->db->where('po_sup_id',$sup);
                    $hasil=$this->db->get();
                    $data['qtn'] = $hasil->result(); 
            //$data['qtn'] = $resultagent;

            echo json_encode($data);
        }
        
    function getprod(){
        if(!isset($this->session->userdata['login_data']['username'])) { 
                
                        redirect('Login_controller'); 
                        exit();
            }
        $this->db->select('mes_item.item_id as itmid, mes_brand.brand_name as brname, mes_model.model_name as moname, item.itm_name as itmname, mes_unit.unit_id as uid,mes_item.item_selling_price as sel_price');
            $this->db->from('mes_item');
            $this->db->join( "mes_partnumber", "mes_partnumber.part_itmno  = mes_item.item_id");
            $this->db->join( "mes_category", "mes_category.cat_id = mes_item.item_cat", 'inner');
            $this->db->join( "mes_brand", "mes_brand.brand_id = mes_item.item_brand", 'inner');
            $this->db->join( "mes_unit", "mes_unit.unit_id = mes_item.item_unit", 'inner');
            $this->db->join( "mes_model", "mes_model.model_id = mes_item.item_model", 'inner');
            $this->db->join( "item", "mes_item.item_name = item.itm_id");
            $this->db->where('mes_partnumber.part_id', $this->input->post('part_id'));
            $hasil=$this->db->get();
            $data['item'] = $hasil->result();
            echo json_encode($data);
    }
    
    function getinvoice_product($id) {     
     if(!isset($this->session->userdata['login_data']['username'])) { 
                
                        redirect('Login_controller'); 
                        exit();
            }
        $this->db->select("*");
        $this->db->from('temp_qto_items');
        $this->db->join('mes_item', 'temp_qto_items.po_itm_item_id   = mes_item.item_id','left');
        $this->db->join('item', 'item.itm_id   = mes_item.item_name','left');
       //$this->db->join('mes_currancy', 'temp_qto_items.po_itm_currancy   = mes_currancy.curr_id','left');
        //$this->db->join('mes_service_type', 'temp_qto_items.service_des   = mes_service_type.serv_id','left');
        $this->db->join('mes_unit', 'temp_qto_items.po_itm_unit   = mes_unit.unit_id','left');
        //$this->db->join( "mes_model", "mes_model.model_id = mes_item.item_model", 'left');
        //$this->db->join('mes_partnumber', 'temp_qto_items.po_itm_partno  = mes_partnumber.part_id','left');
        $this->db->join( "mes_brand", "mes_brand.brand_id = mes_item.item_brand", 'left');
        //$this->db->join( "mes_spec", "mes_spec.spec_id  = mes_item.item_spec",'left');
        $this->db->join( "mes_category", "mes_category.cat_id = mes_item.item_cat",'left');
        $this->db->where('temp_qto_items.po_user', $this->session->userdata['login_data']['user_id']);
        $this->db->order_by("temp_qto_items.temp_id", "desc");
        $hasil=$this->db->get();
        $dataa = $hasil->result();
        
         for($i=0; $i<count($dataa); $i++){
             
                    $itm = $dataa[$i]->itm_name;
                    $data[] = array($dataa[$i]->cat_shortcode,$dataa[$i]->item_catcount,$itm,$dataa[$i]->unit_symble,$dataa[$i]->po_itm_unitprice,$dataa[$i]->po_itm_qty,$dataa[$i]->po_itm_id,$dataa[$i]->free_item,$dataa[$i]->brand_shordcode); 
                
        }
        if(!empty($data)){$data;}else{$data="";}
       
         echo json_encode($data);
    }

    function addinvoice_product() {
        
        if(!isset($this->session->userdata['login_data']['username'])) { 
                
                        redirect('Login_controller'); 
                        exit();
            }
        $allqty = $this->input->post('qty')+$this->input->post('free');
        
                    $usr = $this->session->userdata['login_data']['user_id'];
                        $data = array(
                            'itemid' => $this->input->post('item') ,
                            'refid' => $this->input->post('sls'),
                            'qty' => $this->input->post('qty'),
                            'free' => $this->input->post('free'),
                            'unit_price' => $this->input->post('price'),
                            'dispc' => 0,
                            'user' => $usr,
                       );    
                         
                        $rest_api_base_url = 'https://neha.webip.lk/lumen/public';
                        $post_endpoint = '/add_temp_item_web';
                        $request_data = $data;
                        $response = perform_http_request('POST', $rest_api_base_url . $post_endpoint, $request_data);    
                         $det = json_decode($response); 
            if($det!=null){
                $det = "Added";
            }else{
                $det = "Please Retry";
            }
            
       echo json_encode($det);
    }
    
    function addinvoice_product_old() {
        
        if(!isset($this->session->userdata['login_data']['username'])) { 
                
                        redirect('Login_controller'); 
                        exit();
            }
        $allqty = $this->input->post('qty')+$this->input->post('free');
        
                    $this->db->select('user_depoid');
                    $this->db->from('mes_user');
                    $this->db->where('user_id',$this->input->post('sls'));
                    $hasil=$this->db->get();
                    $sls= $hasil->result();

        $stk = $this->Common_model->check_stock($this->input->post('item'),$allqty,$sls[0]->user_depoid);
        if(!$stk){ 
            $data = "No Stock Available";
        }else{
        
            $item = $this->input->post('item');
            $this->db->select('item_id,item_selling_price,item_freqty,item_freeitm');
            $this->db->from('mes_item');
            $this->db->where('item_id',$item);
            $hasil=$this->db->get();
            $item_data = $hasil->result();
          
          if($item_data[0]->item_freqty!=0){
              $frqt = $this->input->post('qty')/($item_data[0]->item_freqty/$item_data[0]->item_freeitm);
               $dd = intval($frqt);
          }else{
              $dd = 0;
          }
          
          $max_price = (($item_data[0]->item_selling_price)/100)*95;
          
            if($this->input->post('price') < $max_price){
                $data = "Price cannot Approve";
                
            }else if($this->input->post('price') < $this->input->post('pricelkr')){
                $dat = array(
                'temp_id'  => $this->input->post('temp_id'),
                'po_itm_item_id' => $this->input->post('item'),
                'po_itm_qty'  => $this->input->post('qty'), 
                'po_itm_unitprice'  => $this->input->post('price'), 
                'po_itm_unit'  => $this->input->post('unit'),
                'po_aprvl'  => '1',
                'free_item' => $this->input->post('free'),
                'depo_id'  => $sls[0]->user_depoid,
                'po_user' => $this->session->userdata['login_data']['username']
                
                );
                $detail = $this->db->insert('temp_qto_items',$dat);
                $insert_id = $this->db->insert_id();
                $data = "Price Changed.Invoice need to be approved";
                
               //$dd = round($item_data[0]->item_freqty[0],0,PHP_ROUND_HALF_ODD);
              
                
            }else if( ($dd*3) < $this->input->post('free')){
                
                $dat = array(
                'temp_id'  => $this->input->post('temp_id'),
                'po_itm_item_id' => $this->input->post('item'),
                'po_itm_qty'  => $this->input->post('qty'), 
                'po_itm_unitprice'  => $this->input->post('price'), 
                'po_itm_unit'  => $this->input->post('unit'),
                'po_aprvl'  => '1',
                'free_item' => $this->input->post('free'),
                'depo_id'  => $sls[0]->user_depoid,
                'po_user' => $this->session->userdata['login_data']['username']
                
                );
                $detail = $this->db->insert('temp_qto_items',$dat);
                $insert_id = $this->db->insert_id();
                $data = "Invoice need to be approved";
                
            }else{
                $dat = array(
                'temp_id'  => $this->input->post('temp_id'),
                'po_itm_item_id' => $this->input->post('item'),
                'po_itm_qty'  => $this->input->post('qty'), 
                'po_itm_unitprice'  => $this->input->post('price'), 
                'po_itm_unit'  => $this->input->post('unit'),
                'po_aprvl'  => '0',
                'free_item' => $this->input->post('free'),
                'depo_id'  => $sls[0]->user_depoid,
                'po_user' => $this->session->userdata['login_data']['username']
                );
                $detail = $this->db->insert('temp_qto_items',$dat);
                $insert_id = $this->db->insert_id();
                $data = "Added";
            }
            
           $stk = $this->Common_model->cal_stock($sls[0]->user_depoid,"temp",$insert_id,$this->input->post('item'),$allqty,"min",0);
       
        }
            
       echo json_encode($data);
    }
   
    function save_inv() {
        if(!isset($this->session->userdata['login_data']['username'])) { 
                
                        redirect('login'); 
                        exit();
            }
            
            if($this->session->userdata['login_data']['userlevel'] == 20){
                
                $usr = $this->session->userdata['login_data']['user_id'];
            }else{ 
                $usr = $this->input->post('sales');}
       
     
                        $data = array(
                            'cus_id' => $this->input->post('sup_id'),
                            'ref_id' => $usr,
                            'tot_price' => $this->input->post('total'),
                            'discount' => $this->input->post('dis'),
                            'final' => $this->input->post('final'),
                            'tot_qty' => $this->input->post('qty'),
                            'other' => $this->input->post('other'),
                            'remark' => $this->input->post('remark'),
                            'username' => $this->session->userdata['login_data']['username'],
                       );    
                         
                        $rest_api_base_url = 'https://neha.webip.lk/lumen/public';
                        $post_endpoint = '/save_inv';
                        $request_data = $data;
                        $response = perform_http_request('POST', $rest_api_base_url . $post_endpoint, $request_data);    
                         $det = json_decode($response); 
            if($det!=null){
                $det = "Removed";
            }else{
                $det = "Please Retry";
            }
       
         echo json_encode($det);
    }
    
    function save_inv_old() {
        if(!isset($this->session->userdata['login_data']['username'])) { 
                
                        redirect('login'); 
                        exit();
            }
            $temp_id = $this->input->post('temp_id');
            
            
            $this->db->select('po_itm_id');
            $this->db->from('temp_qto_items');
            $this->db->where('po_user',$this->session->userdata['login_data']['username']);
            $hasil=$this->db->get();  
            $count = $hasil->num_rows();
            
            if($count<1){
                echo json_encode("error");
            }
            
            $cust = $this->input->post('sup_id');
            
            $this->db->select('cust_discount');
            $this->db->from('mes_customer');
            $this->db->where('cust_id', $cust);
            $hasil=$this->db->get();  
            $cusdata = $hasil->result();
            
            if($cusdata[0]->cust_discount!=0.00){
                if($cusdata[0]->cust_discount<$this->input->post('dis')){ $discnt = $this->input->post('dis'); $auth = 0;
                }else{$discnt = $this->input->post('dis'); $auth = 1; }
                
            }else if(0 < $this->input->post('dis')){
                $discnt = $this->input->post('dis');
                $auth = 0;
            }else{
                $auth = 1;
            }
            
            $val = $this->load->library('Numbertowordconvertsconver');
            $number = $this->input->post('final');
            $rndfin = ceil(round($number, 2));
            $num1 =  $this->numbertowordconvertsconver->convert_number($rndfin);
            //$num2 = $this->numbertowordconvertsconver->convert_number($tempNum[1]);
            $finl= $num1." only";
            
            //if($tempNum[1]!=00){
           //    $finl= $num1." and ". $num2." cents only";
                
           // }else{$finl= $num1." only";}
            //$fword = $this->numbertowordconvertsconver->convert_number($number);
            
            $out = $this->Common_model->outstand($this->input->post('sup_id'));
        $dat = array(
                //'date'  => date('Y-m-d'),
                'po_sup_id'  => $this->input->post('sup_id'),
                'po_sup_outstand'  => $out,
                'po_ref_id'  => $this->input->post('sales'),
                'uniq_id'  => random_string('alnum',20),
                'po_tot_price'  => $this->input->post('total'), 
                'po_discount'  => $this->input->post('dis'),
                'actual_final'  => $this->input->post('final'),
                'po_final_tot'  => $rndfin,
                'po_tot_qty'  => $this->input->post('qty'),
                'po_tot_items'  => $count,
                'po_other'  => $this->input->post('other'),
                'po_currancy' => $this->input->post('cur'),
                'po_delevery'  => "0", 
                'po_cuser'  => $this->session->userdata['login_data']['username'], 
                'po_remark' => $this->input->post('remark'),
                'po_fwording' => $finl,
                'po_cdate'  => date('Y-m-d H:i:s'),
                'po_auth'   => $auth,
                'depo'  => $this->session->userdata['login_data']['depot']
                
            );
       $data = $this->db->insert('mes_qto',$dat);
        $insert_id = $this->db->insert_id(); 
        
        
         
        $this->db->set('po_itm_po_id',$insert_id);
        $this->db->set('temp_id',$insert_id);
        $this->db->where('po_user',$this->session->userdata['login_data']['username']);
        $this->db->update('temp_qto_items');
            
        $this->db->select("*");    
        $this->db->from('temp_qto_items');
        $this->db->where('po_itm_po_id', $insert_id );
        $query = $this->db->get();
        
        $tot_free = 0;    
        foreach ($query->result() as $row) {
                $dat = array(
                'po_itm_item_id'  => $row->po_itm_item_id,
                'service_des'  => $row->service_des,
                'depo_id'  => $row->depo_id,
                'po_itm_po_id' => $row->po_itm_po_id,
                'po_itm_qty'  => $row->po_itm_qty, 
                'po_itm_unit'  => $row->po_itm_unit,
                'free_item'  => $row->free_item,
                'po_itm_unitprice'  => $row->po_itm_unitprice,
                'po_itm_currancy'  => $row->po_itm_currancy,
                'po_itm_description'  => $row->po_itm_description,
                'po_aprvl' => $row->po_aprvl,
                'po_user'  => $this->session->userdata['login_data']['username']
            );
                  $this->db->insert('qto_items',$dat);
                   $tot_free = $tot_free + $row->free_item;
                  
                
                $this->db->set('invt_type',"INV");
                $this->db->set('invt_type_id',$insert_id);
                $this->db->where('invt_type','temp');
                $this->db->where('invt_type_id',$row->po_itm_id);
                $this->db->update('mes_inventry');  
                
                
                $this->db->where('po_itm_id', $row->po_itm_id);
                  $this->db->delete('temp_qto_items');
                  
            }
            $this->db->select('po_itm_po_id');
            $this->db->from('qto_items');
            $this->db->where('po_itm_po_id', $insert_id);
            $this->db->where('po_aprvl', 1);
            $hasil=$this->db->get();  
            $count2 = $hasil->num_rows();
            if(($count2 > 0)||($auth!=1)){$aprl = '0';}else{$aprl = '1';}
            
            $this->db->select("*");    
            $this->db->from('inv_return');
            $this->db->join( "mes_qto", "mes_qto.po_id  = inv_return.ret_invnum");
            $this->db->where('mes_qto.po_sup_id', $this->input->post('sup_id'));
            $this->db->where('inv_return.ret_to_inv','0');
            $this->db->order_by("inv_return.ret_id", "asc");
            $hasil = $this->db->get();
            $rtn = $hasil->result();
            
            
            $this->db->set('po_tot_freqty',$tot_free);
            if(isset($rtn[0]->ret_amount)){
                $this->db->set('return_amnt',$rtn[0]->ret_amount);
            }
            $this->db->set('po_auth',$aprl);
            $this->db->where('po_id',  $insert_id);
            $this->db->update('mes_qto');
            
            if(isset($rtn[0]->ret_amount)){
                $this->db->set('ret_to_inv','1');
                $this->db->where('ret_id', $rtn[0]->ret_id);
                $this->db->update('inv_return');
            }
            
            if($aprl!=1){
            $msg = "Requesting Authorization for";
            //$this->Common_model->dosms($insert_id,$msg);
            
        }
              $dt = $auth;
              
         echo json_encode($dt);
         //$this->view_pdf($insert_id);
    }
    
    function getprod_spec(){
        if(!isset($this->session->userdata['login_data']['username'])) { 
                
                        redirect('Login_controller'); 
                        exit();
            }
        $this->db->select('*');
            $this->db->from('mes_item');
            $this->db->join( "mes_spec", "mes_spec.spec_id  = mes_item.item_spec");
            $this->db->join( "mes_category", "mes_category.cat_id = mes_item.item_cat", 'inner');
            $this->db->join( "mes_brand", "mes_brand.brand_id = mes_item.item_brand", 'inner');
            $this->db->join( "mes_unit", "mes_unit.unit_id = mes_item.item_unit", 'inner');
            $this->db->join( "mes_model", "mes_model.model_id = mes_item.item_model", 'inner');
            $this->db->join( "item", "mes_item.item_name = item.itm_id");
            $this->db->where('mes_spec.spec_id', $this->input->post('part_id'));
            $hasil=$this->db->get();
            $data['item'] = $hasil->result();
            echo json_encode($data);
    }
    
    function viewallqtn(){
      if(!isset($this->session->userdata['login_data']['username'])) { 
                
                        redirect('login'); 
                        exit();
            }
            $rest_api_base_url = 'https://neha.webip.lk/lumen/public';
            $post_endpoint = '/profile';
 
        $response = perform_http_request('GET', $rest_api_base_url . $post_endpoint);
         $data['prof'] = $response;   
            
            $data['content'] = "pages/allqto";        
            $this->load->view('template',$data);
        }
        
    function view_pdf(){
        
        $id = $_GET['id'];
        $this->db->select("*");    
        $this->db->from('mes_qto');
        $this->db->where('uniq_id', $id);
        $query = $this->db->get();
        $gtid=$query->result();
        $insert_id = $gtid[0]->po_id; 
        $cus_id = $gtid[0]->po_sup_id; 
        
        $this->db->select("*");    
        $this->db->from('qto_items');
        $this->db->where('po_itm_po_id', $insert_id );
        $this->db->join('mes_item', 'qto_items.po_itm_item_id   = mes_item.item_id','left');
        $this->db->join('item', 'item.itm_id   = mes_item.item_name','left');
        $this->db->join('mes_model', 'mes_item.item_model   = mes_model.model_id','left');
        $this->db->join('mes_brand', 'mes_item.item_brand   = mes_brand.brand_id','left');
        $this->db->join('mes_unit', 'qto_items.po_itm_unit   = mes_unit.unit_id','left');
        $this->db->join('mes_currancy', 'qto_items.po_itm_currancy   = mes_currancy.curr_id','left');
        $this->db->join( "mes_category", "mes_category.cat_id = mes_item.item_cat", 'left');
        $this->db->join( "batch", "batch.batch_id  = qto_items.po_itm_batch", 'left');
        $this->db->order_by("mes_item.item_brand", "asc");
        $query = $this->db->get();
        $dataa=$query->result();
        
         for($i=0; $i<count($dataa); $i++){
             
                    
                    if($dataa[$i]->brand_name!=""){$spece = "  ";}else{$spece = "";} if($dataa[$i]->model_name!=""){$spece1 = "  ";}else{$spece1 = "";}
                    if($dataa[$i]->retail_price == 0.00){$rp = "";}else{$rp = number_format(($dataa[$i]->retail_price),2,".",",");}
                  
                    $itm = $dataa[$i]->brand_name.$spece.$dataa[$i]->itm_name."\n".$dataa[$i]->model_name;
                    $inv[] = array($dataa[$i]->cat_shortcode,$dataa[$i]->item_catcount,$dataa[$i]->itm_name,$dataa[$i]->unit_symble,$dataa[$i]->po_itm_unitprice,$dataa[$i]->po_itm_qty,$dataa[$i]->po_itm_id,$dataa[$i]->free_item,$dataa[$i]->brand_shordcode,$rp,$dataa[$i]->batch,$dataa[$i]->exp_date); 
                
        }
        $data['inv_itm'] = $inv;
        
         $this->db->select("*");    
                $this->db->from('mes_inventry');
               // $this->db->join('mes_termcat', 'mes_tmdes.tmdes_catid  = mes_termcat.tcat_id');
                $this->db->where('invt_type', "INV");
                $this->db->where('invt_type_id', $insert_id);
                //$this->db->order_by("mes_tmdes.tmdes_catid", "asc");
                $querynew = $this->db->get();
                $dateinv =$querynew->result();
        
        
        $this->db->select("*");    
        $this->db->from('mes_qto');
        $this->db->where('po_id', $insert_id );
        $this->db->join('mes_customer', 'mes_qto.po_sup_id  = mes_customer.cust_id', 'left');
        $this->db->join('mes_currancy', 'mes_qto.po_currancy   = mes_currancy.curr_id', 'left');
        $this->db->join('mes_country', 'mes_customer.cust_country   = mes_country.cnty_id', 'left');
        $this->db->join('mes_depot', 'mes_depot.dep_id  = mes_qto.depo');
        //$this->db->join('mes_user', 'mes_qto.po_cuser   = mes_user.user_id','left');
        $this->db->join('mes_user', 'mes_qto.po_ref_id   = mes_user.user_id','left');
        $query = $this->db->get();
        $rr = $query->result();
        
                $this->db->select("*");    
                $this->db->from('mes_qto');
                $this->db->join('mes_depot', 'mes_depot.dep_id  = mes_qto.depo');
                $this->db->where('po_sup_id', $cus_id);
                $this->db->where('po_payment', 0);
                $this->db->order_by("po_cdate", "asc");
                $queryinv = $this->db->get();
                $dateinvd =$queryinv->result();
                
                $invout="";
                $incount=0;
                  for($i=0; $i<count($dateinvd); $i++){
                      
                    $dataout = $this->Common_model->outstandqto($dateinvd[$i]->po_id);
                    
                    if($dataout!=0){
                        
                        $invout = $invout." | ".$dateinvd[$i]->po_cdate." - ".$dateinvd[$i]->qto_code.$dateinvd[$i]->po_id." - ".number_format($dataout,2); 
                        
                        $incount = $incount +1;
                    }
                    
                
                    }
        
        $dataout = $this->Common_model->outstand($cus_id);
        
                $this->db->select("*");    
                $this->db->from('mes_qto');
                $this->db->where('po_cdate', $rr[0]->po_cdate);
                $queryinv = $this->db->get();
                $daily_count =$queryinv->result();
        $dailycnt = 0;
            for($i=0; $i<count($daily_count); $i++){
                if($daily_count[$i]->uniq_id==$id){
                    $dailycnt = ($i+1);
                    break;
                }
            }    
            
           // $time = new DateTime($dateinv[0]->invt_cdate);
            $date = "";
            $time = "";
        
        $data['inv']=array($rr,"",$dataout,$invout,$rr[0]->dep_name,$incount,$dailycnt,$time);
        
       $tc = explode(',',$rr[0]->po_tc);
      // sort($tc);
       $length = count($tc);
        
         for ($i = 1; $i < $length; $i++) {
                $this->db->select("*");    
                $this->db->from('mes_tmdes');
                $this->db->join('mes_termcat', 'mes_tmdes.tmdes_catid  = mes_termcat.tcat_id');
                $this->db->where('tmdes_id', $tc[$i]);
                $this->db->order_by("mes_tmdes.tmdes_catid", "asc");
                $query = $this->db->get();
                $tm[] =$query->result();
            } 
        
        $data['tm'][0] = "";
        
                $this->db->select("*");    
                $this->db->from('mes_profile');
                $query = $this->db->get();
                $data['tm'][1] =$query->result();
     
     
        $this->load->view('pages/qtnpdf',$data);
    }
    
    function show_all_qtn() {
        if(!isset($this->session->userdata['login_data']['username'])) { 
                
                        redirect('logout'); 
                        exit();
            }
            
            $this->db->select('mes_qto.*,mes_customer.*,mes_currancy.*,mes_country.*,mes_user.*,mes_qto.po_final_tot as fintot');
            $this->db->from('mes_qto');
            $this->db->join( "mes_customer", "mes_customer.cust_id = mes_qto.po_sup_id", 'left');
            $this->db->join( "mes_currancy", "mes_currancy.curr_id = mes_qto.po_currancy", 'left');
            $this->db->join( "mes_country", "mes_country.cnty_id = mes_customer.cust_country", 'left');
            $this->db->join('mes_user', 'mes_qto.po_ref_id   = mes_user.user_id','left');
            $this->db->order_by("mes_qto.po_auth",1);
            $this->db->order_by("mes_qto.po_id","desc");
            $this->db->limit(100);
            
            
            if($this->session->userdata['login_data']['userlevel']>=20){
                
                $this->db->where('po_ref_id',$this->session->userdata['login_data']['user_id']);
                
            }
            
         
            $hasil=$this->db->get();
            $data= $hasil->result(); 
            //$data['content'] = ('pages/allinvoice');                       
            //$this->load->view('template',$data);
            
            $link = site_url('qto');
            
            if($this->session->userdata['login_data']['userlevel'] < 2){
                
                $det[0]="<a href='$link'><button type='button' class='btn btn-outline-danger' >Create New Invoice</button></a></br>";
            }
            
             if($this->session->userdata['login_data']['userlevel']>=20){
                       
                       $vw_btn = "<a href ='".base_url()."inv_view_pdf/?id=".$data[0]->uniq_id."' target='_blank'> <button type='button' class='btn btn-outline-secondary btn-sm' >View</button></a>";
                   }
             
            //$det[0]="";
            $det[1] ="<tr>
														<th scope='col'>ID</th>
														
														<th>INV Number</th>
														<th>Customer</th>
														<th>Item</th>
														<th>Qty</th>
														<th>Free</th>
														<th style='text-align: right;'>Total</th>
														<th style='text-align: right;'>Return</th>
														<th style='text-align: right;'>Payment</th>
														<th style='width: 90px;'>Date</th>
													    <th>Status</th>
														<th>Action</th>
                                                                                                             
																											
													</tr>";
            
          $det[2]="";
          
                for($i=0; $i<count($data); $i++){
                    
                    
                        
                        if($data[$i]->po_dispatch==1){$disbtn ="Restock";}else{$disbtn ="Dispatch";}
                    
                   if(($this->session->userdata['login_data']['userlevel'] < 6 ) || ($this->session->userdata['login_data']['userlevel'] ==15 ) ){
                        $vw_btn1 = " <a href ='".base_url()."authorize_inv/".$data[$i]->po_id."'> <button type='button' class='btn btn-outline-secondary btn-sm' >Authorize</button></a>";
                    }else{$vw_btn1 ="";}
                    
                     if($this->session->userdata['login_data']['userlevel'] == 9 && $data[$i]->po_dispatch==1){
                        $vw_btn2 = "<a href ='".base_url()."inv_view_pdf/?id=".$data[$i]->uniq_id."' target='_blank'> <button type='button' class='btn btn-outline-secondary btn-sm' >View</button></a>
                        <button type='button' class='btn btn-danger btn-sm'  id='".$data[$i]->po_id."' onclick='edit_dispatch(this.id)' >$disbtn</button>
                                ";
                    }else{
                        
                        if($data[$i]->po_authuser!="0"){$authuser = $data[$i]->po_authuser; }else{$authuser = "";}
                         $vw_btn2 = "<a href ='".base_url()."inv_view_pdf/?id=".$data[$i]->uniq_id."' target='_blank'> <button type='button' class='btn btn-outline-secondary btn-sm' >View</button></a><br><b>$authuser</b>
                  ";
                   }
                    
                   
                   
                        
                    if($data[$i]->po_auth==1 ){
                        if($data[$i]->po_status==1){
                        $sts = "<td style='color:#00800085; font-size:25px; text-align: center;'>&#9679;</td>"; $vw_btn = $vw_btn2;
                        }else{
                        $sts = "<td style='color:#ff000080; font-size:25px; text-align: center;'>&#9679;</td>";  $vw_btn = $vw_btn2;}
                        
                    }else{
                        if($data[$i]->po_status==1){
                        $sts = "<td style='color:#c6ab1b85; font-size:25px; text-align: center;'>&#9679;</td>"; $vw_btn = $vw_btn1;
                        }else{
                        $sts = "<td style='color:#ff000080; font-size:25px; text-align: center;'>&#9679;</td>";  $vw_btn = $vw_btn1;}
                        
                    }
                    if($data[$i]->po_recieved==1){
                        $rec = 'Invoiced';
                        }else{
                        $rec = 'No invoice';}
                        
                        
                        if($data[$i]->po_payment==1){
                        $pd = 'Paid';$pdd = 0.00; 
                        $floatq = "<td style='text-align: right;' width='100px'>".$pd."</td>";
                        }else{
                        $pd = "Pending"; 
                            
                            $this->db->select('SUM(pay_amount) AS pay_amountt');
                            $this->db->from('mes_payment');
                            $this->db->where('pay_invid',$data[$i]->po_id);
                            $this->db->where('pay_stetus',1);
                            $this->db->where('pay_authrize',1);
                            $hasil=$this->db->get();
                            $paid= $hasil->result();
                            $pdd = $paid[0]->pay_amountt;
                           $float = (float)$pdd;
                            
                            //if($float1==0.00){$float = "";}else{$float = $float1;}
                            $floatq = "<td style='text-align: right;' width='100px'>".$pd."<br>".number_format($float, 2, '.', ',')."</td>";
                        } 
                        
                        if($data[$i]->fintot == $data[$i]->return_amnt){
                            $floatq = "<td style='text-align: right;' width='100px'>Cancelled</td>";
                        }
                        if($data[$i]->fintot == 0.00 ){$floatq = "<td style='text-align: right;' width='100px'>Sample Issue</td>";}
                        
                    
                        
                    
                    $x = $i+1;
                    $dat =  "
                                 <tr scope='row'><td >".$x."</td>
                                 <td >".$data[$i]->po_code.$data[$i]->po_id."</td>
                                 
                               
                                 <td>".$data[$i]->cust_company."<br>".$data[$i]->cust_addres."<br><b>".$data[$i]->user_fname." ".$data[$i]->user_lname."</b></td>
                                 <td style='text-align: center;'>".($data[$i]->po_tot_items)."</td>
                                <td style='text-align: right;'>".$data[$i]->po_tot_qty."</td>
                                <td style='text-align: right;'>".$data[$i]->po_tot_freqty."</td>
                             
                                <td style='text-align: right;' width='100px'>".number_format($data[$i]->fintot, 2, '.', ',')."</td>
                                <td style='text-align: right;' width='100px'>".number_format($data[$i]->return_amnt, 2, '.', ',')."</td>
                              $floatq
                            
                                <td width='70px'>".$data[$i]->po_cdate."</td>
                                
                                $sts
                               
                                
                                
                                <td>$vw_btn   </td>
                               
                              
                              </tr>";
                              $x++;
                              $det[2] =$det[2].$dat;
                              $det[3] = $data[0]->po_id;
                }
                
            
            	
           echo json_encode($det);
            //echo json_encode($data);
        }
 
    function prodelete(){
       if(!isset($this->session->userdata['login_data']['username'])) { 
                
                        redirect('Login_controller'); 
                        exit();
            }
        
        $usr = $this->session->userdata['login_data']['user_id'];
                        $data = array(
                            'temp_line_id' => $this->input->post('product_code'),
                            'ref_id' => $usr
                       );    
                         
                        $rest_api_base_url = 'https://neha.webip.lk/lumen/public';
                        $post_endpoint = '/remove_inv_item';
                        $request_data = $data;
                        $response = perform_http_request('POST', $rest_api_base_url . $post_endpoint, $request_data);    
                         $det = json_decode($response); 
            if($det!=null){
                $det = "Removed";
            }else{
                $det = "Please Retry";
            }
        
        
        
        echo json_encode($det);
    
        }
        
        function prodelete_old(){
       if(!isset($this->session->userdata['login_data']['username'])) { 
                
                        redirect('Login_controller'); 
                        exit();
            }
        
               $this->db->select('*');
                    $this->db->from('temp_qto_items');
                    $this->db->where('po_itm_id',$this->input->post('product_code'));
                    $hasil=$this->db->get();
                    $qto_itm= $hasil->result();
                    
        $allqty = $qto_itm[0]->po_itm_qty+$qto_itm[0]->free_item;
        
                  $this->db->select('user_depoid');
                    $this->db->from('mes_user');
                    $this->db->where('user_id',$this->input->post('sales'));
                    $hasil=$this->db->get();
                    $sls= $hasil->result();
        
            $stk = $this->Common_model->cal_stock($sls[0]->user_depoid,"temprem",0,$qto_itm[0]->po_itm_item_id,$allqty,"plus",0);
            
                    
        $product_code=$this->input->post('product_code');
        if($product_code!=""){
            $this->db->where('po_itm_id', $product_code);
            $data=$this->db->delete('temp_qto_items');
        }
        
        
        
        echo json_encode($data);
    
        }
        
    function authorize($inv_id){
        if(!isset($this->session->userdata['login_data']['username'])) { 
                        redirect('login'); 
                        exit();
            }
            $this->db->select('*');
            $this->db->from('mes_qto');
            $this->db->where('po_id', $inv_id);
            $this->db->join('mes_user', 'mes_qto.po_ref_id   = mes_user.user_id');
            $this->db->join('mes_customer', 'mes_qto.po_sup_id   = mes_customer.cust_id');
            $hasil=$this->db->get();  
            $inv = $hasil->result();
            
            if($inv[0]->po_auth!="1"){
                $columns_arr= array("*");            
                //$where_arr = array('sup_status!='=> 0);                     
                $resultagent = $this->General->getData('mes_termcat',$columns_arr);
                $data['tccatdetails'] = $resultagent;
                
                $data['category'] = $this->Product_model->cat_list();
               
                $data['curren'] = $this->Product_model->currency_list();
                $data['unit'] = $this->Product_model->unit_list();
                $data['tax'] = $this->Product_model->tax_list();
                $data['inv'] = $inv;
               
               
               
               $id = $this->General->getqtnlast_id();
                if(empty($id)){$num = 0;}else{$num = $id[0]->po_id;}
                $data['inv_id'] = $inv_id;
               
                 $data['content'] = "pages/auth_quotation";        
                $this->load->view('template',$data);
                
            }else{
                $this->viewallqtn();
            }
            
    } 
    
    function get_auth_product($id){
        
        if(!isset($this->session->userdata['login_data']['username'])) { 
                
                        redirect('Login_controller'); 
                        exit();
            }
        $this->db->select("*");
        $this->db->from('qto_items');
        $this->db->join('mes_item', 'qto_items.po_itm_item_id   = mes_item.item_id','left');
        $this->db->join('item', 'item.itm_id   = mes_item.item_name','left');
        $this->db->join('mes_currancy', 'qto_items.po_itm_currancy   = mes_currancy.curr_id','left');
        $this->db->join('mes_unit', 'qto_items.po_itm_unit   = mes_unit.unit_id','left');
        $this->db->join( "mes_model", "mes_model.model_id = mes_item.item_model", 'left');
        $this->db->join( "mes_brand", "mes_brand.brand_id = mes_item.item_brand", 'left');
        $this->db->join( "mes_category", "mes_category.cat_id = mes_item.item_cat",'left');
        $this->db->where('qto_items.po_itm_po_id',  $id);
        $this->db->order_by("qto_items.po_itm_po_id", "desc");
        $hasil=$this->db->get();
        $dataa = $hasil->result();
        
         for($i=0; $i<count($dataa); $i++){
             
                $this->db->select('*');
                $this->db->from('batch');
                $this->db->where('batch_id',$dataa[$i]->po_itm_batch);
                $hasil=$this->db->get();  
                $inv = $hasil->result();
             
                    $itm = $dataa[$i]->brand_name." ".$dataa[$i]->itm_name." ".$dataa[$i]->model_name;
                    $data[] = array($inv[0]->batch,$dataa[$i]->item_catcount,$dataa[$i]->itm_name,$dataa[$i]->unit_symble,
                    $dataa[$i]->po_itm_unitprice,$dataa[$i]->po_itm_qty,$dataa[$i]->po_itm_id,$dataa[$i]->free_item,
                    $inv[0]->selling_price,$dataa[$i]->item_freeitm,$dataa[$i]->item_freqty,$dataa[$i]->po_itm_item_id); 
                
        }
        if(!empty($data)){$data;}else{$data="";}
       
         echo json_encode($data);
    }
     
    function get_allgrn(){
        if(!isset($this->session->userdata['login_data']['username'])) { 
                
                        redirect('Login_controller'); 
                        exit();
            }
        
            $this->db->select('invt_qty,buy_price,invt_cdate');
            $this->db->from('mes_inventry');
            $this->db->where('invt_itemid', $this->input->post('item_id'));
            $this->db->order_by("invt_id", "desc");
            $this->db->limit(5, 0);
            $hasil=$this->db->get();  
            $inv = $hasil->result();
            
            $dt="";
          
                for($i=0; $i<count($inv); $i++){ 
                    $x = $i+1;
                    $dat =  "
                                 <tr scope='row'><td >".$x."</td>
                                 <td >".$inv[$i]->buy_price."</td>
                                 <td >".$inv[$i]->invt_qty."</td>
                                <td >".$inv[$i]->invt_cdate."</td>
                              </tr>";
                              $x++;
                              $dt =$dt.$dat;
                }         
                
           
            
            echo json_encode($dt);
    }    

    function get_qto_itm(){
        
        if(!isset($this->session->userdata['login_data']['username'])) { 
                
                        redirect('Login_controller'); 
                        exit();
            }
            $this->db->select('*');
            $this->db->from('qto_items');
            $this->db->where('po_itm_id', $this->input->post('item_id'));
            //$this->db->where('po_aprvl', 1);
            $hasil=$this->db->get();  
            $inv = $hasil->result();
            
            $this->db->select('*');
            $this->db->from('mes_item');
            $this->db->where('item_id', $inv[0]->po_itm_item_id);
            $this->db->join('item', 'item.itm_id = mes_item.item_name','left');
            $itm=$this->db->get();  
            $itmdt = $itm->result();
            
            $this->db->select('*');
                $this->db->from('batch');
                $this->db->where('batch_id',$inv[0]->po_itm_batch);
                $hasil=$this->db->get();  
                $batch = $hasil->result();
            
            $data = array($itmdt[0]->itm_name,$batch[0]->selling_price,$itmdt[0]->item_freeitm,$itmdt[0]->item_freqty,$inv[0]->po_itm_qty,$inv[0]->po_itm_unitprice,$inv[0]->free_item);
            
            echo json_encode($data);
    }
    
    function update_item(){
        
        if(!isset($this->session->userdata['login_data']['username'])) { 
                
                        redirect('Login_controller'); 
                        exit();
            }
        $inv_id = $this->input->post('inv_id');
        
            $this->db->select('*');
            $this->db->from('qto_items');
            $this->db->where('po_itm_id', $this->input->post('inv_id'));
            $this->db->join('mes_qto', 'mes_qto.po_id = qto_items.po_itm_po_id','left');
            $hasil=$this->db->get();  
            $item = $hasil->result();
            
            $this->db->select('user_depoid');
                    $this->db->from('mes_user');
                    $this->db->where('user_id',$item[0]->po_ref_id);
                    $hasil=$this->db->get();
                    $sls= $hasil->result();
                    
            $done = "Updated. Cannot Increse Free Quantity";        
            
            if($item[0]->free_item > $this->input->post('inv_fr')){
                $stock = $this->Common_model->cal_stock($sls[0]->user_depoid,"auth",$item[0]->po_itm_po_id,$item[0]->po_itm_item_id,$item[0]->free_item,"plus",0,$item[0]->po_itm_batch);
                $stock = $this->Common_model->cal_stock($sls[0]->user_depoid,"auth",$item[0]->po_itm_po_id,$item[0]->po_itm_item_id,$this->input->post('inv_fr'),"min",0,$item[0]->po_itm_batch);
                
               // $stk = $this->Common_model->cal_stock($sls[0]->user_depoid,"auth",$item[0]->po_itm_po_id,$item[0]->po_itm_item_id,$item[0]->free_item,"plus",0);
           // $stk = $this->Common_model->cal_stock($sls[0]->user_depoid,"auth",$item[0]->po_itm_po_id,$item[0]->po_itm_item_id,$this->input->post('inv_fr'),"min",0);
            $done = "Free Issues Updated"; 
                $this->db->set('free_item',$this->input->post('inv_fr'));
                
            }
        
         
        $this->db->set('po_itm_unitprice',$this->input->post('inv_price'));
        $this->db->where('po_itm_id',  $this->input->post('inv_id'));
        $this->db->update('qto_items');
        
        echo json_encode($done);
        
    }
    
    function updt_auth_inv(){
        if(!isset($this->session->userdata['login_data']['username'])) { 
                
                        redirect('login'); 
                        exit();
            }
        $this->db->select('*');
            $this->db->from('qto_items');
            $this->db->where('po_itm_po_id', $this->input->post('id'));
            $hasil=$this->db->get();  
            $item = $hasil->result();
            
            $totqty = $prc = $totprice = $totfree= 0;
            
            for($i=0; $i<count($item); $i++){ 
                $totqty += $item[$i]->po_itm_qty;
                $prc = $item[$i]->po_itm_qty * $item[$i]->po_itm_unitprice;
                $totprice += $prc;
                $totfree += $item[$i]->free_item;
               
                $this->db->set('po_aprvl',0);
                $this->db->where('po_itm_id',$item[$i]->po_itm_id);
                $this->db->update('qto_items');
            }
        
        $caldis = (100 - $this->input->post('dis'));
        $fin =  ($totprice/100)*$caldis;
        
        $this->load->library('Numbertowordconvertsconver');
        $rndfin = ceil(round($fin, 2));
        //$rndfin = ceil($fin);
        $num1 =  $this->numbertowordconvertsconver->convert_number($rndfin);
        $fwrd = $num1." only";
        
        $this->db->set('po_tot_price',$totprice);
        $this->db->set('po_discount',$this->input->post('dis'));
        $this->db->set('po_final_tot',$rndfin);
        $this->db->set('po_fwording',$fwrd);
        $this->db->set('actual_final',$fin);
        $this->db->set('po_tot_qty',$totqty);
        $this->db->set('po_tot_freqty',$totfree);
        $this->db->set('po_auth',1);
        $this->db->set('po_auth_comment',$this->input->post('remark'));
        $this->db->set('po_authdate',date("Y-m-d"));
        $this->db->set('po_authuser',$this->session->userdata['login_data']['username']);
        $this->db->where('po_id',$this->input->post('id'));
        $this->db->update('mes_qto');
        
        echo json_encode("Invoice Authorized");
    }
    
    function customer_data(){
        if(!isset($this->session->userdata['login_data']['username'])) { 
                
                        redirect('Login_controller'); 
                        exit();
            }
        $this->db->select('cust_discount,cust_addres');
            $this->db->from('mes_customer');
            $this->db->where('cust_id', $this->input->post('sup_id'));
            $hasil=$this->db->get();  
            $item = $hasil->result();
            
           echo json_encode($item); 
    }
    
    function serchinv(){
        
          if(!isset($this->session->userdata['login_data']['username'])) { 
                
                        redirect('Login_controller'); 
                        exit();
            }
            
            
            
            //$this->input->post('item_id')
            
            $this->db->select('mes_qto.*,mes_customer.*,mes_currancy.*,mes_country.*,mes_user.*,mes_customer.cust_company as cus,mes_qto.po_final_tot as fintot');
            $this->db->from('mes_qto');
            $this->db->join( "mes_customer", "mes_customer.cust_id = mes_qto.po_sup_id", 'left');
            $this->db->join( "mes_currancy", "mes_currancy.curr_id = mes_qto.po_currancy", 'left');
            $this->db->join( "mes_country", "mes_country.cnty_id = mes_customer.cust_country", 'left');
            $this->db->join('mes_user', 'mes_qto.po_ref_id   = mes_user.user_id','left');
            
            
            if($this->input->post('invid')!=""){
               $this->db->where('po_id',$this->input->post('invid'));
           }else if($this->input->post('cusid')!=""){
                
                $this->db->like('mes_customer.cust_company',$this->input->post('cusid'));
               
            }
            
            
              if($this->session->userdata['login_data']['userlevel']>=20){
                
                $this->db->where('po_ref_id',$this->session->userdata['login_data']['user_id']);
                
            }
            
            $hasil=$this->db->get();
            $data= $hasil->result(); 
            //$data['content'] = ('pages/allinvoice');                       
            //$this->load->view('template',$data);
            
            $link = site_url('qto');
            
            if($this->session->userdata['login_data']['userlevel']  < 2){
                
                $det[0]="<a href='$link'><button type='button' class='btn btn-outline-danger' >Create New Invoice</button></a></br>";
            }
            
             if($this->session->userdata['login_data']['userlevel']>=20){
                       
                       $vw_btn = "<a href ='".base_url()."inv_view_pdf/?id=".$data[0]->uniq_id."' target='_blank'> <button type='button' class='btn btn-outline-secondary btn-sm' >View</button></a>";
                   }
             
            //$det[0]="";
            $det[1] ="<tr>
														<th scope='col'>ID</th>
														
														<th>INV Number</th>
														<th>Customer</th>
														<th>Item</th>
														<th>Qty</th>
														<th>Free</th>
														<th style='text-align: right;'>Total</th>
														<th style='text-align: right;'>Return</th>
														<th style='text-align: right;'>Payment</th>
														<th>Date</th>
													    <th>Status</th>
														<th>Action</th>
                                                                                                             
																											
													</tr>";
            
          $det[2]="";
          
                for($i=0; $i<count($data); $i++){
                    
                    
                        
                        if($data[$i]->po_dispatch==1){$disbtn ="Restock";}else{$disbtn ="Dispatch";}
                    
                    if(($this->session->userdata['login_data']['userlevel'] != 9) && ($this->session->userdata['login_data']['userlevel'] != 20) ){
                        $vw_btn1 = " <a href ='".base_url()."authorize_inv/".$data[$i]->po_id."'> <button type='button' class='btn btn-outline-secondary btn-sm' >Authorize</button></a>";
                    }else{$vw_btn1 ="";}
                    
                     if($this->session->userdata['login_data']['userlevel'] == 9 && $data[$i]->po_dispatch==1){
                        $vw_btn2 = "<a href ='".base_url()."inv_view_pdf/?id=".$data[$i]->uniq_id."' target='_blank'> <button type='button' class='btn btn-outline-secondary btn-sm' >View</button></a>
                        <button type='button' class='btn btn-danger btn-sm'  id='".$data[$i]->po_id."' onclick='edit_dispatch(this.id)' >$disbtn</button>
                                ";
                    }else{
                        
                        if($data[$i]->po_authuser!="0"){$authuser = $data[$i]->po_authuser; }else{$authuser = "";}
                         $vw_btn2 = "<a href ='".base_url()."inv_view_pdf/?id=".$data[$i]->uniq_id."' target='_blank'> <button type='button' class='btn btn-outline-secondary btn-sm' >View</button></a><br><b>$authuser</b>
                  ";
                   }
                    
                   
                   
                        
                    if($data[$i]->po_auth==1 ){
                        if($data[$i]->po_status==1){
                        $sts = "<td style='color:#00800085; font-size:25px; text-align: center;'>&#9679;</td>"; $vw_btn = $vw_btn2;
                        }else{
                        $sts = "<td style='color:#ff000080; font-size:25px; text-align: center;'>&#9679;</td>";  $vw_btn = $vw_btn2;}
                        
                    }else{
                        if($data[$i]->po_status==1){
                        $sts = "<td style='color:#c6ab1b85; font-size:25px; text-align: center;'>&#9679;</td>"; $vw_btn = $vw_btn1;
                        }else{
                        $sts = "<td style='color:#ff000080; font-size:25px; text-align: center;'>&#9679;</td>";  $vw_btn = $vw_btn1;}
                        
                    }
                    if($data[$i]->po_recieved==1){
                        $rec = 'Invoiced';
                        }else{
                        $rec = 'No invoice';}
                        
                        
                        if($data[$i]->po_payment==1){
                        $pd = 'Paid';$pdd = 0.00; 
                        $floatq = "<td style='text-align: right;' width='100px'>".$pd."</td>";
                        }else{
                        $pd = "Pending"; 
                            
                            $this->db->select('SUM(pay_amount) AS pay_amountt');
                            $this->db->from('mes_payment');
                            $this->db->where('pay_invid',$data[$i]->po_id);
                            $this->db->where('pay_stetus',1);
                            $this->db->where('pay_authrize',1);
                            $hasil=$this->db->get();
                            $paid= $hasil->result();
                            $pdd = $paid[0]->pay_amountt;
                           $float = (float)$pdd;
                            
                            //if($float1==0.00){$float = "";}else{$float = $float1;}
                            $floatq = "<td style='text-align: right;' width='100px'>".$pd."<br>".number_format($float, 2, '.', ',')."</td>";
                        } 
                        
                        if($data[$i]->fintot == $data[$i]->return_amnt){
                            $floatq = "<td style='text-align: right;' width='100px'>Cancelled</td>";
                            $sts = "<td style='color:#ff000080; font-size:25px; text-align: center;'>&#9679;</td>";
                        }
                        
                    
                        
                    
                    $x = $i+1;
                    $dat =  "
                                 <tr scope='row'><td >".$x."</td>
                                 <td >".$data[$i]->po_code.$data[$i]->po_id."</td>
                                 
                               
                                <td>".$data[$i]->cust_company."<br>".$data[$i]->cust_addres."<br><b>".$data[$i]->user_fname." ".$data[$i]->user_lname."</b></td>
                                <td style='text-align: center;'>".($data[$i]->po_tot_items)."</td>
                                <td style='text-align: right;'>".$data[$i]->po_tot_qty."</td>
                                <td style='text-align: right;'>".$data[$i]->po_tot_freqty."</td>
                                <td style='text-align: right;' width='100px'>".number_format($data[$i]->fintot, 2, '.', ',')."</td>
                                <td style='text-align: right;' width='100px'>".number_format($data[$i]->return_amnt, 2, '.', ',')."</td>
                              $floatq
                            
                                <td width='70px'>".$data[$i]->po_cdate."</td>
                                
                                $sts
                               
                                
                                
                                <td>$vw_btn   </td>
                               
                              
                              </tr>";
                              $x++;
                              $det[2] =$det[2].$dat;
                              $det[3] = $data[0]->po_id;
                }
                
            
            	
           echo json_encode($det);
            //echo json_encode($data);
            
            
    }
    
}

