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

class Purchase_return extends CI_Controller {

    var $main_menu_name = "purchases";
	var $sub_menu_name = "purchase_return";

	public function __construct()
	{
		parent::__construct();

		$this->load->model('Sales_Model');
		$this->load->model('Purchase_Return_Model');
		$this->load->model('Supplier_Model');
		$this->load->model('Warehouse_Model');
		$this->load->model('Common_Model');
		$this->load->model('Tax_Rates_Model');
		$this->load->model('Customer_Model');
		$this->load->model('Sequerty_Model');
		$this->load->model('User_Model');
		$this->load->model('Purchases_Model');
		$this->load->model('Purchase_Return_Model');
		
	}
	
	//Sales reterun list page
	public function index()
	{
		$data['sales'] =array();// $this->Sales_Model->get_all_sales();
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = $this->sub_menu_name;
		$data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
		//echo "test";
        $this->load->view('purchase_return',$data);
	}


		
	//Sales reterun get sold qty
	public function get_avalable_product_qty_for_return()
    {	
		$product_id=$this->input->get('product_id');
		$warehouse_id=$this->input->get('warehouse_id');
		$grn_id=$this->input->get('grn_id');
		$qty=$this->input->get('qty');
		$saleqty=$this->Purchase_Return_Model->get_avalable_product_qty_for_return($product_id,$warehouse_id,$grn_id);
		$salereturnqty=$this->Purchase_Return_Model->get_purchase_return_product_qty($product_id,$warehouse_id,$grn_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));
	}
	
	//Add sales return form
    public function manage()
    {
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = '';
		
		//get sale id
		$grn_id=$this->uri->segment('3');
		$data['grn_item_list']= $this->Purchases_Model->get_grn_item_list_by_grn_id($grn_id);
		$data['grn_details']= $this->Purchases_Model->get_grn_info($grn_id);
		$data['grn_id']=$grn_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'] = array();//$this->Customer_Model->get_all_customers();
		$data['status_list'] = $this->Common_Model->get_all_status();
		
        $this->load->view('purchase_return_manage',$data);
    }
	
	
	//Save sales return
	//Insert data to payment table with type 'purchase_return'
	public function save_purchase_return()
	
	{
		$rowCount=$this->input->post('rowCount');
		//$sl_rtn_datetime_1=$this->input->post('sl_rtn_datetime');
		$pur_rtn_datetime=date('Y-m-d H:i:s', strtotime($this->input->post('pur_rtn_datetime')));
		$user_id=$this->session->userdata('ss_user_id');
		$warehouse_id=$this->input->post('warehouse_id');
		
		$error='';
		$disMsg='';
		$lastid='';
		$sl_rtn_id='';
		
		/* payment validation start */
		$pur_rtn_pymnt_amount=$this->input->post('pur_rtn_pymnt_amount');
		$pur_id=$this->input->post('grn_id');
		$cost_total=$this->input->post('cost_total');
		
		$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=$pur_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');
		
		$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('pur_rtn_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('grn_id', 'System Error', 'required');
		
		if($pur_rtn_pymnt_amount){
		$tmp=number_format($pur_rtn_pymnt_amount, 2, '.','');
		}else{
			$tmp=0;
		}
		//echo $tmp;
        if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
		   $disMsg=validation_errors();
		   $error=true;
        }else if($tmp!=$this->input->post('pur_rtn_total')){
			$error=true;
			$disMsg='Invalid Amount';
		}
		/* end payment validation start */
		
		//get next grn return no
		$warehouse_dtls=$this->Warehouse_Model->get_warehouse_info($warehouse_id);
		//print_r($warehouse_dtls);
		$warehouse_code=$warehouse_dtls['code'];
		$warehouse_last_id=(1+$this->Purchase_Return_Model->get_next_ref_no($warehouse_id));
		$pur_rtn_reference_no =$warehouse_code.'GR/'.sprintf("%04d",$warehouse_last_id);
		
		
		if(!$error){
			$data=array(
				'pur_rtn_reference_no'=>$pur_rtn_reference_no,
				'pur_rtn_warehouse_id'=>$warehouse_last_id,
				'pur_id'=>$this->input->post('grn_id'),
				'supp_id'=>$this->input->post('supp_id'),
				'warehouse_id'=>$this->input->post('warehouse_id'),
				'pur_rtn_datetime'=>$pur_rtn_datetime,
				'pur_rtn_inv_discount'=>$this->input->post('pur_rtn_inv_discount'),
				'pur_rtn_inv_total'=>$this->input->post('pur_rtn_total'),
				'pur_rtn_datetime_created'=>date('Y-m-d H:i:s'),
				'pur_rtn_inv_discount_amount'=>$this->input->post('pur_rtn_inv_discount_amount'),
				'pur_rtn_inv_discount'=>$this->input->post('pur_rtn_inv_discount'),
				'pur_rtn_note'=>$this->input->post('pur_rtn_note'),
				'user_id'=>$user_id,
			);
			$_insert=$this->Purchase_Return_Model->save_purchase_return($data,$sl_rtn_id);
			$lastid=$this->db->insert_id();
			$pur_rtn_id=$lastid;
			$disMsg='GRN return successfully added';
			
			//insert sale item data
			$row=$this->input->post('row');
			$rowCount=$this->input->post('rowCount');
			//print_r($row);
			$data_item=array();
			
			//echo "rowCount:$rowCount";
			for($i=1; $i<=$rowCount; $i++){
				if(isset($row[$i]['product_id'][0]))
				{
					
				$data_item=array(
					'pur_rtn_id'=>$pur_rtn_id,
					'product_id'=>$row[$i]['product_id'][0],
					'pur_rtn_itm_quantity	'=>$row[$i]['qty'][0],
					'discount'=>$row[$i]['discount'][0],
					'unit_price'=>$row[$i]['unit_price'][0],
					'discount_val'=>$row[$i]['discount_val'][0], 
					'gross_total'=>$row[$i]['gross_total'][0]
				);
				$slrtnitmid=$this->Purchase_Return_Model->save_purchase_return_item($data_item);
				$pur_rtn_itm_id=$this->db->insert_id();
				
				
				//add record for f4 table
				
				//check serial no exists
				if($row[$i]['product_sn'][0])
				{
				//add serial numbers
				//exploid serial numbers
					$pieces_sn = explode(",", $row[$i]['product_sn'][0]);
					for($h=0; $h<count($pieces_sn); $h++){
						$sn_data=array(
							'product_id'=>$row[$i]['product_id'][0],	
							//'product_w'=>$row[$i]['product_w'][0],	
							'pur_rtn_id'=>$pur_rtn_id,
							'pur_id'=>$pur_id,
							'pur_rtn_itm_id'=>$pur_rtn_itm_id,
							'pris_number'=>$pieces_sn[$h],
						);
				  		$this->Purchase_Return_Model->save_grn_return_items_serial_numbers($sn_data);
						
						
				//update grn serial number sold status
				$pis_number=$pieces_sn[$h];
				$sn_data=array(	
					'sale_inv_id'=>0,
					'pis_sold'=>0,
					'product_avalable'=>0,
					'pis_number'=>$pis_number.'_'.$pur_rtn_id,
					'avalable_warehouse_id'=>$this->input->post('warehouse_id'),

				);
				$this->Purchases_Model->update_grn_serial_numbers($sn_data,$pis_number);
				
						
					}
                    //end add serial numbers
				}
				
				/*
				$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);
				*/
				}
			}
			
			
			
			
				
				
				//insert user activity
				$this->Common_Model->add_user_activitie("Added GRN Return, (GRN Return No:$pur_rtn_reference_no)");
				
				//add sales return payments
				$data=array(
				'sale_pymnt_amount'=>$pur_rtn_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'=>$pur_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' => 'purchase_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('pur_rtn_id'=>$pur_rtn_id,'error'=>$error,'disMsg'=>$disMsg,));
		
	}	

	//Sales return details page
	public function purchase_return_details()
	{
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = 'purchase_return';
		
		//get sale id
		$pur_rtn_id=$this->uri->segment('3');
		//$data['sale_rtn_item_list']= $this->Purchase_Return_Model->get_sale_return_item_list($sl_rtn_id);
		$data['grn_rtn_details']= $this->Purchase_Return_Model->get_purchase_return_info($pur_rtn_id);
		$data['pur_rtn_item_list']= $this->Purchase_Return_Model->get_grn_return_item_list($pur_rtn_id);
		//$data['total_paid_amount']=$this->Sales_Model->get_total_paid_by_sale_id($sl_rtn_id);
		//$data['customer_details']= $this->Customer_Model->get_customer_info($data['sale_rtn_details']['customer_id']);
		$data['warehouse_details']= $this->Warehouse_Model->get_warehouse_info($data['grn_rtn_details']['warehouse_id']);
		//$data['sale_payments_list']= $this->Sales_Model->get_sale_payments_by_sale_id($sl_rtn_id);
		$data['pur_rtn_id']=$pur_rtn_id;
		 $data['po_rtn_payment']= $this->Purchase_Return_Model->get_pur_rtn_payment_by_id($pur_rtn_id);
        $this->load->view('purchase_return_details',$data);
	}	
	
		public function invoice_print()
	{
		$pur_rtn_id=$this->uri->segment('3');
		$data['grn_rtn_details']= $this->Purchase_Return_Model->get_purchase_return_info($pur_rtn_id);
		$data['pur_rtn_item_list']= $this->Purchase_Return_Model->get_grn_return_item_list($pur_rtn_id);
		
		//$data['customer_details']= $this->Customer_Model->get_customer_info($data['sale_rtn_details']['customer_id']);
		$data['warehouse_details']=  $this->Warehouse_Model->get_warehouse_info($data['grn_rtn_details']['warehouse_id']);
		//$data['sale_payments_list']= $this->Sales_Model->get_sale_payments_by_sale_id($sale_id);
		
        $this->load->view('models/print_purchase_return_invoice',$data);
	}
	
	//Sales return details list 
	public function list_purchase_return()
	{
		$requestData= $_REQUEST;
		
		
	$search_key=$this->input->post('search');

	$search_key_val=$search_key['value'];
	
//	echo "search_key_val:$search_key_val";

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

	$length=$this->input->post('length');
		$warehouse_id=$this->input->post('warehouse_id');
		$search_key1=$this->input->post('search_key1');
	
	
		$data = array();
		$sales = $this->Purchase_Return_Model->get_all_purchase_return($warehouse_id,$start,$length,$search_key_val,'',$search_key1);
		$totalData = $this->Purchase_Return_Model->get_all_purchase_return($warehouse_id,'','',$search_key_val,1,$search_key1);
	//echo 	$this->db->last_query();
		$totalFiltered = $totalData;  
		
		//print_r($sales);
		foreach ($sales as $row){
			$nestedData=array(); 
			$pur_rtn_id=$row['pur_rtn_id'];
			$pur_id=$row['pur_id'];
			$pur_rtn_total_paid=$row['pur_rtn_total_paid'];
			
			$nestedData[] =display_date_time_format($row['pur_rtn_datetime']);
			$nestedData[] = $row['pur_rtn_reference_no'];
			$nestedData[] = $row['reference_no'];
			$nestedData[] = $row['supp_company_name'];
			$nestedData[] = number_format($row['pur_rtn_inv_total'], 2, '.', ',');
			
			$balance=$row['pur_rtn_inv_total']-$pur_rtn_total_paid;
				$nestedData[] = $balance;
				//	$nestedData[] = '';
					$pay_st='';
					if (empty($pur_rtn_total_paid)) {
		  $pay_st = '<span class="label label-warning">Pending</span>';
		}else{
		  if ($pay_st >= $row['pur_rtn_inv_total']) {
			$pay_st = '<span class="label label-success">Paid</span>';
		  }else{
			$pay_st = '<span class="label label-info">Partial</span>';
		  }
		}
			
				$nestedData[] = $pay_st;
				
			$nestedData[] = '<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().'purchase_return/purchase_return_details/'.$pur_rtn_id.'"><i class="fa fa-file-text-o"></i> Return GRN Details</a></li>
								</ul></div>';
	
			$data[] = $nestedData;
	}
	
		$json_data = array(
				"recordsTotal"    => intval( $totalData ),  
				"recordsFiltered" => intval( $totalFiltered ),
				"data"            => $data 
				);
	
		echo json_encode($json_data); 
	}
}