<?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('Transfer_Model');

		$this->load->model('Customer_Model');

		$this->load->model('Sales_Return_Model');

        $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('Supplier_Model');

		$this->load->model('Warehouse_Model');

		$this->load->model('Sales_Model');

		$this->load->model('Tax_Rates_Model');

		$this->load->model('Purchases_Model');

		$this->load->model('Product_Damage_Model');

      	$this->load->model('Proceed_Order_Model');

		$this->load->model('Order_Model');

		$this->load->model('Common_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";

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

    }



    public function get_list_purchases($value='')

    {

		$i=0;

            $values = $this->purchases_model->getpurchases();

            $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>';

                  }

                }

//print_r($values[i]);

//$count = $this->purchases_model->get_no_of_return_purchases($values[$i]->id);

//$return_amount = $this->purchases_model->get_return_amount($values[$i]->id);



//print_r($return_amount);

//$r = $return_amount[0]['sum'];

$i++;



//print_r($count[0]->count);

                $row = array();

                    $row[] = $purchases->date;

                    $row[] = $purchases->reference_no;



                    //$row[] = '';//$count[0]->count;	

					$row[] = $purchases->supp_company_name;



					//$row[] = $purchases->supp_invocie_no;

					//if($r){$row[] = $r;}

					//$row[] = '0.00';//else

					 

