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

class Purchases extends CI_Controller {
	
    var $main_menu_name = "purchases";
	  var $sub_menu_name = "categories";

      function __construct() 
      {
        parent::__construct();
        $this->load->model('purchases_model');
        $this->load->model('common_model');
		$this->load->model('Sequerty_Model');
        $this->load->library('form_validation');
		$this->load->model('User_Model');
		$this->load->model('Sales_Model');
		$this->load->model('Supplier_Model');
		$this->load->model('product_models');
		$this->load->model('Warehouse_Model');
		$this->load->model('category_models');
			$this->load->model('Report_Model');
		
		
      }

    public function index($e=0)
    {
		//if (!$this->User_Model->is_logged_in_k()) {
			//$this->User_Model->checkLoginPanel_k();
		//}
      $data['error'] = $e;
      $data['main_menu_name'] = $this->main_menu_name;
      $data['sub_menu_name'] = "list_purchases";
	  $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
      $this->load->view('purchases_list',$data);
    }
    
    
public function purchase_details()
	{
	    
	   // echo "test";
	   // die();
		$purchase_type = 0;
		$purchase_id=$this->input->get('purchase_id');
		$purchase_type = $this->input->get('type');
		if($this->input->get('status') != null){
             $data['print_without_serial'] = 'yes';
        }
				
		$data['purchase_id']=$purchase_id;
		$data['purchase_details']=$this->purchases_model->get_purchase_info($purchase_id);
		$data['purchase_type'] =$purchase_type;
		$data['purchase_item_list']= $this->purchases_model->get_purchase_item_list_by_purchase_id($purchase_id);
		$data['supplier_details']= $this->Supplier_Model->get_supplier_info($data['purchase_details']['supplier_id']);
		$data['warehouse_details']= $this->Warehouse_Model->get_warehouse_info($data['purchase_details']['warehouse_id']);
		$data['po_paid_total'] = $this->purchases_model->grn_pay_total($purchase_id);
		//$data['sale_payments_list']= $this->Sales_Model->get_sale_payments_by_sale_id($sale_id);
		
		
        $this->load->view('models/view_purchase',$data);
	}
	
	public function update_serial_no_by_id(){
	    $val=$this->input->post('val');
		$updated_val=$this->input->post('updated_val');
		$old_val=$this->input->post('old_val');
		$id=$this->input->post('id');
		
		$data = array(
			'pis_number' =>$updated_val
		);

	if($this->purchases_model->change_manual_setlmnt_status($val,$data)) {

  echo json_encode(array('status'=>1));
  
  $this->common_model->add_user_activitie("Serial No Updated, GRN:$id , OLD SN:$old_val New SN: $updated_val");

  } else {

   echo json_encode(array('status'=>0));

        }	
	}
	
	public function add_serial_no()
    {
        $data['row'] = $this->uri->segment(3);
		 $data['qty'] = $this->uri->segment(4);
		  $product_des = $this->uri->segment(5);
		  //product_models
		  //$product_des='..';
		  /*
		  if(($product_id)){
		  $product_des=$this->product_models->get_product_by_id($product_id);
		   $product_des=$product_des->product_code." ".$product_des->product_name;
		  }
		  */
		      $data['product_dis_name']=$product_des;
		  
		//echo "test:".$this->uri->segment(3);
		 $data['btnText'] = 'Submit';
        $this->load->view('models/serial_no_add',$data);
    }

