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

class Grn_Controller extends CI_Controller {

        public function __construct() {
        parent::__construct();
        $this->load->model('Product_model');
        $this->load->model('General');
        $this->load->model('Common_model');
            if(!isset($this->session->userdata['login_data']['username'])) { 
                    
                            redirect('https://newapp.nance.lk/logout'); 
                            exit();
                }
         
        }
        
        function index(){
            
                    $this->db->from('mes_po');
                    $this->db->where('po_status',1);
                    $this->db->where('po_auth',0);
                    $this->db->where('po_recieved',0);
                    $hasil=$this->db->get();
                    $resultagent= $hasil->result(); 
                    
            $data['agentdetail'] = $resultagent;
            
          $data['itemdetail'] =  $this->Product_model->product_grn_list();
            
            $data['content'] = "pages/newgrn";        
            $this->load->view('template',$data);
        }
        
        function removebin(){
            
            $id = $this->input->post('arr_rowid');
            $j = count($id);
            $to_stock = $this->input->post('arr_bin_stock');
            
            for($i=0; $i<$j; $i++){
                
                $this->db->select('ret_to_stock.*,batch.*,batch.batch as batchcode');
                $this->db->from('ret_to_stock');
                $this->db->join('batch', 'ret_to_stock.batch   = batch.batch_id','left');
                $this->db->where('to_stock_id',$id[$i]);
                $hasil=$this->db->get();
                $ret_item= $hasil->result();
                
                if($to_stock[$i] > $ret_item[0]->to_bin){
                    echo json_encode("Incorrect Quantities");
                }else{
                    
                   // $newstk = $to_stock[$i] + $ret_item[0]->to_stock;
                    $newbin =  ($ret_item[0]->to_bin - $to_stock[$i]); 
                    
                                    //$this->db->set('to_stock', $newstk);
                                    $this->db->set('to_bin', $newbin);
                                    //$this->db->set('bin_auth', 1);
                                        $this->db->where('to_stock_id', $id[$i]);
                                        $result = $this->db->update('ret_to_stock');
                                        
                   // $this->db->select('*');
                   // $this->db->from('return_items');
                    //$this->db->join('mes_qto', 'mes_qto.po_id   = return_items.ret_inv_id','left');
                   // $this->db->where('ret_itm_id',$ret_item[0]->ret_item_row);
                   // $hasil=$this->db->get();
                   // $ret_dep= $hasil->result();     
                   
                    $dat = array(
                        'restlog_binqty'  => $to_stock[$i],
                        'restlog_batchid' => $ret_item[0]->batchcode,
                        'restlog_cuser'  => $this->session->userdata['login_data']['user_id'],
                        'restlog_cdate'  => date('Y-m-d')
                        
                    );
                    $data = $this->db->insert('ret_to_stock_log',$dat);
                    $insert_id = $this->db->insert_id();
                                        
                                        
                       // $stock = $this->Common_model->cal_stock($ret_dep[0]->depo,"BinToStock",$id[$i],$ret_item[0]->product,$to_stock[$i],"plus",0,$ret_item[0]->batch_id);
                       $msg = "done";
                }
                
               
                
            }
            
                
                
            echo json_encode($msg);    
        }
        
            
        
        
        function qtoo(){
                $this->db->select('*');
                $this->db->from('temp_qto_items');
                $this->db->where('po_itm_po_id', 10893);
                $hasil=$this->db->get();
                $stockk= $hasil->result();
            
            for($i=1; $i<count($stockk); $i++){
                
                       
                $dat = array(
                        'po_itm_item_id'  => $stockk[$i]->po_itm_item_id,
                        'depo_id' => $stockk[$i]->depo_id,
                        'po_itm_batch' => $stockk[$i]->po_itm_batch,
                        'po_itm_po_id' => $stockk[$i]->po_itm_po_id,
                        'service_des'  => $stockk[$i]->service_des,
                        'po_itm_qty'  => $stockk[$i]->po_itm_qty,
                        'free_item'  => $stockk[$i]->free_item,
                        'po_itm_unit'  => $stockk[$i]->po_itm_unit,
                        'po_itm_unitprice'  => $stockk[$i]->po_itm_unitprice,
                        'po_itm_currancy'  => $stockk[$i]->po_itm_currancy,
                        'po_itm_description'  => $stockk[$i]->po_itm_description,
                        'po_aprvl'  => $stockk[$i]->po_aprvl,
                        'po_user'  => 11
                        
                    );
            $data = $this->db->insert('qto_items',$dat);
            
            }
        }
        
        function test(){
                $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->group_by('product');
                //$this->db->where('product', 5);
                $hasil=$this->db->get();
                $stockk= $hasil->result();
            
            for($i=0; $i<count($stockk); $i++){
                $this->db->set('item_selling_price', $stockk[$i]->selling);
                $this->db->set('item_buying_price', $stockk[$i]->buying);
                $this->db->set('item_retail_price', $stockk[$i]->retail);
                $this->db->set('retail_price', $stockk[$i]->retail);
                $this->db->where('item_id', $stockk[$i]->product);
                $result=$this->db->update('mes_item');
                echo $stockk[$i]->product."-".$stockk[$i]->selling."<br>";
            }
        }
        
        function test2(){
           // SELECT `product`,SUM(`tot_qty`),SUM(`avl_qty`) FROM `batch_depo` GROUP BY `product`;

                $this->db->select('`product`,SUM(`tot_qty`) as tot,SUM(`avl_qty`) as avl');
                $this->db->from('batch_depo');
                $this->db->group_by('product'); 
                $hasil=$this->db->get();
                $stockk= $hasil->result();
            
            for($i=1; $i<count($stockk); $i++){
                $this->db->set('dpstock_qty', $stockk[$i]->avl);
                $this->db->where('dpstock_itemid', $stockk[$i]->product);
                $result=$this->db->update('mes_depot_stock1');
                echo $stockk[$i]->product;
            }
        }
       
        function getproduct(){
          
            $data = $this->Common_model->po_grnitem($this->input->post('po_id'));
           $det="";
            if(count($data)<2){ 
                $det = "<tr><td>Only Services Available</td></tr>";
            }else{
                for($i=1; $i<count($data); $i++){
                  
                    $this->db->select('sum(mes_inventry.invt_qty) as rec');
                    $this->db->from('mes_grn');
                    $this->db->where('grn_poidcode', $this->input->post('po_id'));
                    $this->db->join( "mes_inventry", "mes_inventry.invt_type_id = mes_grn.grn_id", 'left');
                    $this->db->where('mes_inventry.invt_type',"GRN");
                    $this->db->where('mes_inventry.invt_itemid',$data[$i][6]);
                    $hasil=$this->db->get();
                    $rec= $hasil->result(); 
                    
                    $rem = $data[$i][5] - $rec[0]->rec;
                    if($rec[0]->rec){$rc=$rec[0]->rec;}else{$rc=0.00;}
                    
                    $dat =  "
                                 <tr>
                               <td >".$i."</td>
                               <td >".$data[$i][0]."-".$data[$i][1]."</td>
                               <td >".$data[$i][2]."</td>
                               <td style='text-align: center;'>".$data[$i][3]."</td>
                                <td style='text-align: right;'>".$data[$i][5]."</td>
                                <td style='text-align: right;'>".$rc."</td>
                               <td><input type='text' id=".$data[$i][6]."  name='po_val[]' placeholder='' value='' class='col-xs-12 col-sm-12 input-sm form-control-sm form-control txt_val'/ style='text-align: right;'>
                                <input type='hidden' id=''  name='po_tot[]' value=".$rem.">
                               </td>
                              
                               
                             <!--td style='text-align: right;'>
                                <div class='hidden-sm hidden-xs btn-group'>
                                 <button class='btn btn-outline-danger btn-sm' name='tax' id=".$data[$i][6]." onclick ='del_data(this.id);'>X</button>
                   
                               </div>
                                </td-->
                                </tr>";
                                
                              $det =$det.$dat;
                              
                              
                }
            }
              
                
                  echo json_encode($det);
        }
        