//					$grand_tot= $purchases->grand_total;

                    $row[] = $purchases->supp_invocie_no;// $purchases->grand_total;

					$row[] = number_format($purchases->grand_total,2,'.','');

					//$row[] = number_format($purchases->grand_total-$r,2,'.',',');

                    $row[] = number_format($purchases->grn_total_paid,2,'.','');

                    $row[] = number_format($purchases->grand_total - $purchases->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>			

					<li><a href="'.base_url().'purchases/purchases_return_add/?purchase_id='.$purchases->id.'"><i class="fa fa-angle-double-left"></i></i> Return GRN</a></li>

					

                    </ul></div>

                    </div>';

                    $data[] = $row;

                }



                $output = array('data' =>$data);

                echo json_encode($output);

            }else{

                $output = array('data' =>'');

                echo json_encode($output);



            }

       }

	   public function test(){

		   

		   $this->purchases_model-> update_purchase_qty(1,4,1,500);

		   

		   }

	   

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_return';

      	$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();

		

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

    }

	

	public function save_purchase_return(){

		  $data['main_menu_name'] = $this->main_menu_name;

      $data['sub_menu_name'] = 'add_purchases_return';

      

	 // 

      $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['sale_id']=$sale_id;

		$data['suppliers'] = $this->Supplier_Model->get_all_supplier();

  		$data['warehouse'] = $this->purchases_model->get_warehouse();

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

		 $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');

				$warehouse_id= $this->input->post('powarehouse');//$data['warehouse_details'][0]['id'];

				$ref_id_nxt=$this->Sales_Model->gen_ref_number_booking('warehouse_ret_id','purchases_return','','warehouse_id',$warehouse_id);

				$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);



                }

              }

		}

	

		  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 purchases_return_add()

    {

		$data['main_menu_name'] = $this->main_menu_name;

		$data['sub_menu_name'] = '';

		

		//get sale id

		$sale_id=$this->uri->segment('3');

		$data['sale_item_list']=array();

		//$data['sale_item_list']= $this->Sales_Model->get_sale_item_list_by_sale_id($sale_id);

		$data['sale_details']= $this->Sales_Model->get_purchase_info($sale_id);

		$data['sale_id']=$sale_id;

		//get suppliers list

		$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();

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

    }*/

	

	 public function suggestions($value='')

    {

		//print_r($_GET);

		$term=$this->input->get('term');

		$in_type=$this->input->get('t');

		$data['sales'] = $this->Sales_Model->get_products_suggestions($term);

		$json = array();

		//echo "Count:".count($data['sales']);

		//print_r($data['sales']);

		foreach ($data['sales'] as $row)

		{

			//set price

			$price_tmp=0;

			if($in_type=='Cash'){

				$price_tmp=$row['product_cost'];

			}

			if($in_type=='Credit'){

				$price_tmp=$row['credit_salling_price'];

			}

			if($in_type=='Wholesale'){

				$price_tmp=$row['wholesale_price'];

			}

			

			$product_name=$row['product_name'];

			$product_code=$row['product_code'];

			$product_part_no=$row['product_part_no'];

			$product_oem_part_number=$row['product_oem_part_number'];

			$product_id=$row['product_id'];

			$product_price=$price_tmp;

			$sendParameters="'$product_id','$product_name','$product_code','$product_price'";

			$sendParameters="$product_id,$product_name,$product_code,$product_price";

			$extraName='';

			$extraName.=", Selling Price: ".number_format($product_price, 2, '.', ',');

			if($product_part_no) $extraName.=", Part No: $product_part_no";

			if($product_oem_part_number) $extraName.=", OEM Part No: $product_oem_part_number";

			



			

			

			 $json_itm=array(

			 		'id'=> $row['product_id'],

					'product_id'=> $row['product_id'],

					'product_code'=> $row['product_code'],

					'product_name'=> $row['product_name'],

					'product_price'=> $price_tmp,

					'product_part_no'=> $row['product_part_no'],

					'item_cost'=> $row['product_cost'],

					'product_oem_part_number'=> $row['product_oem_part_number'],

                    'value'=> $row['product_name']." (".$row['product_code'].")",

                    'label'=> $row['product_name']." (".$row['product_code'].")$extraName"

                    );

					array_push($json,$json_itm);

		}		

		echo json_encode($json);		

    }





     public function add_purchases($purchased_id="")

    {

		$data['suppliers'] = $this->Supplier_Model->get_all_supplier();

		$data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();

		$data['warehouse'] = $this->purchases_model->get_warehouse();

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

		$data['purchased_id'] = $purchased_id;

		$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['main_menu_name'] = $this->main_menu_name;

      	$data['sub_menu_name'] = 'add_purchases';

		

		 //$items = $this->Order_Model->get_proceed_order_item_list_by_po_id($purchased_id);

			//if($items)

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

		//else show_404();

		

		/*

		//if (!$this->User_Model->is_logged_in_k()) {

		//	$this->User_Model->checkLoginPanel_k();

		//}

     */

    }

	public function save_purchases(){

		//print_r($_SUBMIT);

		//print_r($this->input->post());

		$disMsg ='';

		$error  ='';

		$lastid ='';

		  $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');

				$warehouse_id=$this->input->post('powarehouse');

				$warehouse_code=$this->Warehouse_Model->get_warehouse_info($warehouse_id);

				$perfix_for_contract='G'.$warehouse_code['code']."/";//contract

				//$ref_id_nxt=$this->Sales_Model->gen_ref_number_booking('warehouse_pur_id','purchases','','warehouse_id',$warehouse_id);

				$ref_id_nxt=$this->common_model->gen_ref_number('id','purchases','');

				

				$reference_no = $this->common_model->gen_ref_number('id','purchases',$perfix_for_contract);

				

				//$sale_reference		= $ref_id_nxt;

				//$reference_no=$perfix_for_contract.$sale_reference;



                $supplier     = $this->input->post('supplier');

                $discount     = $this->input->post('sale_inv_discount');

                $powarehouse  = $this->input->post('powarehouse'); 

                $note         = $this->input->post('note');

                $grand_total  = $this->input->post('sale_total');

                $total        = $this->input->post('sub_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($podate,$reference_no,$supplier,$discount, $powarehouse,$note , $grand_total,$total,$order_cal_des,$supp_invocie_no,$ref_id_nxt);

$lastid=$this->db->insert_id();

                if ($grn_header_id) {

					

					

			

			//insert sale item data

			$row=$this->input->post('row');

			$rowCount=$this->input->post('rowCount');

			$data_item=array();

			for($i=1; $i<=$rowCount; $i++){

				//echo "/ $rowCount , Test:".$row[$i]['product_id'][0];

				if(isset($row[$i]['product_id'][0]))

				{					

				$data_item=array(

					'purchase_id'  => $grn_header_id ,

					'product_id'   => $row[$i]['product_id'][0],

					'product_code' => $row[$i]['product_code'][0],

					'product_name' => $row[$i]['product_name'][0],

					'quantity'     => $row[$i]['qty'][0],

					'unit_price'   => $row[$i]['unit_price'][0],

					'sub_total'    => $row[$i]['gross_total'][0],

					'discount'	   => $row[$i]['discount'][0],

					'discount_cal' => $row[$i]['discount_val'][0]

				

				

				/*	'purchase_id'  => $grn_header_id ,

					'product_id'=>$row[$i]['product_id'][0],

					'quantity'=>$row[$i]['qty'][0],

					'discount'=>$row[$i]['discount'][0],

					'unit_price'=>$row[$i]['unit_price'][0],

					'item_cost'=>$row[$i]['item_cost'][0],

					'unit_price'=>$row[$i]['unit_price'][0]+$row[$i]['item_price_p'][0],

					'discount_val'=>$row[$i]['discount_val'][0], 

					'gross_total'=>$row[$i]['gross_total'][0]*/

				);

				$this->purchases_model->add_grn_list_item($data_item);

				}

			}

			$disMsg='Purchase successfully added';

			

                 /*   $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);

                  //die();

                  for ($i=0; $i <count($product_array); $i++) { 

                    $this->purchases_model->add_grn_list_item($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->common_model->add_fi_table("grn",$grn_header_id,$product_id_array[$i],$quantity_array[$i],$unit_cost_array[$i]);

                  }*/



               // $this->index(1);

			   $this->session->set_flashdata('message', 'Purchase successfully added!');

		

		echo json_encode(array('sale_id'=>$lastid,'error'=>$error,'disMsg'=>$disMsg,));

				}

				}

		}

		public function get_avalable_product_qty_for_return_purchases()

    {	

		$product_id=$this->input->get('product_id');

		$warehouse_id=$this->input->get('warehouse_id');

		$sale_id=$this->input->get('sale_id');

		$qty=$this->input->get('qty');

		$saleqty=$this->Sales_Return_Model->get_avalable_product_qty_for_return($product_id,$warehouse_id,$sale_id);

		$salereturnqty=$this->Sales_Return_Model->get_sales_return_product_qty($product_id,$warehouse_id,$sale_id);

		$totalRemaningQty=$saleqty-$salereturnqty;

		//echo "qty:$qty , remmnaingQty:$saleqty , salereturnqty:$salereturnqty";

		if($qty<=$totalRemaningQty){

			$remmnaingQty=$saleqty;

		}else {

			$remmnaingQty=0;

		}

		

		echo json_encode(array('remmnaingQty'=>$remmnaingQty));

	}

	