    public function get_list_purchases($value='')
    {
           $search_key = $this->input->get('search');
        $search_key_val = $search_key['value'];
        $start = $this->input->get('start');
        $length = $this->input->get('length');
		$warehouse_id = $this->input->get('warehouse_id');
		$search_key1=$this->input->get('search_key1');
		$srh_to_date=$this->input->get('srh_to_date');
		$srh_from_date=$this->input->get('srh_from_date');
		 // echo "search_key1:$search_key1";
        $values = '';
        $totalData = 0;
        if ($search_key_val) {
            //if(strlen($search_key_val) > 2)
            {
                $values = $this->purchases_model->getpurchases($start, $length, $search_key_val,$warehouse_id,$search_key1,$srh_from_date,$srh_to_date);
                $values_count = $this->purchases_model->getpurchases('', '', $search_key_val,$warehouse_id,$search_key1,$srh_from_date,$srh_to_date);
                $totalData = count($values_count);
            }
        } else {
            $values = $this->purchases_model->getpurchases($start, $length, '',$warehouse_id,$search_key1,$srh_from_date,$srh_to_date);
            $values_count = $this->purchases_model->getpurchases('', '', '',$warehouse_id,$search_key1,$srh_from_date,$srh_to_date);
            if(($values))
            $totalData = count($values_count);
        }
        $totalFiltered = $totalData;
        //echo 'total:'.$totalFiltered;
        $i = 0; //START FROM HERE
        $data = array();
        $pay_st;
            if (!empty($values)) {
                foreach ($values as $purchases) {
                    
                    
                    $grn_total_paid=0;
                $grn_total_paid = $this->purchases_model->get_total_paid_by_grn_id($purchases->id);
                
                if (empty($grn_total_paid)) {
                  $pay_st = '<span class="label label-warning">Pending</span>';
                }else{
                  if ($grn_total_paid >= $purchases->grand_total) {
                    $pay_st = '<span class="label label-success">Paid</span>';
                  }else{
                    $pay_st = '<span class="label label-info">Partial</span>';
                  }
                }
                
                

                $row = array();
                    $row[] = $purchases->date;
                    $row[] = $purchases->reference_no;
					 $row[] = $purchases->name;
                    $row[] = $purchases->supp_company_name;
					$row[] = $purchases->supp_invocie_no;
                    $row[] = number_format($purchases->grand_total,2,'.',',');
                    $row[] = number_format($grn_total_paid,2,'.',',');
                    $row[] = number_format($purchases->grand_total - $grn_total_paid,2,'.',',');
                    $row[] = $pay_st;
                    $row[] = '<div class="text-center"><div class="btn-group text-left">
                    <button data-toggle="dropdown" class="btn btn-default btn-xs btn-primary dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                    <ul role="menu" class="dropdown-menu pull-right">
                    <li><a href="'.base_url('purchases/view/'.$purchases->id).'"><i class="fa fa-file-text-o"></i> GRN Details</a></li>
					 
                    </ul></div>
                    </div>';
                    $data[] = $row;
                }
                
                /*
                <li><a href="'.base_url('purchase_return/manage/'.$purchases->id).'"><i class="fa fa-file-text-o"></i> Return GRN</a></li>
                */

               $output = array(
                'recordsTotal' => $totalData,
                'recordsFiltered' => $totalFiltered,
                'data' => $data);
            echo json_encode($output);
        }else {
            $output = array('recordsTotal' => '',
                'recordsFiltered' => '',
                'data' => '');
            echo json_encode($output);
        }
       }