        function batchprice(){
            
             if(!isset($this->session->userdata['login_data']['username'])) { 
                    
                            redirect('Login_controller'); 
                            exit();
                }
                
                
                    $this->db->select('batch.*,mes_item.*,batch.retail_price as rt');
                    $this->db->from('batch');
                    $this->db->join( "mes_item", "mes_item.item_id = batch.product", 'left');
                    $this->db->where('product', $this->input->post('item'));
                    $this->db->order_by('batch_id', "DESC");
                    $this->db->limit(1);
                    $hasil=$this->db->get();
                    $rec= $hasil->result(); 
            
             
                 if (!empty($rec)){
                      $data[] = array($rec[0]->buying_price,$rec[0]->selling_price,$rec[0]->rt,$rec[0]->item_exp); 
                 }else{
                     $data[]="";
                 }
                    
           
           
           
             echo json_encode($data);
        }
        
        function pogrnsave(){
            $id = $this->input->post('ids');
            $qt = $this->input->post('values');
           
           if((count($id)>0) && (count($qt)>0) ){
           
           
           $tot = 0;
            $dat = array(
                        'grn_poid'  => $this->input->post('poid'),
                        'grn_invnum' => $this->input->post('inv'),
                        'grn_donum' => $this->input->post('podo'),
                        'grn_poidcode' => $this->input->post('poidval'),
                        'grn_totqty'  => $tot,
                        'grn_cuser'  => $this->session->userdata['login_data']['username'],
                        'grn_cdate'  => date('Y-m-d')
                        
                    );
            $data = $this->db->insert('mes_grn',$dat);
           $insert_id = $this->db->insert_id();
           
           if($data){
               for($i=0; $i<count($id); $i++){
                if($qt[$i]!=""){
                    $dat = array(
                        'invt_type'  => "GRN",
                        'invt_type_id'  => $insert_id,
                        'invt_itemid'  => $id[$i],
                        'invt_qty' => $qt[$i],
                        'invt_cuser'  => $this->session->userdata['login_data']['username'],
                        'invt_cdate'  =>date('Y-m-d')
                        
                    );
                    $data = $this->db->insert('mes_inventry',$dat);
                    $tot = $tot+$qt[$i];
                }
            }
           
            $this->db->set('grn_totqty', $tot);
            $this->db->where('grn_id', $insert_id);
            $result=$this->db->update('mes_grn');
           }
           
               
           }
           
            $send = "New GRN Created";
            echo json_encode($send);
            
        }
            
        function dire_grn(){
            
            $id = $this->input->post('ids');
            $qt = $this->input->post('values');
            $dpo_price = $this->input->post('dpo_price');
            $exp_date = $this->input->post('exp_date');
           
           $tot = 0;
            $dat = array(
                        'grn_poid'  => "",
                        'grn_invnum' => $this->input->post('inv'),
                        'grn_donum' => $this->input->post('podo'),
                        'grn_totqty'  => $tot,
                        'grn_cuser'  => $this->session->userdata['login_data']['username'],
                        'grn_cdate'  => date('Y-m-d')
                        
                    );
            $data = $this->db->insert('mes_grn',$dat);
           $insert_id1 = $this->db->insert_id();
           
            for($i=0; $i<count($id); $i++){
                if($qt[$i]!=""){
                    $dat = array(
                        'invt_type'  => "GRN",
                        'invt_type_id'  => $insert_id1,
                        'invt_itemid'  => $id[$i],
                        'invt_qty' => $qt[$i],
                        'buy_price' => $dpo_price[$i],
                        'exp_date' => $exp_date[$i],
                        'invt_proc' =>'0',
                        'invt_cuser'  => $this->session->userdata['login_data']['username'],
                        'invt_cdate'  =>date('Y-m-d')
                        
                    );
                    $data = $this->db->insert('mes_inventry',$dat);
                    $insert_id = $this->db->insert_id();
                    $tot = $tot+$qt[$i];
                }
                
                //$this->Common_model->cal_stock(0,"GRN",$insert_id,$id[$i],$qt[$i],"plus","0");
            }
           
            $this->db->set('grn_totqty', $tot);
            $this->db->where('grn_id', $insert_id1);
            $result=$this->db->update('mes_grn');
           
      
            $send = "New GRN Created";
            echo json_encode($send);
        } 
        
        function grn_all(){
            
             $data['content'] = "pages/allgrn";        
            $this->load->view('template',$data); 
        }
        
        function showallgrn(){
             
             
            $this->db->select('*');
            $this->db->from('mes_grn');
            $this->db->join( "mes_user", "mes_user.user_id  = mes_grn.grn_cuser", 'left');
            //$this->db->join( "mes_user", "mes_user.user_id  = mes_grn.grn_puser", 'left');
            $this->db->order_by("grn_id","desc");
            $this->db->order_by("grn_proceed","0");
            $this->db->limit(100);
            $hasil=$this->db->get();
            $data= $hasil->result(); 
            
         
            $link = site_url('new_grn');
            
             if($this->session->userdata['login_data']['userlevel'] < 6){
                 $det[0]="<a href='$link'><button type='button' class='btn btn-outline-danger' >Create New GRN</button></a></br>";
             }else{
                   $det[0]="</br>";
             }
           
           
            
            $det[1] ="<tr>
														<th scope='col' style='text-align: center;'>ID</th>
														
														<th>GRN Number</th>
														<th>Supplier</th>
														<th>Invoice Number</th>
														<th>Total Qty</th>
														<th>Date</th>
														<th>User</th>
													    <th>Status</th>
														<th>Action</th>
                                                                                                             
																											
													</tr>";
            
          $det[2]="";
          
                for($i=0; $i<count($data); $i++){
                    
            $this->db->select('*');
            $this->db->from('mes_po');
            $this->db->where('po_id', $data[$i]->grn_poidcode);
            $this->db->join( "mes_suppliers", "mes_suppliers.sup_id = mes_po.po_sup_id", 'inner');
            $hasil1=$this->db->get();
            $datanew= $hasil1->result();
            
            $this->db->select('*');
            $this->db->from('mes_user');
            $this->db->where('mes_user.user_id', $data[$i]->grn_puser);
            $hasilgrn=$this->db->get();
            $datagrn= $hasilgrn->result(); 
            
            if($hasil1->num_rows()>0){
                $sup = $datanew[0]->sup_company;
            }else{$sup = "Direct GRN";}
            
            if($this->session->userdata['login_data']['userlevel'] < 6 || $this->session->userdata['login_data']['userlevel'] == 10){
                
                $pro = "<button type='button' class='btn btn-outline-secondary btn-sm' type='button' id='".$data[$i]->grn_id."'  onclick='po_proceed(this.id)' >Process</button>";
            }else{$pro="";}
                    
                   $vw_btn1 = "<a href ='".base_url()."pdf_grn/".$data[$i]->grn_id."' target='_blank'> <button type='button' class='btn btn-outline-secondary btn-sm' >View</button></a>
                               <a href ='".base_url()."edit_grn/".$data[$i]->grn_id."'> <button type='button' class='btn btn-outline-secondary btn-sm' >Edit</button></a>
                                <button type='button' class='btn btn-outline-secondary btn-sm' type='button' id='".$data[$i]->grn_id."' name='edtbutton' onclick='po_cancel(this.id)' data-target='#Modal_edit'>Cancel</button>
                                $pro
                                ";
                    $vw_btn2 = "<a href ='".base_url()."pdf_grn/".$data[$i]->grn_id."' target='_blank'> <button type='button' class='btn btn-outline-secondary btn-sm' >View</button></a>
                                
                                ";
                        
                    if($data[$i]->grn_proceed==1){
                        if($data[$i]->grn_stetus==1){
                        $sts = "<td style='color:#00800085; font-size:25px; text-align: center;'>&#9679;</td>"; $vw_btn = $vw_btn2."<br><b>".$datagrn[0]->user_name."</b>";
                        }else{
                        $sts = "<td style='color:#ff000080; font-size:25px; text-align: center;'>&#9679;</td>";  $vw_btn = $vw_btn2;}
                        
                    }else{
                        if($data[$i]->grn_stetus==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_btn2."<br><b>".$data[$i]->grn_euser."</b>";}
                        
                    }
                    if($data[$i]->grn_poid!=""){$poid = $data[$i]->grn_poid;}else{$poid="N/A";}
                    
                    $x = $i+1;
                    $dat =  "
                                 <tr scope='row'>
                                 <td >".$x."</td>
                                 <td >".$data[$i]->grn_code.$data[$i]->grn_id."</td>
                                 <td>".$sup."</td>
                                 
                                 <td>".$data[$i]->grn_invnum."</td>
                                 <td style='text-align: right;'>".$data[$i]->grn_totqty."</td>
                                <td style='text-align: right;'>".$data[$i]->grn_cdate."</td>
                                <td style='text-align: right;'>".$data[$i]->user_name."</td>
                                $sts
                                <td>$vw_btn   </td>
                               
                              
                              </tr>";
                              $x++;
                              $det[2] =$det[2].$dat;
                }
                
            
            	
           echo json_encode($det);
            //echo json_encode($data);
        }
        
