<?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');
	}
	
	//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;
        $this->load->view('transfer',$data);
	}	
	
	//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']['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');
		if(!$trnsfr_reference_no)
		{
			$query   		= $this->Transfer_Model->get_next_ref_no();
			$result  		= $query->row();
			$trnsfr_reference_no		= sprintf("%05d", $result->trnsfr_id+1);
		}
		$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');
		
		$error='';
		$disMsg='';
		$lastid='';
		$trnsfr_id='';
		
		if(!$error){
			$data=array(
				'trnsfr_reference_no'=>$trnsfr_reference_no,
				'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
			);
			$_insert=$this->Transfer_Model->save_transfer($data,$trnsfr_id);
			$lastid=$this->db->insert_id();
			$trnsfr_id=$lastid;
			$disMsg='Sale 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);
				
				//add reford for f4 table
				$type='sale';
				$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');
		$data['transfer'] = $this->Transfer_Model->get_products_suggestions($term);
		$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'];
			$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'=> $row['product_price'],
					'product_part_no'=> $row['product_part_no'],
					'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();
        $this->load->view('models/transfer_print',$data);
	}	
	
	//Transfers list
	public function list_transfer()
	{
	$requestData= $_REQUEST;
	
	$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();
	$totalData = count($transfer);
	$totalFiltered = $totalData;  
	
	foreach ($transfer as $row){
		$nestedData=array(); 
		$trnsfr_id=$row['trnsfr_id'];
		$total_paid_amount='';
		$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>
							
                            </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); 
	}
}