    public function add_purchases()
    {
		//if (!$this->User_Model->is_logged_in_k()) {
		//	$this->User_Model->checkLoginPanel_k();
		//}
      $data['main_menu_name'] = $this->main_menu_name;
      $data['sub_menu_name'] = 'add_purchases';
      $data['warehouse'] = $this->purchases_model->get_warehouse();
      $data['supplier'] = $this->purchases_model->get_supplier();
	  $data['category_list'] 	= $this->category_models->getCategory();

      if (isset($_POST['submit'])) {

              $this->form_validation->set_rules('supplier', 'supplier', 'required');

              if ($this->form_validation->run() == FALSE)
              {
                $this->load->view('purchases',$data);
              }
              else
              {
                $podate       = $this->input->post('podate');
                // $reference_no = $this->input->post('reference_no');
				
				//get next grn no
				//$warehouse_last_id=(1+$this->purchases_model->get_next_ref_no());
				//$reference_no ='GRN'.sprintf("%04d",$warehouse_last_id);
				
				 $powarehouse  = $this->input->post('powarehouse'); 
				 $warehouse_id=$powarehouse;
				//start get next referance no
				$warehouse_dtls=$this->Warehouse_Model->get_warehouse_info($warehouse_id);
				$warehouse_code=$warehouse_dtls['code'];
				$warehouse_last_id=(1+$this->purchases_model->get_next_warehouse_ref_no($warehouse_id));
				$reference_no =$warehouse_code.'/GRN/'.sprintf("%04d",$warehouse_last_id);
				//end get next referance no
				
                $supplier     = $this->input->post('supplier');
                $discount     = $this->input->post('discount');
                $powarehouse  = $this->input->post('powarehouse'); 
                $note         = $this->input->post('note');
                $grand_total  = $this->input->post('hgtotal');
                $total        = $this->input->post('total');
                $order_cal_des= $this->input->post('order_cal_des');
				$supp_invocie_no= $this->input->post('supp_invocie_no');
				$poaddition     = $this->input->post('poaddition');
				
			//	echo "poaddition:$poaddition ,";

                $grn_header_id = $this->purchases_model->add_grn_header($podate,$reference_no,$supplier,$discount, $powarehouse,$note , $grand_total,$total,$order_cal_des,$supp_invocie_no,$warehouse_last_id,$poaddition);

                if ($grn_header_id) {
                    $product_id_array       = $this->input->post('product_id');
                    $product_array          = $this->input->post('product');
                    $product_name_array     = $this->input->post('product_name');
                    $unit_cost_array        = $this->input->post('unit_cost');
					 $product_price_array        = $this->input->post('product_price');
                    $quantity_array         = $this->input->post('quantity');
                    $product_discount_array = $this->input->post('product_discount');
					$product_sn_array = $this->input->post('product_sn');
					$product_w_array = $this->input->post('product_w');
                    $gross_total            = $this->input->post('gross_total');
                    $sub_total              = $this->input->post('subtotal');
					$product_sn_exissts_array = $this->input->post('product_sn_exissts');
					$pis_min_cash_price_array=$this->input->post('pis_min_cash_price');
					
					//print_r($product_sn_array);
					//die();
                    $discount_cal           = $this->input->post('discount_cal');
                  //echo count($product_array);
                  //die();
                  for ($i=0; $i <count($product_array); $i++) { 
				  
				 
				    $this->purchases_model->add_grn_list_item(intval($product_id_array[$i]), $grn_header_id,$product_array[$i], $product_name_array[$i], $unit_cost_array[$i], $quantity_array[$i], $product_discount_array[$i],$gross_total,$sub_total[$i],$discount_cal[$i], intval($product_w_array[$i]));
					$purchase_item_id=$this->db->insert_id();
                    $this->common_model->add_fi_table("grn",$grn_header_id,$product_id_array[$i],$quantity_array[$i],$unit_cost_array[$i]);
					
					//add GRN item item cost
					$this->product_models->update_product_cost($product_id_array[$i],$unit_cost_array[$i]);
					//end add GRN item cost
					
					
					//add serial numbers
					//exploid serial numbers
					if($product_sn_exissts_array[$i]){
					$pieces_sn = explode(",", $product_sn_array[$i]);
					for($h=0; $h<count($pieces_sn); $h++){
						$sn_data=array(
							'product_id'=>intval($product_id_array[$i]),	
							'purchase_id'=>$grn_header_id,
							'purchase_item_id'=>$purchase_item_id,
							'pis_number'=>$pieces_sn[$h],
							'product_w'=>intval($product_w_array[$i]),
							'pis_cost_price'=>floatval($unit_cost_array[$i]),
							'product_avalable'=>1,
							'avalable_warehouse_id'=>$powarehouse,
							'pis_cash_price'=>floatval($product_price_array[$i]),
							'pis_min_cash_price'=>floatval($pis_min_cash_price_array[$i]),
							
						);
						
						//print_r($sn_data);
				  		$this->purchases_model->save_grn_serial_numbers($sn_data);
					}
					}
                    //end add serial numbers
				  
                  }

              //  $this->index(1);
			  
			  //  $this->load->view('purchases_details',$data);
			  $purchas_id=$grn_header_id;
			  $data['main_menu_name'] = $this->main_menu_name;
      $data['sub_menu_name'] = "view_purchases";
      $data['po_header'] = $this->purchases_model->getpurchases_by_id($purchas_id);
      $data['po_middle'] = $this->purchases_model->get_purchese_data_by_id($purchas_id);
      $data['po_payment']= $this->purchases_model->get_payment_by_id($purchas_id);
      $data['po_paid_total'] = $this->purchases_model->grn_pay_total($purchas_id);
      $data['purchas_id'] = $purchas_id;
      
      
      //$this->load->view('purchases_details',$data);
      
       redirect('purchases/view/'.$purchas_id, 'refresh');

                }
              }
        }else{

            $this->load->view('purchases',$data);

        }
      
    }
    