        function searchallgrn(){
            
              $date = $this->input->post('date');
              $grn = $this->input->post('grn');
            
            $this->db->select('*');
            $this->db->from('mes_grn');
            $this->db->join( "mes_user", "mes_user.user_id  = mes_grn.grn_cuser", 'left');
            //$this->db->join( "mes_user", "mes_user.user_id  = mes_grn.grn_puser", 'left');
            $this->db->order_by("grn_id","desc");
            $this->db->order_by("grn_proceed","0");
            if($grn!=""){
                $this->db->where('grn_id', $grn);
            }
            
             if($date!=""){
               $this->db->where('grn_cdate', $date);
            }
            
            
            //$this->db->limit(100);
            $hasil=$this->db->get();
            $data= $hasil->result(); 
            
         
                $link = site_url('new_grn');
           
             if($this->session->userdata['login_data']['userlevel'] < 6){
                 $det[0]="<a href='$link'><button type='button' class='btn btn-outline-danger' >Create New GRN</button></a></br>";
             }else{
                   $det[0]="</br>";
             }
            
            $det[1] ="<tr>
														<th scope='col' style='text-align: center;'>ID</th>
														
														<th>GRN Number</th>
														<th>Supplier</th>
														<th>Invoice Number</th>
														<th>Total Qty</th>
														<th>Date</th>
														<th>User</th>
													    <th>Status</th>
														<th>Action</th>
                                                                                                             
																											
													</tr>";
            
          $det[2]="";
          
                for($i=0; $i<count($data); $i++){
                    
            $this->db->select('*');
            $this->db->from('mes_po');
            $this->db->where('po_id', $data[$i]->grn_poidcode);
            $this->db->join( "mes_suppliers", "mes_suppliers.sup_id = mes_po.po_sup_id", 'inner');
            $hasil1=$this->db->get();
            $datanew= $hasil1->result();
            
            $this->db->select('*');
            $this->db->from('mes_user');
            $this->db->where('mes_user.user_id', $data[$i]->grn_puser);
            $hasilgrn=$this->db->get();
            $datagrn= $hasilgrn->result(); 
            
            if($hasil1->num_rows()>0){
                $sup = $datanew[0]->sup_company;
            }else{$sup = "Direct GRN";}
            
            if($this->session->userdata['login_data']['userlevel'] < 6 || $this->session->userdata['login_data']['userlevel'] == 10){
                
                $pro = "<button type='button' class='btn btn-outline-secondary btn-sm' type='button' id='".$data[$i]->grn_id."'  onclick='po_proceed(this.id)' >Process</button>";
            }else{$pro="";}
                    
                   $vw_btn1 = "<a href ='".base_url()."pdf_grn/".$data[$i]->grn_id."' target='_blank'> <button type='button' class='btn btn-outline-secondary btn-sm' >View</button></a>
                               <a href ='".base_url()."edit_grn/".$data[$i]->grn_id."'> <button type='button' class='btn btn-outline-secondary btn-sm' >Edit</button></a>
                                <button type='button' class='btn btn-outline-secondary btn-sm' type='button' id='".$data[$i]->grn_id."' name='edtbutton' onclick='po_cancel(this.id)' data-target='#Modal_edit'>Cancel</button>
                              $pro
                                ";
                    $vw_btn2 = "<a href ='".base_url()."pdf_grn/".$data[$i]->grn_id."' target='_blank'> <button type='button' class='btn btn-outline-secondary btn-sm' >View</button></a>
                                
                                ";
                        
                    if($data[$i]->grn_proceed==1){
                        if($data[$i]->grn_stetus==1){
                        $sts = "<td style='color:#00800085; font-size:25px; text-align: center;'>&#9679;</td>"; $vw_btn = $vw_btn2."<br><b>".$datagrn[0]->user_name."</b>";
                        }else{
                        $sts = "<td style='color:#ff000080; font-size:25px; text-align: center;'>&#9679;</td>";  $vw_btn = $vw_btn2;}
                        
                    }else{
                        if($data[$i]->grn_stetus==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_btn2."<br><b>".$data[$i]->grn_euser."</b>";}
                        
                    }
                    if($data[$i]->grn_poid!=""){$poid = $data[$i]->grn_poid;}else{$poid="N/A";}
                    
                    $x = $i+1;
                    $dat =  "
                                 <tr scope='row'>
                                 <td >".$x."</td>
                                 <td >".$data[$i]->grn_code.$data[$i]->grn_id."</td>
                                 <td>".$sup."</td>
                                 
                                 <td>".$data[$i]->grn_invnum."</td>
                                 <td style='text-align: right;'>".$data[$i]->grn_totqty."</td>
                                <td style='text-align: right;'>".$data[$i]->grn_cdate."</td>
                                <td style='text-align: right;'>".$data[$i]->user_name."</td>
                                $sts
                                <td>$vw_btn   </td>
                               
                              
                              </tr>";
                              $x++;
                              $det[2] =$det[2].$dat;
                }
                
            
            	
           echo json_encode($det);
            //echo json_encode($data);
            
        }
        