public function save_purchases_return()

	

	{

		$rowCount=$this->input->post('rowCount');

		$sl_rtn_datetime_1=$this->input->post('sl_rtn_datetime');

		$sl_rtn_datetime=date('Y-m-d H:i:s', strtotime($sl_rtn_datetime_1));

		$user_id=$this->session->userdata('ss_user_id');

		

		$error='';

		$disMsg='';

		$lastid='';

		$sl_rtn_id='';

		

		/* payment validation start */

		$sale_pymnt_amount=$this->input->post('sale_pymnt_amount');

		$sale_id=$this->input->post('sale_id');

		$sale_pymnt_ref_no=$this->input->post('sale_pymnt_ref_no');

		$sale_pymnt_paying_by=$this->input->post('sale_pymnt_paying_by');

		$sale_pymnt_date_time=$sl_rtn_datetime;

		$sale_pymnt_date_time_send=date('Y-m-d H:i:s', strtotime($sale_pymnt_date_time));

		$sale_pymnt_cheque_no=$this->input->post('sale_pymnt_cheque_no');

		$sale_pymnt_crdt_card_no=$this->input->post('sale_pymnt_crdt_card_no');

		$sale_pymnt_crdt_card_holder_name=$this->input->post('sale_pymnt_crdt_card_holder_name');

		$sale_pymnt_crdt_card_month=$this->input->post('sale_pymnt_crdt_card_month');

		$sale_pymnt_crdt_card_year=$this->input->post('sale_pymnt_crdt_card_year');

		$sale_pymnt_crdt_card_type=$this->input->post('sale_pymnt_crdt_card_type');

		$cr_interest=$this->input->post('cr_interest');

		$cr_interest_amt=$this->input->post('cr_interest_amt');

		$in_type=$this->input->post('in_type');

		

		$sale_pymnt_note=$this->input->post('sale_pymnt_note');

		$user_id=$this->session->userdata('ss_user_id');

		$sale_pymnt_added_date_time=date("Y-m-d H:i:s");

		$sale_pymnt_id='';

		

        $this->load->library('form_validation'); //form validation lib

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

		if($sale_pymnt_paying_by=='Credit Card'){

			$this->form_validation->set_rules('sale_pymnt_crdt_card_type', 'Card Type', 'required');

			$this->form_validation->set_rules('sale_pymnt_crdt_card_no', 'Credit Card No', 'required');

			$this->form_validation->set_rules('sale_pymnt_crdt_card_holder_name', 'Holder Name', 'required');

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

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

		}

		if($sale_pymnt_paying_by=='Cheque'){

			$this->form_validation->set_rules('sale_pymnt_cheque_no', 'Cheque No', 'required');

		}

		$this->form_validation->set_rules('sale_id', 'System Error', 'required');

		

		if($sale_pymnt_amount){

		$tmp=number_format($sale_pymnt_amount, 2, '.','');

		}else{

			$tmp=0;

		}

	//	echo $this->input->post('sl_rtn_total');

        if ($this->form_validation->run() == FALSE)

        {

           $st = array('status' =>0,'validation' => validation_errors());

		   $disMsg=validation_errors();

		   $error=true;

        }else if($tmp!=$this->input->post('sl_rtn_total')){

			$error=true;

			$disMsg='Invalid Amount';

		}

		/* end payment validation start */

		

		

		

		

		if(!$error){

			$data=array(

				'purchases_rtn_reference_no'=>$this->input->post('sl_rtn_reference_no'),

				'sale_id'=>$this->input->post('sale_id'),

				'customer_id'=>$this->input->post('customer_id'),

				'warehouse_id'=>$this->input->post('warehouse_id'),

				'date'=>$sl_rtn_datetime,

				'sl_rtn_inv_discount'=>$this->input->post('sl_rtn_inv_discount'),

				'sl_rtn_total'=>$this->input->post('sl_rtn_total'),

				'sl_rtn_datetime_created'=>date('Y-m-d H:i:s'),

				'sl_rtn_inv_discount_amount'=>$this->input->post('sl_rtn_inv_discount_amount'),

				'sl_rtn_note'=>$this->input->post('sl_rtn_note'),

				'user_id'=>$user_id,

				'in_type'=>$in_type,

				'cr_interest'=>$cr_interest,

				'cr_interest_amt'=>$cr_interest_amt,

			);

			$_insert=$this->Sales_Return_Model->save_sales_return($data,$sl_rtn_id);

			$lastid=$this->db->insert_id();

			$sl_rtn_id=$lastid;

			$disMsg='Sale return successfully added';

			

			//insert sale item data

			$row=$this->input->post('row');

			$rowCount=$this->input->post('rowCount');

			//print_r($row);

			$data_item=array();

			for($i=1; $i<=$rowCount; $i++){

				if(isset($row[$i]['product_id'][0]))

				{

					

				$data_item=array(

					'sl_rtn_id'=>$sl_rtn_id,

					'product_id'=>$row[$i]['product_id'][0],

					'quantity'=>$row[$i]['qty'][0],

					'discount'=>$row[$i]['discount'][0],

					'unit_price'=>$row[$i]['unit_price'][0]+$row[$i]['item_price_p'][0],

					'discount_val'=>$row[$i]['discount_val'][0], 

					'gross_total'=>$row[$i]['gross_total'][0]

				);

				$slrtnitmid=$this->Sales_Return_Model->save_sales_return_item($data_item);

				$slrtnitmid=$this->db->insert_id();

				//add record for f4 table

				$type='sl_rtn';

				$ref_id=$slrtnitmid;

				$product=$row[$i]['product_id'][0];

				$quantity=$row[$i]['qty'][0];

				$unit_cost=$row[$i]['unit_price'][0];

				$this->Common_Model->add_fi_table($type,$ref_id,$product,$quantity,$unit_cost);

				}

			}

			//add sales return payments

				$data=array(

				'sale_pymnt_amount'=>$sale_pymnt_amount,	

				'sale_pymnt_ref_no'=>$sale_pymnt_ref_no,

				'sale_pymnt_paying_by'=>$sale_pymnt_paying_by,

				'sale_pymnt_date_time'=>$sale_pymnt_date_time_send,

				'sale_pymnt_note'=>$sale_pymnt_note,

				'user_id'=>$user_id,

				'sale_id'=>$sl_rtn_id,

				'sale_pymnt_added_date_time'=>date('Y-m-d H:i:s'),

				'sale_pymnt_cheque_no'=>$sale_pymnt_cheque_no,

				'sale_pymnt_crdt_card_no'=>$sale_pymnt_crdt_card_no,

				'sale_pymnt_crdt_card_holder_name'=>$sale_pymnt_crdt_card_holder_name,

				'sale_pymnt_crdt_card_type'=>$sale_pymnt_crdt_card_type,

				'sale_pymnt_crdt_card_month'=>$sale_pymnt_crdt_card_month,

				'sale_pymnt_crdt_card_year'=>$sale_pymnt_crdt_card_year,

				'sale_payment_type' => 'sales_return'

			);

			

               if ($this->Sales_Model->save_sale_payments($data,$sale_pymnt_id)) {

                   

               } else {

                    $error=true;

               }

				//end add return payments

		

		}else {

			$error=true;

		}

		

						

		echo json_encode(array('sale_id'=>$lastid,'error'=>$error,'disMsg'=>$disMsg,));

		

	}	



    public function get_product_by_code()

    {

        

        $emp_array=array();

        $product_code = $this->input->get('term');

		$s_tmp_id = strtotime("now"); //$this->input->get('s_tmp_id');

        $get_product_all_by_id  = $this->purchases_model->get_product_by_code($product_code);

          if (!empty($get_product_all_by_id)) {

            $empar=array();

			//$s_tmp_id=0;

            foreach ($get_product_all_by_id as $key => $value) {

              $r      = $get_product_all_by_id[$key];

              $lb = $get_product_all_by_id[$key]->product_name;

			  

			 // mt_rand()

              $label  = array("id"=>$s_tmp_id,"item_id"=>$get_product_all_by_id[$key]->product_id,"label"=>$get_product_all_by_id[$key]->product_code.' / '.$get_product_all_by_id[$key]->product_part_no.' / '.$get_product_all_by_id[$key]->product_oem_part_number.' / '.$get_product_all_by_id[$key]->product_name.' / LKR.'.$get_product_all_by_id[$key]->product_cost,"qty"=>1,'row' =>$r,'value'=>$get_product_all_by_id[$key]->product_name);

              array_push($empar,$label);

			  

			  //$s_tmp_id++;

            }

              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_r()

    {

        

        $emp_array=array();

        $product_code = $this->input->get('term');

		$sale_id = $this->input->get('sale_id');

		

//		 $this->Sales_Model->get_products_suggestions($term,$sale_id);

		

		$s_tmp_id = strtotime("now"); //$this->input->get('s_tmp_id');

  //      $get_product_all_by_id  = $this->purchases_model->get_product_by_code($product_code);

        $get_product_all_by_id  = $this->Sales_Model->get_products_suggestions_r($product_code,$sale_id);

       // print_r($get_product_all_by_id );

		

		  if (!empty($get_product_all_by_id)) {

            $empar=array();

			//$s_tmp_id=0;

            foreach ($get_product_all_by_id as $key => $value) {

              $r      = $get_product_all_by_id[$key];

              $lb = $get_product_all_by_id[$key]->product_name;

			  

			 // mt_rand()

              $label  = array("id"=>$s_tmp_id,"item_id"=>$get_product_all_by_id[$key]->product_id,"label"=>$get_product_all_by_id[$key]->product_code.' / '.' / '.$get_product_all_by_id[$key]->product_name.' / LKR.'.$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);

			  

			  //$s_tmp_id++;

            }

              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 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);

      if($data['po_header']){

		  $data['po_middle'] = $this->purchases_model->get_purchese_data_by_id($purchas_id);

	  //print_r($data['po_middle']);

      //$data['po_header_r'] = $this->purchases_model->getpurchases_return_by_id_sum($purchas_id);

	//  print_r($data['po_header_r']);

	  //$po_header = $this->purchases_model->getpurchases_return_by_id($purchas_id);

	  //$data['po_header']['0']['purchase_id']; 

     // $data['po_middle_r'] = $this->purchases_model->get_purchese_return_data_by_id($data['po_header_r'][0]->pr_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);

	  }

	  else show_404();

    }

	

	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 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);



            }

       }

}