    public function get_product_by_code()
    {
        //return array();
        $emp_array=array();
        $product_code = $this->input->get('term');
		 $cat_srh = $this->input->get('cat_srh');
		 $powarehouse=$this->input->get('powarehouse');
        $get_product_all_by_id  = $this->purchases_model->get_product_by_code($product_code,$cat_srh);
          if (!empty($get_product_all_by_id)) {
            $empar=array();
            foreach ($get_product_all_by_id as $key => $value) {
                
                //Start get last grn cost price,selling price, mi selling price by id
              $grn_itm_des=$this->purchases_model->get_last_grn_cost_price_by_prodcut_id($get_product_all_by_id[$key]->product_id);
             
             $pis_cost_price=0;
             $pis_cash_price=0;
             
             if(isset($grn_itm_des['pis_cost_price'])){
                //echo "1111";
                 $pis_cost_price=$grn_itm_des['pis_cost_price'];
                 if($pis_cost_price){
                     $get_product_all_by_id[$key]->product_cost=$pis_cost_price;
                 }
                 $pis_cash_price=$grn_itm_des['pis_cash_price'];
                 if($pis_cash_price){
                     $get_product_all_by_id[$key]->product_price=$pis_cash_price;
                 }
             }
             
             //End get last grn cost price,selling price, mi selling price by id
             
              $r      = $get_product_all_by_id[$key];
              $lb = $get_product_all_by_id[$key]->product_name;
			   $rand_var=date("YmdHis");
			   
			   $qty='';
			   $qty_w='';
			   
			  //$qty_des=$this->Report_Model->get_total_balance_by_product_id($get_product_all_by_id[$key]->product_id,''); 
			  //print_r($qty_des);
			   //$qty=$qty_des->product_balance;
			   
			   //$qty_des_w=$this->Report_Model->get_total_balance_by_product_id($get_product_all_by_id[$key]->product_id,$powarehouse); 
			  //print_r($qty_des);
			   //$qty_w=$qty_des_w->product_balance;
			   
	
			   
              $label  = array("id"=>$rand_var,"item_id"=>$get_product_all_by_id[$key]->product_id,"label"=>$get_product_all_by_id[$key]->product_name.' -  Price '.$get_product_all_by_id[$key]->product_price,"qty"=>1,'row' =>$r,'value'=>$get_product_all_by_id[$key]->product_name);
              array_push($empar,$label);
            }
              echo json_encode($empar);

          } else {

            echo '[{"id":0,"label":"No matching result found! Product might be out of stock in the selected warehouse.","value":"hg"}]';
          }
      
    }