        function view_pdf($insert_id){
            
        $this->db->select("*");    
        $this->db->from('mes_grn');
        $this->db->join( "mes_user", "mes_user.user_id = mes_grn.grn_cuser", 'left');
        $this->db->where('grn_id', $insert_id );
        $query = $this->db->get();
        $grn_q=$query->result();
        $data['inv']=$grn_q;
        
      
        
       /* if($grn_q[0]->grn_proceed > 0){
            $this->db->select("*");    
            $this->db->from('mes_inventry');
            $this->db->where('invt_type',"GRN");
            $this->db->where('invt_type_id',$insert_id);
            $this->db->join( "mes_item", "mes_item.item_id = mes_inventry.invt_itemid", 'left');
            $this->db->join( "mes_category", "mes_category.cat_id = mes_item.item_cat", 'left');
            $this->db->join( "mes_brand", "mes_brand.brand_id = mes_item.item_brand", 'left');
            $this->db->join( "mes_model", "mes_model.model_id = mes_item.item_model", 'left');
            $this->db->join( "mes_unit", "mes_unit.unit_id = mes_item.item_unit", 'left');
            $this->db->join( "item", "mes_item.item_name = item.itm_id",'left');
            $this->db->join( "mes_spec", "mes_spec.spec_id = mes_item.item_spec", 'left');
            $query = $this->db->get();
            $dataa = $query->result();
            
            $inv = []; 
            
             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]->part_no!=""){$spece2 = "  ";}else{$spece2 = "";}
                        $itm = $dataa[$i]->brand_name.$spece.$dataa[$i]->itm_name."\n".$dataa[$i]->model_name.$spece1.$dataa[$i]->spec_spec;
                        $inv[] = array($dataa[$i]->cat_shortcode,$dataa[$i]->item_catcount,$dataa[$i]->itm_name,$dataa[$i]->unit_symble,$dataa[$i]->invt_qty,$dataa[$i]->brand_shordcode); 
                    
            }
            $data['inv_itm'] =$inv;
      //  }else{}*/
      
      
                $this->db->select("grn_item.*,mes_item.*,item.*,grn_item.retail_price as rtlp");    
                $this->db->from('grn_item');
               // $this->db->where('invt_type',"GRN");
                $this->db->where('grn_id',$insert_id);
                $this->db->join( "mes_item", "mes_item.item_id = grn_item.item", 'left');
                //$this->db->join( "mes_category", "mes_category.cat_id = mes_item.item_cat", 'left');
                //$this->db->join( "mes_brand", "mes_brand.brand_id = mes_item.item_brand", 'left');
                //$this->db->join( "mes_model", "mes_model.model_id = mes_item.item_model", 'left');
               // $this->db->join( "mes_unit", "mes_unit.unit_id = mes_item.item_unit", 'left');
                $this->db->join( "item", "mes_item.item_name = item.itm_id",'left');
                //$this->db->join( "mes_spec", "mes_spec.spec_id = mes_item.item_spec", 'left');
                $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]->part_no!=""){$spece2 = "  ";}else{$spece2 = "";}
                           // $itm = $dataa[$i]->brand_name.$spece.$dataa[$i]->itm_name."\n".$dataa[$i]->model_name.$spece1.$dataa[$i]->spec_spec;
                            //$inv[] = array($dataa[$i]->cat_shortcode,$dataa[$i]->item_catcount,$dataa[$i]->itm_name,$dataa[$i]->unit_symble,$dataa[$i]->temp_grn_qty,$dataa[$i]->brand_shordcode,$dataa[$i]->brand_shordcode); 
                            
                            $inv[] = array($dataa[$i]->batch,$dataa[$i]->itm_name,$dataa[$i]->grn_qty,$dataa[$i]->bying_price,$dataa[$i]->selling_price,$dataa[$i]->rtlp,$dataa[$i]->man_date,$dataa[$i]->exp_date,); 
                        
                }
                
                $data['inv_itm'] =$inv;
        
        
        
        
           // $data['inv_itm'] =$inv;

        
        $data['tm'][0] = "";
        
                $this->db->select("*");    
                $this->db->from('mes_profile');
                $query = $this->db->get();
                $data['tm'][1] =$query->result();
      
            
            $this->load->view('pages/grnnotepdf',$data);
            
        }
        
        function showstock(){
          
            $data['content'] = "pages/allstc";        
            $this->load->view('template',$data); 
          
      }
      
        function showsalltock(){
            
            $depot = $this->input->post('depot');
          
            $this->db->select('*');
            $this->db->from('mes_stock');
            $this->db->join( "mes_item", "mes_item.item_id = mes_stock.stc_itemid", 'left');
            $this->db->join( "mes_unit", "mes_item.item_unit  = mes_unit.unit_id", 'left');
            $this->db->order_by("(stc_qty < item_moq)", "DESC");
            $this->db->order_by("(mes_item.item_id)", "ASC");
            $hasil=$this->db->get();
            $data= $hasil->result(); 
            
            
            $det[1] ="<tr>
														<th scope='col'>ID</th>
														
														<th>Product ID</th>
													
															<th>Item description</th>
														
														<th>Moq</th>
														
														
														<th>Stock Qty</th>
															<th>Bin Qty</th>
													
														<th>Action</th>
													   
                                                                                                             
																											
													</tr>";
            
          $det[2]="";
          
                for($i=0; $i<count($data); $i++){
                    
                    $pro = $this->Product_model->single_product($data[$i]->stc_itemid);
                    if($pro[0]->brand_name!=""){$spece = "  ";}else{$spece = "";} 
                   //if($pro[0]->part_no!=""){$spece2 = "  ";}else{$spece2 = "";}
                    $itm = $pro[0]->brand_name.$spece.$pro[0]->itm_name;
              
              if($this->session->userdata['login_data']['userlevel']<2){
                  $adj_btn = "<button type='button' class='btn btn-outline-secondary btn-sm' type='button' id='".$data[$i]->stc_id."/".$depot."' name='edtbutton' onclick='edit_view(this.id)' data-target='#Modal_edit'>Adjustment</button>
                                ";
              }else{
                   $adj_btn="";
              }
                
                     
                    
                    $this->db->select('sum(to_bin) as bin');
                    $this->db->from('ret_to_stock');
                    $this->db->join( "batch", "batch.batch_id = ret_to_stock.batch", 'left');
                    $this->db->where('batch.product', $data[$i]->stc_itemid);
                    $hasil=$this->db->get();
                    $bin = $hasil->result();  
                    
                   if($data[$i]->item_moq != 0 && ($data[$i]->item_moq > $data[$i]->stc_qty)){$stl = "style='background-color: #ffe8e8;'";}else{$stl = "";}
                   
                   if($bin[0]->bin>0){
                       
                       $binbutn = "<button type='button' class='btn btn-outline-secondary btn-sm' type='button' id='batch_bin/".$data[$i]->stc_itemid."' onclick='bin_view(this.id)' data-backdrop='static' data-keyboard='false' data-target='#Modal_binedit'>Bin Empty</button>";
                   }else{$binbutn ="";}
                    
                    $x = $i+1;
                    $dat =  "
                                 <tr scope='row' $stl>
                                 <td >".$x."</td>
                                 <td>".$pro[0]->cat_shortcode."-".$pro[0]->brand_shordcode."-".$pro[0]->item_catcount."</td>
                               
                                 <td>".$pro[0]->itm_name."</td>
                                 <td style='text-align: right;'><b>".$data[$i]->item_moq."</b></td>
                                
                                 
                                 <td style='text-align: right;'>".$data[$i]->stc_qty."</td>
                                 <td style='text-align: right;'>".$bin[0]->bin."</td>
                               
                                 <!--td style='text-align: right;'>".$data[$i]->stc_actqty."</td-->
                                 <td style='text-align: right;'><button type='button' class='btn btn-outline-secondary btn-sm' type='button' id='batch_product/".$data[$i]->stc_itemid."' onclick='batch_view(this.id)' data-backdrop='static' data-keyboard='false' data-target='#Modal_edit'>View</button>
                                 $binbutn
                               </td>
                             
                               
                              
                              </tr>";
                              $x++;
                              $det[2] =$det[2].$dat;
                }
                
            
            	
           echo json_encode($det);
            //echo json_encode($data);
        }
        
        function showdepo_stock(){
            
          $depot = $this->input->post('depot');
          
            $this->db->select('*');
            $this->db->from('mes_depot_stock');
            $this->db->join( "mes_item", "mes_item.item_id = mes_depot_stock.dpstock_itemid", 'left');
            $this->db->join( "mes_unit", "mes_item.item_unit  = mes_unit.unit_id", 'left');
            $this->db->where('dpstock_dpoid',$depot);
            $this->db->order_by("(mes_item.item_id)", "ASC");
            $hasil=$this->db->get();
            $data= $hasil->result(); 
            
          
            
            
            $det[1] ="<tr>
														<th scope='col'>ID</th>
														
														<th>Product ID</th>
													
															<th>Item description</th>
														
														
														
														
														<th style='text-align: right;'>Stock Qty</th>
													
														<th style='text-align: right;'>Action</th>
													   
                                                                                                             
																											
													</tr>";
            
          $det[2]="";
          
                for($i=0; $i<count($data); $i++){
                    
                    $pro = $this->Product_model->single_product($data[$i]->dpstock_itemid);
                    
                    if($pro[0]->brand_name!=""){$spece = "  ";}else{$spece = "";} 
                   //if($pro[0]->part_no!=""){$spece2 = "  ";}else{$spece2 = "";}
                    $itm = $pro[0]->brand_name.$spece.$pro[0]->itm_name;
                    
                   if($this->session->userdata['login_data']['userlevel']<2){
                  $adj_btn = "<button type='button' class='btn btn-outline-secondary btn-sm' type='button' id='".$data[$i]->dpstock_itemid."/".$depot."' name='edtbutton' onclick='edit_view(this.id)' data-target='#Modal_edit'>Adjustment</button>
                                ";
                      }else{
                           $adj_btn="";
                      }
                            
                    if($depot==0){$abtn = $ajestbtn;}else{$abtn = "";}
                    
                    
                    
             
                    $x = $i+1;
                    $dat =  "
                                 <tr scope='row'>
                                 <td >".$x."</td>
                                 <td>".$pro[0]->cat_shortcode."-".$pro[0]->brand_shordcode."-".$pro[0]->item_catcount."</td>
                               
                                 <td>".$pro[0]->itm_name."</td>
                                
                                
                                 <td style='text-align: right;'>".$data[$i]->dpstock_qty."</td>
                                 
                                 <td style='text-align: right;'><button type='button' class='btn btn-outline-secondary btn-sm' type='button' id='depobatch_product/".$data[$i]->dpstock_itemid."/".$depot."' onclick='batch_view_depo(this.id)' data-backdrop='static' data-keyboard='false' data-target='#Modal_edit'>View</button>
                             
                               
                              
                              </tr>";
                              $x++;
                              $det[2] =$det[2].$dat;
                }
                
            
            	
           echo json_encode($det);
            //echo json_encode($data);
        }
          
        function grn_auth(){
            if(!isset($this->session->userdata['login_data']['username'])) { 
                            redirect('https://newapp.nance.lk/logout'); 
                            exit();
                }
                
            $dt = explode("/",$this->input->post('id'));
            $id = $this->input->post('id');
            
            $this->db->select('*');
            $this->db->from('grn_item');
            $this->db->where('grn_id',$id);
            $this->db->where('grnitem_auth',0);
            $hasil=$this->db->get();
            $data= $hasil->result();
            
            $tot = 0;
                for($i=0; $i<count($data); $i++){
                    $this->db->select('*');
                    $this->db->from('batch');
                    $this->db->where('batch',$data[$i]->batch);
                    $this->db->where('product',$data[$i]->item);
                    $hasil1=$this->db->get();
                    $b_data= $hasil1->result();
                    
                    if($hasil1->num_rows()<1){
                        $dat = array(
                            'batch'  => $data[$i]->batch,
                            'product'  => $data[$i]->item,
                            'tot_qty'  => $data[$i]->grn_qty,
                            'avl_qty' => 0,
                            'buying_price' => $data[$i]->bying_price,
                            'selling_price' => $data[$i]->selling_price,
                            'retail_price' => $data[$i]->retail_price,
                            'man_date' => $data[$i]->man_date,
                            'exp_date' => $data[$i]->exp_date
                            
                        );
                           $this->db->insert('batch',$dat);
                            $batchid = $this->db->insert_id();
                    }else{
                        $new_tqty = $b_data[0]->tot_qty +$data[$i]->grn_qty;
                        $batchid = $b_data[0]->batch_id;
                        
                        $this->db->set('tot_qty', $new_tqty);
                        $this->db->where('batch_id',$b_data[0]->batch_id);
                        $this->db->update('batch');
                    }
                    
                    $stock = $this->Common_model->cal_stock(0,"GRN",$id,$data[$i]->item,$data[$i]->grn_qty,"plus",0,$batchid);
                
                    if($stock){ 
                        $this->db->set('grnitem_auth', 1);
                        $this->db->where('grn_itm_id',$data[$i]->grn_itm_id);
                        $this->db->update('grn_item');
                        
                    }
                    
                }
                   
                    $this->db->select('*');
                    $this->db->from('grn_item');
                    $this->db->where('grn_id',$id);
                    $this->db->where('grnitem_auth',0);
                    $hasill=$this->db->get();
                    $dett= $hasill->result();
                    
               if(count($dett)<1){
                    $this->db->set('grn_proceed', "1");
                    $this->db->set('grn_pdate', date('Y-m-d'));
                    $this->db->set('grn_puser', $this->session->userdata['login_data']['user_id']);
                    $this->db->where('grn_id',$id);
                    $this->db->update('mes_grn');
                    
                    $ret = "GRN Completed";
               }else{  $ret = "Not Completed"; }
                   
                        
                    
            echo json_encode($ret);
        }
        
        function grn_auth_old(){
            $dt = explode("/",$this->input->post('id'));
            $id = $dt[0];
            
            $this->db->select('*');
            $this->db->from('mes_inventry');
            $this->db->where('invt_type',"GRN");
            $this->db->where('invt_type_id',$id);
            $this->db->where('invt_proc',0);
            $hasil=$this->db->get();
            $data= $hasil->result(); 
            
            for($i=0; $i<count($data); $i++){
                    //echo $data[$i]->invt_qty;
                    $this->Common_model->cal_stock_no_inventry(0,"GRN",$data[$i]->invt_id,$data[$i]->invt_itemid,$data[$i]->invt_qty,"plus","0");
                    
                    $this->db->set('invt_proc', "1");
                    $this->db->where('invt_type',"GRN");
                    $this->db->where('invt_id',$data[$i]->invt_id);
                    $this->db->update('mes_inventry');
            }
            
                    $this->db->set('grn_proceed', "1");
                    $this->db->set('grn_pdate', date('Y-m-d'));
                    $this->db->set('grn_puser', $this->session->userdata['login_data']['username']);
                    $this->db->where('grn_id',$id);
                   $this->db->update('mes_grn');
                    
                   
                        $ret = "GRN Completed";
                    
                    
            
            echo json_encode($ret);
        }
        
        function grnnote_cancel(){
            
            if(!isset($this->session->userdata['login_data']['user_id'])) { 
                
                        redirect('Login_controller'); 
                        exit();
            }
            
            //$this->db->where('grn_itm_id', $product_code);
            $this->db->where('user', $this->session->userdata['login_data']['user_id']);
            $this->db->delete('temp_grn_item');
            
            $data = "Invoice Canceled";
        echo json_encode($data);
            
            
        }
        
        function view_ajest(){
            
      $id = $this->input->post('id');
      $depoid = $this->input->post('depoid');
      
      if($depoid=="0"){
          
               $this->db->select("*");    
                $this->db->from('mes_stock');
                $this->db->where('stc_id',$id);
                $query = $this->db->get();
                $data =$query->result();
            
            
            
              $det="
             <div class='form-group row'>
               <input type='hidden' name='data_id' id='data_id' class='form-control' readonly='' value='".$data[0]->stc_id."'>
               <input type='hidden' name='peort_id' id='peort_id' class='form-control' readonly='' value='".$depoid."'>
             
                                <label class='col-md-2 col-form-label'>Stock Qty</label>
                                <div class='col-md-10'>
                                  <input type='text' name='tax_name' id='tax_name' class='form-control' placeholder='' value='".$data[0]->stc_qty."' readonly>
                                 </div>
                            </div>
                          <div class='form-group row'>
                                <label class='col-md-2 col-form-label'>New Stock</label>
                                <div class='col-md-10'>
                                  <input type='text' name='qty_value' id='qty_value' class='form-control' placeholder=''>
                                 </div>
                            </div>
                            
                             <div class='form-group row'>
                                <label class='col-md-2 col-form-label'>Reason</label>
                                <div class='col-md-10'>
                                  <input type='text' name='tmp_reason' id='tmp_reason' class='form-control' placeholder=''>
                                 </div>
                            </div>
                           
                        
              ";
      }else{
          
              $this->db->select("*");    
                $this->db->from('mes_depot_stock');
                $this->db->where('dpstock_itemid',$id);
                $this->db->where('dpstock_dpoid',$depoid);
                $query = $this->db->get();
                $data =$query->result();
            
            
            
              $det="
             <div class='form-group row'>
               <input type='hidden' name='data_id' id='data_id' class='form-control' readonly='' value='".$data[0]->dpstock_itemid."'>
                <input type='hidden' name='peort_id' id='peort_id' class='form-control' readonly='' value='".$depoid."'>
             
                                <label class='col-md-2 col-form-label'>Stock Qty</label>
                                <div class='col-md-10'>
                                  <input type='text' name='tax_name' id='tax_name' class='form-control' placeholder='' value='".$data[0]->dpstock_qty."' readonly>
                                 </div>
                            </div>
                          <div class='form-group row'>
                                <label class='col-md-2 col-form-label'>New Stock</label>
                                <div class='col-md-10'>
                                  <input type='text' name='qty_value' id='qty_value' class='form-control' placeholder=''>
                                 </div>
                            </div>
                            
                             <div class='form-group row'>
                                <label class='col-md-2 col-form-label'>Reason</label>
                                <div class='col-md-10'>
                                  <input type='text' name='tmp_reason' id='tmp_reason' class='form-control' placeholder=''>
                                 </div>
                            </div>
                           
                        
              ";
          
      }
      
      
           
                        
                	
               echo json_encode($det);	
        }
        
        function update_ajest(){
                
                 
            
                $this->form_validation->set_error_delimiters('', ''); 
                $this->form_validation->set_rules('tmp_reason', 'Reason', 'required');
                $this->form_validation->set_rules('qty_value', 'Stock Qty', 'trim|numeric|required');
                
                
             $ret = "";
                if ($this->form_validation->run() == FALSE){
                    //$ret = validation_errors();
                    $ret = "error";
    	   }else{
    	       
    	        $id = $this->input->post('data_id');
    	        $depoid = $this->input->post('peort_id');
    	        
    	       
    	        $this->db->from('mes_stock');
                $this->db->where('stc_id',$id);
                $query = $this->db->get();
                $data =$query->result();
                
                $this->db->from('mes_depot_stock');
                $this->db->where('dpstock_itemid',$id);
                $this->db->where('dpstock_dpoid',$depoid);
                $querydp = $this->db->get();
                $datadepo =$querydp->result();
                
                if($depoid=="0"){$ajqty = $data[0]->stc_qty;}else{$ajqty = $datadepo[0]->dpstock_qty;}
    	       
    	       //$stkvaldef = $this->input->post('qty_value') - $ajqty ;
    	        //$newstk = $stkvaldef - $data[0]->stc_qty;
    	        //$newalvstk = $ajaqty + $stkvaldef ;
    	        
    	        if($depoid=="0"){
    	            
    	            $this->db->set('stc_qty', $this->input->post('qty_value'));
    	            $this->db->set('stc_actqty', $this->input->post('qty_value'));
                    $this->db->where('stc_id', $id);
                    $result=$this->db->update('mes_stock');
                    
    	        }else{
    	            
    	            $this->db->set('dpstock_qty', $this->input->post('qty_value'));
                    $this->db->where('dpstock_itemid', $id);
                    $this->db->where('dpstock_dpoid',$depoid);
                    $result=$this->db->update('mes_depot_stock');
    	        }
    	        
    	       
                
                
                if($result){
                    
                    
                    $dat2 = array(
                        'adjs_itmid '  => $id,
                        'adjs_depoid'  => $depoid,
                        'adjs_qty'  => $this->input->post('qty_value'),
                        'adjs_user'  => $this->session->userdata['login_data']['username'],
                        'adjs_curntqty'  => $ajqty,
                        'adjs_reson'  => $this->input->post('tmp_reason')
                        
                    );
                    $dataadju = $this->db->insert('mes_stockadjust',$dat2);
                    $insert_id = $this->db->insert_id();
                    //$this->Common_model->cal_stock("","",$id,$stkvaldef,"plus","0");
                    
                        $dat = array(
                            'invt_type'  => "SAJ",
                            'invt_type_id'  => "",
                            'invt_itemid'  => $id,
                            'invt_qty'  => $this->input->post('qty_value'),
                            'cal'  => "add",
                            'invt_proc'  => 1
                        );
                        $data = $this->db->insert('mes_inventry',$dat);
                    $ret= "Stock Details Updated";
                }else{
                    $ret= "Please Re enter all details";
                }
    	   }
        
    	    //$ret[1] = "get_tax";
    	    echo json_encode($ret);	
    	}
        
        function cancel_grn_old(){
            $id = $this->input->post('id');
            
            $this->db->select('*');
            $this->db->from('mes_inventry');
            $this->db->where('invt_type',"GRN");
            $this->db->where('invt_type_id',$id);
            $this->db->where('invt_proc',0);
            $hasil=$this->db->get();
            $data= $hasil->result(); 
            
            for($i=0; $i<count($data); $i++){
                    $this->db->set('invt_proc', "0");
                    $this->db->where('invt_type',"GRN");
                    $this->db->where('invt_type_id',$data[$i]->invt_id);
                    $this->db->update('mes_inventry');
                    
                    
                    
                    
            }
            
                    $this->db->set('grn_proceed', "0");
                    $this->db->set('grn_stetus', "0");
                    $this->db->set('grn_euser', $this->session->userdata['login_data']['username']);
                    $this->db->set('grn_edate', date('Y-m-d'));
                    
                    $this->db->where('grn_id',$id);
                    $this->db->update('mes_grn');
                    
                    
                        $ret = "GRN Canceled";
                   
             echo json_encode($ret);
        }
        
        function cancel_grn(){
            $id = $this->input->post('id');
            
           // $this->db->select('*');
           // $this->db->from('temp_grn_itms');
           // $this->db->where('grn_id',$id);
            //$hasil=$this->db->get();
            //$data= $hasil->result(); 
            
                    // $this->db->where('grn_id', $id);
                     //$data=$this->db->delete('temp_grn_itms');
            
            
                    $this->db->set('grn_proceed', "0");
                    $this->db->set('grn_stetus', "0");
                    $this->db->set('grn_euser', $this->session->userdata['login_data']['user_id']);
                    $this->db->set('grn_edate', date('Y-m-d'));
                    
                    $this->db->where('grn_id',$id);
                    $this->db->update('mes_grn');
                    
                    
                        $ret = "GRN Canceled";
                   
             echo json_encode($ret);
        }
        
        // add one by one items to a table
        
        function add_grn_item(){
            if(!isset($this->session->userdata['login_data']['username'])) { 
                
                        redirect('login'); 
                        exit();
            }
            
            $depo_id = $this->input->post('depo_id');
            $tritm = $this->input->post('tritm');
            $qty = $this->input->post('qty');
            $grnuid = trim($this->input->post('grnuid'));
            
            
                $this->form_validation->set_error_delimiters('', ''); 
                $this->form_validation->set_rules('sprice', 'Selling Price', 'trim|required|decimal');
                $this->form_validation->set_rules('rprice', 'Retail Price', 'trim|required|decimal|greater_than[$sprice]');
                $this->form_validation->set_rules('batch_code', 'Batch Code', 'trim|required');
                $this->form_validation->set_rules('qty', 'Quantity', 'trim|required|numeric');
                $this->form_validation->set_rules('item', 'Item', 'trim|required');
                
                
             $data['Added'] = "";
             
            if ($this->form_validation->run() == FALSE){
                    //$ret = validation_errors();
                    $data['Added'] = validation_errors();
    	   }else{
    	       
    	       
    	    $this->db->select('item_exp');
            $this->db->from('mes_item');
            $this->db->where('item_id', $this->input->post('item'));
            $hasile=$this->db->get();
            $expdt= $hasile->result(); 
    	       
    	       $exp = strtotime($this->input->post('exp'));
    	       $mfd = strtotime($this->input->post('grn_mfd'));
    	       
    	       if( ($expdt[0]->item_exp=="1") && ($exp <= $mfd) ){
    	           $data['Added'] = "Please change EXP Date";
    	           
    	       }else{
    	           
    	           if($qty!=0){
               $dat = array(
                'grn_qty' => $this->input->post('qty'),
                'bying_price' => $this->input->post('bprice'),
                'retail_price' => $this->input->post('rprice'),
                'selling_price' => $this->input->post('sprice'),
                'batch' => trim(strtoupper($this->input->post('batch_code'))),
                'exp_date' => $this->input->post('exp'),
                'man_date'  => $this->input->post('grn_mfd'), 
                'item'  => $this->input->post('item'),
                //'grn_id'  => $uid,
                'user' => $this->session->userdata['login_data']['user_id'],
                'date'  => date("Y-m-d")
                 );
                $detail = $this->db->insert('temp_grn_item',$dat);
                
                $data['Added'] = "Added";
                //$data['uid'] = $uid;
            } 
    	       }
    	       
    	         
            
                
    	   }
           
            echo json_encode($data);
        
        }
        
        function getgrnitm() {     
         if(!isset($this->session->userdata['login_data']['username'])) { 
                    
                            redirect('Login_controller'); 
                            exit();
                }
            $this->db->select("temp_grn_item.*,item.*,temp_grn_item.retail_price as ret");
            $this->db->from('temp_grn_item');
            $this->db->join('mes_item', 'temp_grn_item.item   = mes_item.item_id','left');
            $this->db->join('item', 'item.itm_id   = mes_item.item_name','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->join( "mes_user", "temp_grn_item.user = mes_user.user_id",'left');
            $this->db->where('temp_grn_item.user', $this->session->userdata['login_data']['user_id']);
            $hasil=$this->db->get();
            $dataa = $hasil->result();
            
             for($i=0; $i<count($dataa); $i++){
                 
                        $itm = $dataa[$i]->itm_name;
                        $data[] = array($dataa[$i]->batch,$itm,$dataa[$i]->bying_price,$dataa[$i]->selling_price,$dataa[$i]->ret,$dataa[$i]->grn_qty,$dataa[$i]->exp_date,$dataa[$i]->man_date,$dataa[$i]->grn_itm_id ); 
                    
            }
            if(!empty($data)){$data;}else{$data="";}
           
             echo json_encode($data);
        }
    
        function prodelete(){
       if(!isset($this->session->userdata['login_data']['username'])) { 
                
                        redirect('Login_controller'); 
                        exit();
            }
        
                    $this->db->select('*');
                    $this->db->from('temp_grn_item');
                    $this->db->where('grn_itm_id',$this->input->post('product_code'));
                    $hasil=$this->db->get();
                    $qto_itm= $hasil->result();
                    
      
        $product_code=$this->input->post('product_code');
        if($product_code!=""){
            $this->db->where('grn_itm_id', $product_code);
            $this->db->where('user', $this->session->userdata['login_data']['user_id']);
            $data=$this->db->delete('temp_grn_item');
        }
        
       
                
        $data = "Item Removed";
        echo json_encode($data);
    
        }
        
        function editprodelete(){
       if(!isset($this->session->userdata['login_data']['username'])) { 
                
                        redirect('Login_controller'); 
                        exit();
            }
        
                    $this->db->select('*');
                    $this->db->from('grn_item');
                    $this->db->where('grn_itm_id',$this->input->post('product_code_delete'));
                    $hasil=$this->db->get();
                    $qto_itm= $hasil->result();
                    
                   
                    
      
        $product_code=$this->input->post('product_code_delete');
        
          if($product_code!=""){
            
            $this->db->where('grn_itm_id', $product_code);
            //$this->db->where('temp_grn_user', $this->session->userdata['login_data']['username']);
            $data=$this->db->delete('grn_item');
            
                    $this->db->select('sum(grn_qty) as nqty');
                    $this->db->from('grn_item');
                    $this->db->where('grn_id',$qto_itm[0]->grn_id);
                    $hasil=$this->db->get();
                    $tot_itm= $hasil->result();
            
            
                $this->db->set('grn_euser', $this->session->userdata['login_data']['user_id']);
                $this->db->set('grn_edate', date("Y-m-d"));
                $this->db->set('grn_totqty', $tot_itm[0]->nqty);
                $this->db->where('grn_id', $qto_itm[0]->grn_id);
                $result=$this->db->update('mes_grn');
                
             
        
     
                
                $data = "Item Removed"; 
         }
        
        echo json_encode($data);
    
        }
        
        function product_delete(){
       if(!isset($this->session->userdata['login_data']['username'])) { 
                
                        redirect('Login_controller'); 
                        exit();
            }
        
               
      
        $product_code=$this->input->post('product_code');
        if($product_code!=""){
            
                    $this->db->select('grn_id');
                    $this->db->from('temp_grn_itms');
                    $this->db->where('temp_grn_auid',$this->input->post('product_code'));
                    $hasil=$this->db->get();
                    $qto_itm= $hasil->result();
                    
                     $this->db->where('temp_grn_auid', $product_code);
                     $data=$this->db->delete('temp_grn_itms');
                    
                    $this->db->select('sum(temp_grn_qty) as nqty');
                    $this->db->from('temp_grn_itms');
                    $this->db->where('grn_id',$qto_itm[0]->grn_id);
                    $hasil=$this->db->get();
                    $tot_itm= $hasil->result();
            
                $this->db->set('grn_totqty', $tot_itm[0]->nqty);
                $this->db->where('grn_id', $qto_itm[0]->grn_id);
                $result=$this->db->update('mes_grn');
        }
        
       
                
        $data = "Item Removed";
        echo json_encode($data);
    
        }
        
        function transer_save_old(){
            
           $this->db->select('*');
            $this->db->from('temp_grn_itms');
            $this->db->where('temp_grn_user',$this->session->userdata['login_data']['username']);
            $hasil=$this->db->get();
            $data= $hasil->result(); 
            
            if(count($data)>0){
               
                    $dat = array(
                        'grn_poid'  => "",
                        'grn_totqty'  => 0,
                        'grn_cuser'  => $this->session->userdata['login_data']['username'],
                        'grn_cdate'  => date('Y-m-d')
                        
                    );
                    
                    $this->db->insert('mes_grn',$dat);
                    $insert_id = $this->db->insert_id();
            }
            
          $tot = 0;
           for($i=0; $i<count($data); $i++){
               
               $dat = array(
                        'invt_type'  => "GRN",
                        'invt_type_id'  => $insert_id,
                        'invt_itemid'  => $data[$i]->temp_grn_item,
                        'invt_qty' => $data[$i]->temp_grn_qty,
                        'buy_price' => $data[$i]->temp_grn_itmprice,
                        'exp_date' => $data[$i]->temp_grn_exp,
                        'invt_proc' =>'0',
                        'cal' =>'plus',
                        'invt_cuser'  => $this->session->userdata['login_data']['username'],
                        'invt_cdate'  =>date('Y-m-d')
                        
                    );
                    $this->db->insert('mes_inventry',$dat);
                    $invinsert_id = $this->db->insert_id();
                    $tot = $tot + $data[$i]->temp_grn_qty;
               
                $this->db->where('temp_grn_auid', $data[$i]->temp_grn_auid);
                $this->db->where('temp_grn_user', $this->session->userdata['login_data']['username']);
                $del=$this->db->delete('temp_grn_itms');
               
           }
           
            $this->db->set('grn_totqty', $tot);
            $this->db->where('grn_id', $insert_id);
            $result=$this->db->update('mes_grn');
           
      
            $send = "GRN Note Created";
            echo json_encode($send);
        }  
        
        function transer_save(){
            
            $this->db->select('*');
            $this->db->from('temp_grn_item');
            $this->db->where('user',$this->session->userdata['login_data']['user_id']);
            $hasil=$this->db->get();
            $data= $hasil->result(); 
            
            $this->db->select_sum('grn_qty','total');
            $this->db->where('user',$this->session->userdata['login_data']['user_id']);
            $query = $this->db->get('temp_grn_item');
            $res = $query->row_array();
            //now SUM is available in $res['total']
            $grntot =  $res['total'];
            
            
            
            if(count($data)>0){
               
                    $dat = array(
                        'grn_poid'  => "",
                        'grn_totqty'  => $grntot,
                        'grn_cuser'  => $this->session->userdata['login_data']['user_id'],
                        'grn_cdate'  => date('Y-m-d')
                        
                    );
                    
                    $this->db->insert('mes_grn',$dat);
                    $insert_id = $this->db->insert_id();
            }
            
          $tot = 0;
           for($i=0; $i<count($data); $i++){
               
               $dat = array(
                        'grn_id'  => $insert_id,
                        'batch'  => $data[$i]->batch,
                        'item'  => $data[$i]->item,
                        'grn_qty'  => $data[$i]->grn_qty,
                        'bying_price'  => $data[$i]->bying_price,
                        'selling_price'  => $data[$i]->selling_price,
                        'retail_price'  => $data[$i]->retail_price,
                        'man_date'  => $data[$i]->man_date,
                        'exp_date'  => $data[$i]->exp_date,
                        'user'  => $data[$i]->user,
                        'date'  => $data[$i]->date
                        
                    );
                    
                    $this->db->insert('grn_item',$dat);
                    
                    
                    $this->db->where('user',$this->session->userdata['login_data']['user_id']);
                    $this->db->delete('temp_grn_item');
                    
                    
               
               
                //$this->db->set('grn_id', $insert_id);
                //$this->db->where('grn_id', $insert_id);
                //$this->db->where('temp_grn_auid', $data[$i]->temp_grn_auid);
                //$this->db->where('temp_grn_user', $this->session->userdata['login_data']['user_id']);
                //$result=$this->db->update('temp_grn_itms');
                
                //$tot = $tot + $data[$i]->temp_grn_qty;
           }
           
            //$this->db->set('grn_totqty', $tot);
            //$this->db->where('grn_id', $insert_id);
           // $result=$this->db->update('mes_grn');
           
      
            $send = "GRN Note Created";
            echo json_encode($send);
        }   
        
        function edit_view($id){
            
                    
                    $this->db->select('*');
                    $this->db->from('grn_item');
                   // $this->db->where('temp_grn_user',$this->session->userdata['login_data']['username']);
                    $this->db->where('grn_id',$id);
                    $hasil=$this->db->get();
                    $grn_itm= $hasil->result();
                   
                  $count =   count($grn_itm);
               if(count($grn_itm)<1){
                   redirect('view_grn');
               }else{
                   $data['content'] = "pages/edit_grn";        
                   $data['id'] = $id; 
                   $data['count'] = $count;
                   
                     $this->load->view('template',$data); 
               }     
                    
        }
        
        function get_inv_grn(){
            
            $id = $this->input->post('id');
            
            $this->db->select("grn_item.*,item.*,mes_item.*,grn_item.retail_price as ret");
            $this->db->from('grn_item');
            $this->db->join('mes_item', 'grn_item.item   = mes_item.item_id','left');
            $this->db->join('item', 'item.itm_id   = mes_item.item_name','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('mes_inventry.invt_type', "GRN");
            $this->db->where('grn_item.grn_id', $id);
            $hasil=$this->db->get();
            $dataa = $hasil->result();
            
             for($i=0; $i<count($dataa); $i++){
                 
                        $itm = $dataa[$i]->itm_name;
                        $data[] = array($dataa[$i]->batch,$itm,$dataa[$i]->bying_price,$dataa[$i]->selling_price,$dataa[$i]->ret,$dataa[$i]->grn_qty,$dataa[$i]->man_date,$dataa[$i]->exp_date,$dataa[$i]->grn_itm_id); 
                    
            }
            if(!empty($data)){$data;}else{$data="";}
           
             echo json_encode($data);   
                    
        }
        
        function get_edit_grn(){
            
            $id = $this->input->post('id');
            
            $this->db->select("grn_item.*,item.*,mes_item.*,grn_item.retail_price as ret");
            $this->db->from('grn_item');
            $this->db->join('mes_item', 'grn_item.item   = mes_item.item_id','left');
            $this->db->join('item', 'item.itm_id   = mes_item.item_name','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('mes_inventry.invt_type', "GRN");
            $this->db->where('grn_item.grn_itm_id', $id);
            $hasil=$this->db->get();
            $dataa = $hasil->result();
            
             for($i=0; $i<count($dataa); $i++){
                 
                        //$itm = $dataa[$i]->brand_shordcode."-".$dataa[$i]->cat_shortcode."-".$dataa[$i]->item_catcount."-".$dataa[$i]->itm_name;
                        $data[] = array($dataa[$i]->batch,$dataa[$i]->grn_qty,$dataa[$i]->bying_price,$dataa[$i]->selling_price,$dataa[$i]->ret,$dataa[$i]->man_date,$dataa[$i]->exp_date,$dataa[$i]->grn_id,$dataa[$i]->grn_itm_id); 
                    
            }
            if(!empty($data)){$data;}else{$data="";}
           
          // $this->db->select('sum(temp_grn_qty) as nqty');
                    //$this->db->from('temp_grn_itms');
                   // $this->db->where('grn_id',$dataa[0]->grn_id);
                   // $hasil=$this->db->get();
                   // $tot_itm= $hasil->result();
            
               // $this->db->set('grn_totqty', $tot_itm[0]->nqty);
               // $this->db->where('grn_id', $dataa[0]->grn_id);
               // $result=$this->db->update('mes_grn');
           
             echo json_encode($data);   
                    
        }
        
        function updte_grn_item(){
            $bid = $this->input->post('product_code_delete');
            $gid = $this->input->post('prod_grn');
            
              $this->form_validation->set_error_delimiters('', ''); 
                $this->form_validation->set_rules('prod_code', 'Batch Code', 'trim|required');
                $this->form_validation->set_rules('product_code_delete', 'ID', 'trim|required');
                $this->form_validation->set_rules('prod_price', 'Buying Price', 'trim|required');
                $this->form_validation->set_rules('prod_sprice', 'Selling Price', 'trim|required');
                $this->form_validation->set_rules('prod_rprice', 'Retail Price', 'trim|required');
                $this->form_validation->set_rules('prod_qty', 'GRN Qty', 'trim|numeric|required');
                $this->form_validation->set_rules('prod_exp', 'GRN Exp', 'required');
                
                
             $ret = "";
                if ($this->form_validation->run() == FALSE){
                    //$ret = validation_errors();
                    $ret = "error";
    	   }else{
    	       
    	        $this->db->set('batch', trim($this->input->post('prod_code')));
    	        $this->db->set('grn_qty', trim($this->input->post('prod_qty')));
                $this->db->set('bying_price', trim($this->input->post('prod_price')));
                $this->db->set('selling_price', trim($this->input->post('prod_sprice')));
                $this->db->set('retail_price', trim($this->input->post('prod_rprice')));
                $this->db->set('man_date', trim($this->input->post('prod_map')));
                $this->db->set('exp_date', trim($this->input->post('prod_exp')));
                $this->db->where('grn_itm_id', $bid);
                $result=$this->db->update('grn_item');
                
                $ret = "Saved";
                
                $this->db->select('sum(grn_qty) as nqty');
                    $this->db->from('grn_item');
                    $this->db->where('grn_id',$gid);
                    $hasil=$this->db->get();
                    $tot_itm= $hasil->result();
            
               $this->db->set('grn_totqty', $tot_itm[0]->nqty);
               $this->db->where('grn_id',$gid);
               $result=$this->db->update('mes_grn');
            
               
    	   }
            
           echo json_encode($ret);  
            
        }
        
}