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

class Transfer extends CI_Controller {

    var $main_menu_name = "transfer";
	var $sub_menu_name = "transfer";

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

		
		$this->load->model('Transfer_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('Purchases_Model');
		$this->load->model('Sales_Model');
		$this->load->model('User_Model');
		
		
		
	}
	
	//Transfers list page load
	public function index()
	{
		$data['transfer'] = $this->Transfer_Model->get_all_transfer();
		$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();
        $this->load->view('transfer',$data);
	}	
	
	
		public function update_trnsfr_status()
	{
        $trnsfr_id = $this->input->post('trnsfr_id');
		$type = $this->input->get('type');
		
		$disMsg='';
		$prepared_user=0;
		$checked_user=0;
		$approved_user=0;
		$reserved_user=0;
		$authorized_user=0;
		
		
		$printed_date='';
		$reviewed_status=0;
		$reviewed_user='';
		
		$reviewed_status=$this->input->post('reviewed_status');
		
		//if($this->input->post('reviewed_status')=='Reviewed')  
		$reviewed_user=$this->session->userdata('ss_user_id');
		
	
			//echo $prepared_user;
		$data_edit=array();
		if($type=='reviewed'){
			$data_edit=array(
				'reviewed_status'=>$this->input->post('reviewed_status'),
				'reviewed_user'=>$reviewed_user,
				'reviewed_date'=>date("Y-m-d H:i:s"),
			);
		}
		
		
			$_insert=$this->Transfer_Model->save_transfer($data_edit,$trnsfr_id);
			
			
			
			//update serial no transer status
			if($reviewed_status){
			$trnsfr_details=$this->Transfer_Model->get_trnsfr_info($trnsfr_id);
			//echo "trnsfr_to_warehouse_id:".$trnsfr_details['trnsfr_to_warehouse_id'];
			//print_r($trnsfr_details);
			$trnsfr_item_list=$this->Transfer_Model->get_trnsfr_item_list_by_trnsfr_id($trnsfr_id);
			if($reviewed_status){
				foreach ($trnsfr_item_list as $row)
 				{
					$sn_list=$this->Transfer_Model->get_transfer_serial_by_id($trnsfr_id,$row['trnsfr_itm_id']);
					if(!empty($sn_list)){
						
						foreach ($sn_list as $sn) { 
							//echo "<br/> Serial No. ";
							//echo "($sn->tis_number) , ";
							//update grn status
							//update grn serial number sold status
							$product_avalable=1;
							if($reviewed_status=='Approved') {
								$avalable_warehouse_id=$trnsfr_details['trnsfr_to_warehouse_id'];
								$sn_data=array(	
								'product_avalable'=>1,
								'avalable_warehouse_id'=>$avalable_warehouse_id,
								);
							}else if($reviewed_status=='Rejected'){
								$sn_data=array(	
								'product_avalable'=>1,
								);	
							}
							
							
							$pis_number=$sn->tis_number;
							$this->Purchases_Model->update_grn_serial_numbers($sn_data,$pis_number);
						}
					
					}
						
				}
			}
			//else if($reviewed_status=='Rejected'){
				
			//}
			}
			
			//end update serial no transer status
			
			//echo $this->db->last_query();
        
        echo json_encode(array('req_id'=>$trnsfr_id,'error'=>'','disMsg'=>$disMsg,));
	}
	
	//Transfers details view
	public function view()
	{
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = '';
		
		//get sale id
		$trnsfr_id=$this->uri->segment('3');
		$data['trnsfr_item_list']= $this->Transfer_Model->get_trnsfr_item_list_by_trnsfr_id($trnsfr_id);
		$data['trnsfr_details']= $this->Transfer_Model->get_trnsfr_info($trnsfr_id);
		
	
		//$data['customer_details']= $this->Customer_Model->get_customer_info($data['trnsfr_details']['customer_id']);
		$data['warehouse_details']= $this->Warehouse_Model->get_warehouse_info($data['trnsfr_details']['trnsfr_from_warehouse_id']);
		$data['to_warehouse_details']= $this->Warehouse_Model->get_warehouse_info($data['trnsfr_details']['trnsfr_to_warehouse_id']);		
		
		$data['trnsfr_id']=$trnsfr_id;
        $this->load->view('transfer_view',$data);
	}