    public function get_product_by_code_old_2022_08_24()
    {
        //return array();
        $emp_array=array();
        $product_code = $this->input->get('term');
		 $cat_srh = $this->input->get('cat_srh');
		 $powarehouse=$this->input->get('powarehouse');
        $get_product_all_by_id  = $this->purchases_model->get_product_by_code($product_code,$cat_srh);
          if (!empty($get_product_all_by_id)) {
            $empar=array();
            foreach ($get_product_all_by_id as $key => $value) {
                
                //Start get last grn cost price,selling price, mi selling price by id
              $grn_itm_des=$this->purchases_model->get_last_grn_cost_price_by_prodcut_id($get_product_all_by_id[$key]->product_id);
             
             $pis_cost_price=0;
             $pis_cash_price=0;
             
             if(isset($grn_itm_des['pis_cost_price'])){
                //echo "1111";
                 $pis_cost_price=$grn_itm_des['pis_cost_price'];
                 if($pis_cost_price){
                     $get_product_all_by_id[$key]->product_cost=$pis_cost_price;
                 }
                 $pis_cash_price=$grn_itm_des['pis_cash_price'];
                 if($pis_cash_price){
                     $get_product_all_by_id[$key]->product_price=$pis_cash_price;
                 }
             }
             
             //End get last grn cost price,selling price, mi selling price by id
             
              $r      = $get_product_all_by_id[$key];
              $lb = $get_product_all_by_id[$key]->product_name;
			   $rand_var=date("YmdHis");
			   
			   $qty='';
			   $qty_w='';
			   
			  $qty_des=$this->Report_Model->get_total_balance_by_product_id($get_product_all_by_id[$key]->product_id,''); 
			  //print_r($qty_des);
			   $qty=$qty_des->product_balance;
			   
			   $qty_des_w=$this->Report_Model->get_total_balance_by_product_id($get_product_all_by_id[$key]->product_id,$powarehouse); 
			  //print_r($qty_des);
			   $qty_w=$qty_des_w->product_balance;
			   
	
			   
              $label  = array("id"=>$rand_var,"item_id"=>$get_product_all_by_id[$key]->product_id,"label"=>$get_product_all_by_id[$key]->product_name.' -  Price '.$get_product_all_by_id[$key]->product_price. " - All Qty : $qty -  Warehouse  Qty : $qty_w","qty"=>1,'row' =>$r,'value'=>$get_product_all_by_id[$key]->product_name);
              array_push($empar,$label);
            }
              echo json_encode($empar);

          } else {

            echo '[{"id":0,"label":"No matching result found! Product might be out of stock in the selected warehouse.","value":"hg"}]';
          }
      
    }
    
    
    	  public function single_barcode($purchas_id='',$po_item_id='',$qty='')
  {
	 // if(
	  $data['qty'] =intval($qty);
	  
	  $data['po_header'] = $this->purchases_model->getpurchases_by_id($purchas_id);
	  
	 // $data['product_des'] =$this->Product_Models->get_product_by_id($product_id);
	 // $data['sn_list']=$this->purchases_model->get_purchese_serial_by_id($purchas_id,$po_item_id);
	  $data['sn_list']= $this->purchases_model->get_purchese_serial_by_id($purchas_id,$po_item_id);
	  
   // $data['issue_card_items_details'] = $this->Issue_Cards_Model->get_issue_card_item_list_by_issue_card_id($issue_card_id);
	//echo "test";
    $this->load->view('barcode/grn_item_barcode',$data);
  }	

    public function purchases_details($purchas_id='')
    {
      
      $data['main_menu_name'] = $this->main_menu_name;
      $data['sub_menu_name'] = "view_purchases";
      $data['po_header'] = $this->purchases_model->getpurchases_by_id($purchas_id);
      $data['po_middle'] = $this->purchases_model->get_purchese_data_by_id($purchas_id);
      $data['po_payment']= $this->purchases_model->get_payment_by_id($purchas_id);
      $data['po_paid_total'] = $this->purchases_model->grn_pay_total($purchas_id);
      $data['purchas_id'] = $purchas_id;
      $this->load->view('purchases_details',$data);
    }

    public function list_return($e = 0) {
        //if (!$this->User_Model->is_logged_in_k()) {
        //$this->User_Model->checkLoginPanel_k();
        //}
        $data['error'] = $e;
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name'] = "list_return_purchases";
        $this->load->view('purchases_return_list', $data);
    }
	
	    public function get_list_return_purchases($value = '') {
        $search_key = $this->input->get('search');
        $search_key_val = $search_key['value'];
        $start = $this->input->get('start');
        $length = $this->input->get('length');
        $srh_warehouse_id = $this->input->get('srh_warehouse_id');
        $srh_to_date = $this->input->get('srh_to_date');
        $srh_supplier_id = $this->input->get('srh_supplier_id');
        $totalData = 0;
        $values = '';
        if ($search_key_val) {

            $values = $this->purchases_model->getpurchases_return($start, $length, $search_key_val, $srh_warehouse_id, $srh_to_date, $srh_supplier_id);
            $values_count = $this->purchases_model->getpurchases_return('', '', $search_key_val, $srh_warehouse_id, $srh_to_date, $srh_supplier_id);
            $totalData = count($values_count);
        } else {
            $values = $this->purchases_model->getpurchases_return($start, $length, '', $srh_warehouse_id, $srh_to_date, $srh_supplier_id);
            $values_count = $this->purchases_model->getpurchases_return('', '', '', $srh_warehouse_id, $srh_to_date, $srh_supplier_id);
            $totalData = count($values_count);
        }

        $totalFiltered = $totalData;
        /* echo "{";
          print_r($totalData);
          echo "|";
          print_r($totalFiltered);
          echo "}"; */
        /*
          "recordsTotal"    => intval( $totalData ),
          "recordsFiltered" => intval( $totalFiltered ),
          'data' =>$data */

        $data = array();
        $pay_st;
        if (!empty($values)) {
            foreach ($values as $purchases) {

                if (empty($purchases->sale_pymnt_amount)) {
                    $pay_st = '<span class="label label-warning">Pending</span>';
                } else {
                    if ($purchases->grn_total_paid >= $purchases->grand_total) {
                        $pay_st = '<span class="label label-success">Paid</span>';
                    } else {
                        $pay_st = '<span class="label label-info">Partial</span>';
                    }
                }

                $row = array();
                $row[] = $purchases->date;
                $row[] = $purchases->reference_no;
                $row[] = $purchases->supp_company_name;
                $row[] = $purchases->supp_invocie_no;
                $row[] = number_format($purchases->grand_total, 2, '.', '');
                /* $row[] = number_format($purchases->grn_total_paid,2,'.','');
                  $row[] = number_format($purchases->grand_total - $purchases->grn_total_paid,2,'.','');
                  $row[] = $pay_st; */
                if (!$this->input->get('request_for'))
                    $row[] = '<div class="text-center"><div class="btn-group text-left">
                    <button data-toggle="dropdown" class="btn btn-default btn-xs btn-primary dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                    <ul role="menu" class="dropdown-menu pull-right">
                 	<li><a href="' . base_url('purchases/purchases_details_r/' . $purchases->pr_id) . '"><i class="fa fa-file-text-o"></i> GRN Details</a></li></ul></div>
                    
					</div>';
                $data[] = $row;
            }

            $output = array(
                "recordsTotal" => intval($totalData),
                "recordsFiltered" => intval($totalFiltered),
                'data' => $data
            );
            echo json_encode($output);
        }else {
            $output = array('data' => '');
            echo json_encode($output);
        }
    }

    public function purchases_details_r($purchas_id = '') {
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name'] = "view_purchases";
        $data['po_header'] = $this->purchases_model->getpurchases_return_by_id($purchas_id);
        $po_header = $this->purchases_model->getpurchases_return_by_id($purchas_id);
        $data['po_middle'] = $this->purchases_model->get_purchese_return_data_by_id($data['po_header'][0]->pr_id);
        $data['po_payment'] = $this->purchases_model->get_payment_by_id_r($purchas_id);
        $data['po_paid_total'] = $this->purchases_model->grn_pay_total_r($purchas_id);
        $data['purchas_id'] = $purchas_id;
        $this->load->view('purchases_details_r', $data);
    }
	