	//Transfers add page
	public function add_trnsfr_payments()
	{
		$trnsfr_pymnt_amount=$this->input->post('trnsfr_pymnt_amount');
		$trnsfr_id=$this->input->post('trnsfr_id');
		$trnsfr_pymnt_ref_no=$this->input->post('trnsfr_pymnt_ref_no');
		$trnsfr_pymnt_paying_by=$this->input->post('trnsfr_pymnt_paying_by');
		$trnsfr_pymnt_date_time=$this->input->post('trnsfr_pymnt_date_time');
		$trnsfr_pymnt_date_time_send=date('Y-m-d H:i:s', strtotime($trnsfr_pymnt_date_time));
		$trnsfr_pymnt_cheque_no=$this->input->post('trnsfr_pymnt_cheque_no');
		$trnsfr_pymnt_crdt_card_no=$this->input->post('trnsfr_pymnt_crdt_card_no');
		$trnsfr_pymnt_crdt_card_holder_name=$this->input->post('trnsfr_pymnt_crdt_card_holder_name');
		$trnsfr_pymnt_crdt_card_month=$this->input->post('trnsfr_pymnt_crdt_card_month');
		$trnsfr_pymnt_crdt_card_year=$this->input->post('trnsfr_pymnt_crdt_card_year');
		$trnsfr_pymnt_crdt_card_type=$this->input->post('trnsfr_pymnt_crdt_card_type');
		$trnsfr_type = $this->input->post('trnsfr_type');

		$trnsfr_pymnt_note=$this->input->post('trnsfr_pymnt_note');
		$user_id=$this->session->userdata('ss_user_id');
		$trnsfr_pymnt_added_date_time=date("Y-m-d H:i:s");
		$trnsfr_pymnt_id='';
		
        $this->load->library('form_validation'); //form validation lib
        $this->form_validation->set_rules('trnsfr_pymnt_amount', 'Amount', 'required');
		if($trnsfr_pymnt_paying_by=='Credit Card'){
			$this->form_validation->set_rules('trnsfr_pymnt_crdt_card_type', 'Card Type', 'required');
			$this->form_validation->set_rules('trnsfr_pymnt_crdt_card_no', 'Credit Card No', 'required');
			$this->form_validation->set_rules('trnsfr_pymnt_crdt_card_holder_name', 'Holder Name', 'required');
			$this->form_validation->set_rules('trnsfr_pymnt_crdt_card_month', 'Month', 'required');
			$this->form_validation->set_rules('trnsfr_pymnt_crdt_card_year', 'Year', 'required');
		}
		if($trnsfr_pymnt_paying_by=='Cheque'){
			$this->form_validation->set_rules('trnsfr_pymnt_cheque_no', 'Cheque No', 'required');
		}
		$this->form_validation->set_rules('trnsfr_id', 'System Error', 'required');


        if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
			$data=array(
				'trnsfr_pymnt_amount'=>$trnsfr_pymnt_amount,	
				'trnsfr_pymnt_ref_no'=>$trnsfr_pymnt_ref_no,
				'trnsfr_pymnt_paying_by'=>$trnsfr_pymnt_paying_by,
				'trnsfr_pymnt_date_time'=>$trnsfr_pymnt_date_time_send,
				'trnsfr_pymnt_note'=>$trnsfr_pymnt_note,
				'user_id'=>$user_id,
				'trnsfr_id'=>$trnsfr_id,
				'trnsfr_pymnt_added_date_time'=>$trnsfr_pymnt_added_date_time,
				'trnsfr_pymnt_cheque_no'=>$trnsfr_pymnt_cheque_no,
				'trnsfr_pymnt_crdt_card_no'=>$trnsfr_pymnt_crdt_card_no,
				'trnsfr_pymnt_crdt_card_holder_name'=>$trnsfr_pymnt_crdt_card_holder_name,
				'trnsfr_pymnt_crdt_card_type'=>$trnsfr_pymnt_crdt_card_type,
				'trnsfr_pymnt_crdt_card_month'=>$trnsfr_pymnt_crdt_card_month,
				'trnsfr_pymnt_crdt_card_year'=>$trnsfr_pymnt_crdt_card_year,
				'trnsfr_payment_type' => $trnsfr_type
			);
			
               if ($this->Transfer_Model->save_trnsfr_payments($data,$trnsfr_pymnt_id)) {
                    $st = array('status' =>1,'validation' =>'Done!');
                    echo json_encode($st);
               } else {
                    $st = array('status' =>0,'validation' =>'error occurred please contact your system administrator');
                    echo json_encode($st);
               }
		}
	}	
	
	//Transfers payment page 
	public function payments()
	{
        $data['trnsfr_id'] = $this->input->get('id');
        $data['trnsfr_type'] = $this->input->get('trnsfr_type');
        $this->load->view('models/transfer_payment',$data);	
	}
	
	//Transfers save 
	//Transfers item save
	//Add transfer items to 54 table
	public function save_transfer()
	{
		$trnsfr_reference_no=$this->input->post('trnsfr_reference_no');
		$trnsfr_from_warehouse_id=$this->input->post('trnsfr_from_warehouse_id');
		$trnsfr_to_warehouse_id=$this->input->post('trnsfr_to_warehouse_id');
		$rowCount=$this->input->post('rowCount');
		
		$trnsfr_datetime_1=$this->input->post('trnsfr_datetime');
		$trnsfr_datetime=date('Y-m-d H:i:s', strtotime($trnsfr_datetime_1));
		$trnsfr_inv_discount=$this->input->post('trnsfr_inv_discount');		
		$trnsfr_total=$this->input->post('trnsfr_total');
		
		$trnsfr_datetime_created=date('Y-m-d H:i:s');
		
		//start get next referance no
		$warehouse_dtls=$this->Warehouse_Model->get_warehouse_info($trnsfr_from_warehouse_id);
		$warehouse_code=$warehouse_dtls['code'];
		$warehouse_last_id=(1+$this->Common_Model->get_next_warehouse_ref_no($trnsfr_from_warehouse_id,'trnsfr_from_warehouse_id','warehouse_last_id','transfer'));
		$trnsfr_reference_no=$warehouse_code.'/T/'.sprintf("%04d",$warehouse_last_id);
		//end get next referance no
		
		
		$error='';
		$disMsg='';
		$lastid='';
		$trnsfr_id='';
		
		if(!$error){
			$data=array(
				'trnsfr_reference_no'=>$trnsfr_reference_no,
				'warehouse_last_id'=>$warehouse_last_id,
				'trnsfr_from_warehouse_id'=>$trnsfr_from_warehouse_id,
				'trnsfr_to_warehouse_id'=>$trnsfr_to_warehouse_id,
				'trnsfr_datetime'=>$trnsfr_datetime,
				'trnsfr_total'=>$trnsfr_total,
				'trnsfr_datetime_created'=>$trnsfr_datetime_created,
				'user_id'=>$this->session->userdata('ss_user_id'),
				'trnsfr_note'=>$this->input->post('trnsfr_note')
			);
			$_insert=$this->Transfer_Model->save_transfer($data,$trnsfr_id);
			$lastid=$this->db->insert_id();
			$trnsfr_id=$lastid;
			$disMsg='Transfer successfully added';
			
			//insert sale item data
			$row=$this->input->post('row');
			$rowCount=$this->input->post('rowCount');
			$data_item=array();
			for($i=1; $i<=$rowCount; $i++){
				if(isset($row[$i]['product_id'][0]))
				{
					
				$data_item=array(
					'trnsfr_id'=>$trnsfr_id,
					'product_id'=>$row[$i]['product_id'][0],
					'trnsfr_itm_quantity'=>$row[$i]['qty'][0],
					
					'trnsfr_itm_unit_price'=>$row[$i]['unit_price'][0],
				
				);
				$this->Transfer_Model->save_transfer_item($data_item);
				$itemid=$this->db->insert_id();
				
				//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],	
							'trnsfr_id'=>$trnsfr_id,
							'trnsfr_item_id'=>$itemid,
							'tis_number'=>$pieces_sn[$h],
							
						);
				  		$this->Transfer_Model->save_transfer_serial_numbers($sn_data);
						
						
				//update grn serial number sold status
				$pis_number=$pieces_sn[$h];
				$sn_data=array(	
					'trnsfr_id'=>$trnsfr_id,
					'pis_transferred'=>1,
					'product_avalable'=>2, // trnser aprove update
						//	'avalable_warehouse_id'=>$trnsfr_to_warehouse_id,
							'sale_inv_id'=>0,
							'pis_sold'=>0,
							'pis_sales_return'=>0,
				);
				$this->Purchases_Model->update_grn_serial_numbers($sn_data,$pis_number);
				
						
					}
                    //end add serial numbers
				}
				
				
				//add reford for f4 table
				$type='transfer';
				$ref_id=$trnsfr_id;
				$product=$row[$i]['product_id'][0];
				$trnsfr_itm_quantity=$row[$i]['qty'][0];
				$unit_cost=$row[$i]['unit_price'][0];
				$this->Common_Model->add_fi_table($type,$ref_id,$product,$trnsfr_itm_quantity,$unit_cost);
				}
			}
		
		}else {
			
			$disMsg='Please select these before adding any product:'.$disMsg;
		}	
		
		$this->session->set_flashdata('message', 'Transfer successfully added!');
		
		echo json_encode(array('trnsfr_id'=>$lastid,'error'=>$error,'disMsg'=>$disMsg,));
	}

	//Transfers reference no jenarate	
	public function get_next_ref_no(){
		$query=$this->Transfer_Model->get_next_ref_no();
		$result = $query->row();
		//print_r($result);
		$trnsfr_reference_no=sprintf("%05d", $result->trnsfr_id+1);
		$trnsfr_reference_no=$trnsfr_reference_no;
		echo json_encode(array('trnsfr_reference_no'=>$trnsfr_reference_no));
	}
	
	//Transfers ger avalable product qty
	public function get_avalable_product_qty(){
		$product_id=$this->input->get('product_id');
		$warehouse_id=$this->input->get('warehouse_id');
		
		$data['total']=$this->Transfer_Model->get_avalable_product_qty($product_id,$warehouse_id);
		echo json_encode(array('remmnaingQty'=>$data['total']));
	}

	//Transfers add form
    public function transfer_add()
    {
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = 'transfer_add';
		
		//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();
		
        $this->load->view('transfer_add',$data);
    }
	
	//Transfers product items get
	 public function suggestions($value='')
    {
		$term=$this->input->get('term');
		$warehouse_id=$this->input->get('warehouse_id');
			$manual_search=$this->input->get('manual_search');
			
		$data['transfer'] = $this->Sales_Model->get_products_suggestions($term,'',$warehouse_id,$manual_search);
		
		$json = array();
		//echo "Count:".count($data['transfer']);
		//print_r($data['transfer']);
		foreach ($data['transfer'] as $row)
		{
			$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=$row['product_price'];
			
			$product_w=$row['product_w'];
			$product_sn_exissts=$row['product_sn_exissts'];
			
			$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";
			
			$is_search_by_sn=0;
			$product_sn=0;
			if($row['pis_number']==$term){
				$is_search_by_sn=1;
				$product_sn=$row['pis_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'=> $row['product_price'],
					'product_part_no'=> $row['product_part_no'],
					'item_cost'=> $row['product_cost'],
					'product_w'=> $product_w,
					'product_sn'=>$product_sn,
					'product_sn_exissts'=> $product_sn_exissts,
					'is_search_by_sn'=> $is_search_by_sn,
					'product_oem_part_number'=> $row['product_oem_part_number'],
                    'value'=> $row['product_name']." (".$row['product_code'].")",
                    'label'=> $row['product_name']." (".$row['product_code'].")$extraName  | SN: $row[pis_number]"
                    );
					array_push($json,$json_itm);
		}		
		
		
		$data['sales_non_seril'] = $this->Sales_Model->get_non_serial_products_suggestions($term);
		//echo $this->db->last_query();
		
	//	print_r($data['sales_non_seril']);
		foreach ($data['sales_non_seril'] as $row)
		{
			$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=$row['product_price'];
			
			$product_w='';//$row['product_w'];
			$product_sn_exissts=$row['product_sn_exissts'];
			
			$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";
			
			$is_search_by_sn=0;
			$product_sn=0;
			
			
			 $json_itm=array(
			 		'id'=> $row['product_id'],
					'product_id'=> $row['product_id'],
					'product_code'=> $row['product_code'],
					'product_name'=> $row['product_name'],
					'product_price'=> $row['product_price'],
					'product_part_no'=> $row['product_part_no'],
					'item_cost'=> $row['product_cost'],
					'product_w'=> $product_w,
					'product_sn'=>$product_sn,
					'product_sn_exissts'=> $product_sn_exissts,
					'is_search_by_sn'=> $is_search_by_sn,
					'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);		
    }
	
	//Sale details page
	public function trnsfr_details()
	{
		
		$trnsfr_id=$this->input->get('trnsfr_id');
		$data['trnsfr_details']= $this->Transfer_Model->get_trnsfr_info($trnsfr_id);
		
		//get sale item list
		$data['trnsfr_item_list']= $this->Transfer_Model->get_trnsfr_item_list_by_trnsfr_id($trnsfr_id);
		
		
		$data['warehouse_details']= $this->Warehouse_Model->get_warehouse_info($data['trnsfr_details']['trnsfr_from_warehouse_id']);
		$data['to_warehouse_details']= $this->Warehouse_Model->get_warehouse_info($data['trnsfr_details']['trnsfr_to_warehouse_id']);
		
		$data['cr_limit_list'] = $this->Common_Model->get_all_cr_limit();
		$data['trnsfr_id'] = $trnsfr_id;
        $this->load->view('models/transfer_print',$data);
	}	
	
	//Transfers list
	public function list_transfer()
	{
	$requestData= $_REQUEST;
	$search_key=$this->input->get('search');
	$warehouse_id=$this->input->get('warehouse_id');
	$search_key_val=$search_key['value'];
	$start=$this->input->get('start');
	$length=$this->input->get('length');
		$to_warehouse_id=$this->input->get('to_warehouse_id');
	
	$columns = array( 
		0 =>'trnsfr_id', 
		1 => 'trnsfr_id',
		2=> 'trnsfr_id',
		3 =>'trnsfr_id', 
		4 => 'trnsfr_id',
		5=> 'trnsfr_id'
	);
	
	$data = array();
	//$transfer = $this->Transfer_Model->get_all_transfer();
	$transfer_tot = $this->Transfer_Model->get_all_transfer("","","","","",$warehouse_id,$to_warehouse_id);
	$transfer = $this->Transfer_Model->get_all_transfer($start,$length,$search_key_val,"","",$warehouse_id,$to_warehouse_id);
	$totalData = count($transfer_tot);
	$totalFiltered = $totalData;  
	
	foreach ($transfer as $row){
		$nestedData=array(); 
		$trnsfr_id=$row['trnsfr_id'];
		$total_paid_amount='';
		$nestedData[] =$row['trnsfr_id'];
		$nestedData[] =display_date_time_format($row['trnsfr_datetime']);
		$nestedData[] = $row['trnsfr_reference_no'];
		$fromwhe=$this->Transfer_Model->getwarehousename($row['trnsfr_from_warehouse_id']);
		$nestedData[] = $fromwhe['name'];
		$towhe=$this->Transfer_Model->getwarehousename($row['trnsfr_to_warehouse_id']);
		$nestedData[] = $towhe['name'];		
		$nestedData[] =number_format($row['trnsfr_total'], 2, '.', ',');		
		$url=base_url("transfer/trnsfr_details?trnsfr_id=$trnsfr_id");
		$actionTxtUpdate='<a onClick="fbs_click('.$row['trnsfr_id'].')" data-toggle="modal" href="#" class="btn btn-xs btn-blue tooltips" data-placement="top" data-original-title="Edit suppliers"><i class="clip-zoom-in-2"></i></a> &nbsp;';
		
		$actionTxtViewDetails='<a href="'.base_url().'transfer/view/'.$trnsfr_id.'" class="btn btn-xs btn-blue tooltips" data-placement="top" data-original-title="Edit suppliers"><i class="fa fa-file-text-o"></i></a> &nbsp;';
	
	$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 onClick="fbs_click('.$row['trnsfr_id'].')" data-toggle="modal" href="#" data-placement="top" data-original-title="Edit suppliers"><i class="fa fa-print"></i> Print Transfer</a></li>
							<li><a href="'.base_url().'transfer/view/'.$trnsfr_id.'" class="" data-placement="top" data-original-title="Edit suppliers"><i class="fa fa-file-text-o"></i> Details</a><li>
							
                            </ul></div>';
							
							/*<li><a href="'.base_url().'transfer/view/'.$trnsfr_id.'"><i class="fa fa-file-text-o"></i> Transfer Details</a></li>*/
	
	$data[] = $nestedData;
}

	$json_data = array(
			//"draw"            => intval( $requestData['draw'] ),  
			"recordsTotal"    => intval( $totalData ),  
			"recordsFiltered" => intval( $totalFiltered ),
			"data"            => $data 
			);

	echo json_encode($json_data); 
	}
}