    public function purchases_return_add() {
        //if (!$this->User_Model->is_logged_in_k()) {
        //	$this->User_Model->checkLoginPanel_k();
        //}
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name'] = 'add_purchases';

        // 
        $data['supplier'] = $this->purchases_model->get_supplier();

        $sale_id = $this->input->get('sale_id');
        $data['sale_item_list'] = array();
        $data['sale_details'] = $this->Sales_Model->get_purchase_info_r($sale_id);
        //$data['supplier_details']= $this->Supplier_Model->get_supplier_info_r($data['sale_details']['supplier_id']);
        //$data['warehouse_details'] = $this->Warehouse_Model->get_warehouse_info_r($data['sale_details']['warehouse_id']);
        $data['sale_id'] = $sale_id;
        $data['suppliers'] = $this->Supplier_Model->get_all_supplier();
//		$data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
//		$data['tax_rates_list'] = $this->Tax_Rates_Model->get_all_tax_rates();
//		$data['customer_list'] = $this->Customer_Model->get_all_customers();
//		$data['status_list'] = $this->Common_Model->get_all_status();
//		$data['cr_limit_list'] = $this->Common_Model->get_all_cr_limit();
//	  
        $data['warehouse'] = $this->purchases_model->get_warehouse();
        $data['supplier'] = $this->purchases_model->get_supplier();


        if (isset($_POST['submit'])) {
//print_r($_POST);
            $this->form_validation->set_rules('supplier', 'supplier', 'required');

            if ($this->form_validation->run() == FALSE) {
                $this->load->view('purchases', $data);
            } else {

                //echo $this->input->get('sale_id');;
                //$sale_id_r=$this->input->get('sale_id');
                //echo $sale_id_r;
                //$data['sale_details']= $this->Sales_Model->get_purchase_info_r($sale_id_r);
                //$data['supplier_details']= $this->Supplier_Model->get_supplier_info_r($data['sale_details']['supplier_id']);
                //$data['warehouse_details'] = $this->Warehouse_Model->get_warehouse_info_r($data['sale_details']['warehouse_id']);
                //print_r ($this->input->post());  
                $podate = $this->input->post('podate');

                //$reference_no = $this->input->post('reference_no');
                $warehouse_id = $this->input->post('powarehouse'); //$data['warehouse_details'][0]['id'];
                //$sale_id_r   =$this->input->post('sale_id');
                //$warehouse_code=$this->Warehouse_Model->get_warehouse_info($warehouse_id);
                //$perfix_for_contract='G'.$data['warehouse_details'][0]['code'].'/R/'.$sale_id_r;//contract
                $ref_id_nxt = $this->Sales_Model->gen_ref_number_booking('warehouse_pur_id', 'purchases', '', 'warehouse_id', $warehouse_id);

                //$ref_id = new Common_Model();
                $reference_no = $this->common_model->gen_ref_number('pr_id', 'purchases_return', 'GRN/R/');

                $sale_reference = $reference_no; //this->input->post('poref');

                $reference_no = $sale_reference;


                $supplier = $this->input->post('supplier_name');
                $discount = $this->input->post('discount');
                $powarehouse = $this->input->post('powarehouse');
                $note = $this->input->post('note');
                $grand_total = $this->input->post('hgtotal');
                $total = $this->input->post('total');
                $order_cal_des = $this->input->post('order_cal_des');
                $supp_invocie_no = $this->input->post('supp_invocie_no');

                $grn_header_id = $this->purchases_model->add_grn_header_r(0, $podate, $reference_no, $supplier, $discount, $powarehouse, $note, $grand_total, $total, $order_cal_des, $supp_invocie_no, $ref_id_nxt);
                $last_id = $this->db->insert_id();
                if ($grn_header_id) {
                    $product_id_array = $this->input->post('product_id');
                    $product_array = $this->input->post('product');
                    $product_name_array = $this->input->post('product_name');
                    $unit_cost_array = $this->input->post('unit_cost');
                    $quantity_array = $this->input->post('quantity');
                    $product_discount_array = $this->input->post('product_discount');
                    $gross_total = $this->input->post('gross_total');
                    $sub_total = $this->input->post('subtotal');
                    $discount_cal = $this->input->post('discount_cal');
                    //echo count($product_array);
//                  print_r($sub_total);
                    //die();
                    //echo $grand_total.'<br>';
                    //echo array_sum($sub_total);
                    for ($i = 0; $i < count($product_array); $i++) {
                        $this->purchases_model->add_grn_list_item_r($last_id, $product_id_array[$i], $grn_header_id, $product_array[$i], $product_name_array[$i], $unit_cost_array[$i], $quantity_array[$i], $product_discount_array[$i], $gross_total, $sub_total[$i], $discount_cal[$i]);
                        //$this->purchases_model->update_purchase_qty($sale_id_r,$product_id_array[$i],$quantity_array[$i],$sub_total[$i]);

                        $this->common_model->add_fi_table("grn", $grn_header_id, $product_id_array[$i], $quantity_array[$i], $unit_cost_array[$i]);
                    }

                    //$this->purchases_model->update_purchases_values($sale_id_r,$grand_total);

                    $this->list_return(1);
                }
            }
        } else {

            $this->load->view('purchases_return', $data);
        }
    }
}