<?php
require_once ("secure_area.php");
error_reporting(0);
class Receivings extends Secure_area
{
	var $CI;
	function __construct()
	{
		parent::__construct('receivings');
		$this->load->model('po');
		$this->CI =& get_instance();
		$this->load->library('receiving_lib');
	}

	function index()
	{
            $this->_reload(array(), false);
	}

	function item_search()
	{
		$suggestions = $this->Item->get_item_search_suggestions($this->input->get('term'),100);
		$suggestions = array_merge($suggestions, $this->Item_kit->get_item_kit_search_suggestions($this->input->get('term'),100));
		echo json_encode($suggestions);
	}

	function supplier_search()
	{
		$suggestions = $this->Supplier->get_suppliers_search_suggestions($this->input->get('term'),100);
		echo json_encode($suggestions);
	}

	function select_supplier()
	{
		$data = array();
		$supplier_id = $this->input->post("supplier");
		
		if ($this->Supplier->exists($supplier_id))
		{
			$this->receiving_lib->set_supplier($supplier_id);
		}
		else
		{
			$data['error']=lang('receivings_unable_to_add_supplier');
		}
		$this->_reload($data);
	}

	function location_search()
	{
		$suggestions = $this->Location->get_locations_search_suggestions($this->input->get('term'),100);
		echo json_encode($suggestions);
	}

	function select_location()
	{
		$data = array();
		$location_id = $this->input->post("location");
		
		if ($this->Location->exists($location_id))
		{
			$this->receiving_lib->set_location($location_id);
		}
		else
		{
			$data['error']=lang('receivings_unable_to_add_location');
		}
		$this->_reload($data);
	}

	function delete_location()
	{
		$this->receiving_lib->delete_location();
		$this->_reload();
	}


	function change_mode()
	{
		$mode = $this->input->post("mode");
		$this->receiving_lib->set_mode($mode);
        if ($mode == 'supplier_store_accounts')
		{
			$store_account_payment_item_id = $this->Item->create_or_update_store_account_item();
			$this->receiving_lib->empty_cart();
			$this->receiving_lib->add_item($store_account_payment_item_id,1);
		}elseif($mode=='transfer' || $mode=='transfer_return'){
			$this->receiving_lib->delete_supplier();
		}
		$this->_reload();
	}

	function add()
	{       $location = $this->session->userdata('employee_current_location_id');
		$data=array();
		$mode = $this->receiving_lib->get_mode();
		$item_id_or_number_or_item_kit_or_receipt = $this->input->post("item");
                $exist = $this->Item_location->get_total_quantity($item_id_or_number_or_item_kit_or_receipt,$location);
		if($exist>0 || $mode == 'receive' || $mode=='transfer_return'){
                $quantity = $mode=="receive" ? 1:1;
			if($mode=='transfer_return'){
				$quantity = 1;
				$location_id=$this->receiving_lib->get_location();
				if($location_id!=-1)
				{
					
				}else{
                    $data['error'] = 'First select location for transfer return ';
					$error_in_transfer = true;
				}
                $exist_in_tranfering_location = $this->Item_location->get_total_quantity($item_id_or_number_or_item_kit_or_receipt,$location_id);
				if($exist_in_tranfering_location<=0){
                    $data['error'] = 'Zero items in location for transfer return ';					
					$error_in_transfer = true;
				}
			}
		if(isset($error_in_transfer) && $error_in_transfer==true){
			$this->_reload($data);
			return false;
			//exit;
		}

		if($this->receiving_lib->is_valid_receipt($item_id_or_number_or_item_kit_or_receipt) && $mode=='return')
		{
			$this->receiving_lib->return_entire_receiving($item_id_or_number_or_item_kit_or_receipt);
		}
		elseif($this->receiving_lib->is_valid_item_kit($item_id_or_number_or_item_kit_or_receipt))
		{
			$this->receiving_lib->add_item_kit($item_id_or_number_or_item_kit_or_receipt);
		}
		elseif(!$this->receiving_lib->add_item($item_id_or_number_or_item_kit_or_receipt,$quantity))
		{
			$data['error']=lang('receivings_unable_to_add_item');
		}
                }else{
                    $data['error'] = lang('items_not_exist');
                }
		$this->_reload($data);
	}

	function edit_item($item_id)
	{
		$data= array();
		$this->form_validation->set_rules('price', 'lang:items_price', 'numeric');
		$this->form_validation->set_rules('quantity', 'lang:items_quantity', 'numeric');
		$this->form_validation->set_rules('discount', 'lang:items_discount', 'numeric');
                $description = $this->input->post("description");
                $serialnumber = $this->input->post("serialnumber");
		$price = $this->input->post("price");
		$quantity = $this->input->post("quantity");
		$discount = $this->input->post("discount");
		$mode = $this->input->post("mode");
		
		$lot_no = $this->input->post("lot_no");
		$expiry = $this->input->post("expiry");
		$selected_item_id = $this->input->post("selected_item_id");
		$quantity2 = abs($quantity);

		if ($this->form_validation->run() != FALSE)
		{
			
			if(isset($mode) && $this->input->post("mode") == 'transfer')
			{

				$item_location_quantity =$this->CI->Item_location->get_location_quantity($selected_item_id)+0;
				if($quantity2>$item_location_quantity)
				{
					$data['warning'] = 'Transfer QTY is Greater then avaliable stock';
				}else{
					$this->receiving_lib->edit_item($item_id,$description,$serialnumber,$quantity,$discount,$price,$lot_no,$expiry);
				}
			}elseif(isset($mode) && $this->input->post("mode") == 'transfer_return'){
				    $location_id2=$this->receiving_lib->get_location();
					$qty_in_tranfering_location = $this->Item_location->get_item_location_total_quantity($selected_item_id,$location_id2)+0;
					if($quantity2>$qty_in_tranfering_location){
						$data['warning'] = 'Transfer QTY is Greater then avaliable stock in returning location';
					}else{
						$this->receiving_lib->edit_item($item_id,$description,$serialnumber,$quantity,$discount,$price,$lot_no,$expiry);
					}
			}else{
				$this->receiving_lib->edit_item($item_id,$description,$serialnumber,$quantity,$discount,$price,$lot_no,$expiry);
			}
		}
		else
		{
			$data['error']=lang('receivings_error_editing_item');
		}
                
                

		$this->_reload($data);
	}

	function delete_item($item_number)
	{
		$this->receiving_lib->delete_item($item_number);
		$this->_reload();
	}

	function delete_supplier()
	{
		$this->receiving_lib->delete_supplier();
		$this->_reload();
	}
        
	function complete()
	{
		$data['cart']=$this->receiving_lib->get_cart();
		if (empty($data['cart']))
		{
			redirect('receivings');
		}
		
		$data['total']=$this->receiving_lib->get_total();

		$data['receipt_title']=ucfirst(str_replace('_',' ',$this->receiving_lib->get_mode())).' Receipt';
		$data['transaction_time']= date(get_date_format().' '.get_time_format());
		$supplier_id=$this->receiving_lib->get_supplier();
		$location_id=$this->receiving_lib->get_location();
        if($location_id!='-1'){
			$location_info=$this->Location->get_info($location_id);
			$data['location2']=$location_info->name;
		}else{
			$data['location2']='';
		}
		        
		$employee_id=$this->Employee->get_logged_in_employee_info()->person_id;
		$comment = $this->input->post('comment');
		$emp_info=$this->Employee->get_info($employee_id);
		$payment_type = $this->input->post('payment_type');
		if( $this->input->post('po_id')>0){
		$po_id  = $this->input->post('po_id');
		}else{
			$po_id = 0;}
		$data['po_id']  = $po_id;
		$data['payment_type']=$this->input->post('payment_type');
		$data['receiving_type']=$this->receiving_lib->get_mode();
		$data['mode']=$this->receiving_lib->get_mode();
                if ($this->input->post('amount_tendered'))
		{
			$data['amount_tendered'] = $this->input->post('amount_tendered');
			$data['amount_change'] = to_currency($data['amount_tendered'] - round($data['total'], 2));
		}
		$data['employee']=$emp_info->first_name.' '.$emp_info->last_name;

		if($supplier_id!=-1)
		{	
			$suppl_info=$this->Supplier->get_info($supplier_id);		
			$data['supplier']=$suppl_info->company_name;
			if ($suppl_info->first_name || $suppl_info->last_name)
			{
				$data['supplier'] .= ' ('.$suppl_info->first_name.' '.$suppl_info->last_name.')';
			}
            $data['balance'] = $suppl_info->balance;
		}
		$user_info = $this->Employee->get_info($employee_id);
		//SAVE receiving to database
		$receivingID =  $this->Receiving->save($data['cart'], $supplier_id,$employee_id,$comment,$payment_type,false,$data['mode'],$location_id,$po_id);
		//die('here');
		$data['receiving_id']='RECV '.$receivingID;
                if($data['mode'] == "transfer" || $data['mode'] == "transfer_return"){
                    // getting customer balance linked for store credits
					$data['customer'] = $this->Customer->get_store_balance($location_id);
                    $customerBalance = $data['customer']->balance;
                    $location_id=$this->receiving_lib->get_location();
                    $customer_id = $this->Customer->get_person_info($location_id);
                    $custoemrID = $customer_id[0]->person_id;
                    if($data['mode'] == "transfer_return"){
                        $total_amount = $customerBalance - $data['total'];
                    }elseif($data['mode'] == "transfer"){
						$data['total'] = abs($data['total']);
                        $total_amount = $customerBalance + $data['total'];
                    }
                    $transfer_data = array(
						'customer_id' => $custoemrID,
						'receiving_id' => $receivingID,
						'transaction_amount' => $data['total'],
						'date' => date('Y-m-d H:i:s'),
                        'balance' => $total_amount
                    );
					// saving credit transaction for store customer account data in store_accounts table
                    $this->db->insert('store_accounts',$transfer_data); 
                    // updating customers balance
                    $this->db->set('balance',$total_amount);
                    $this->db->where('store_id', $location_id);
                    $this->db->update('customers');
                    
                }
                
                if($data['mode'] == "supplier_store_accounts" || $data['mode']=='receive' || $data['mode']=='return' || $payment_type == 'Credit Account'){
                    
                    if($payment_type == 'Credit Account' && $data['mode']=='receive'){
                        $this->db->set('balance',$data['balance'] + $data['total']);
						$comment = 'Stock Received from supplier '.$data['supplier'].'  by '.$user_info->first_name.' '.$user_info->last_name.' -> '.$comment;

                    }elseif($payment_type == 'Credit Account' && $data['mode']=='return'){
                        $this->db->set('balance',$data['balance'] - $data['total']);
						$comment = 'Stock Return to supplier '.$data['supplier'].'  by '.$user_info->first_name.' '.$user_info->last_name.' -> '.$comment;
                    }elseif($data['mode']=='supplier_store_accounts'){
                        $this->db->set('balance',$data['balance'] - $data['total']);
						$comment = 'Payment Paid to supplier '.$data['supplier'].'  by '.$user_info->first_name.' '.$user_info->last_name.' -> '.$comment;
                    }else {
                       // $this->db->set('balance',$data['balance'] -$data['total']);
					   if($data['supplier']) { $supplier_abc = $data['supplier'];} else { $supplier_abc= 'unknown'; }
						$comment = 'Stock Received from supplier '.$supplier_abc.'  by '.$user_info->first_name.' '.$user_info->last_name.' -> '.$comment;
                    }
                    
                    $this->db->where('person_id', $supplier_id);
                    $this->db->update('suppliers'); 
                    
                    $supplier_account = array(
                        'supplier_id' => $supplier_id,
                        'receiving_id' => $receivingID,
                        'transaction_amount' => -$data['total'],
                        'balance'=> $data['balance']-$data['total'],
                        'comment' => $comment,
                        
                    );
					// saving suppliers credit transaction
                    $this->db->insert('supplier_accounts',$supplier_account);
                }
                
		if ($data['receiving_id'] == 'RECV -1')
		{
			$data['error_message'] = lang('receivings_transaction_failed');
		}

		$location_info=$this->Location->get_info($this->Employee->get_logged_in_employee_current_location_id());
		$data['location']=$location_info->name;
		$data['comment']=$comment;
		// getting receiving time
		$receiving_info = $this->Receiving->get_info($receivingID)->row_array();
		$data['transaction_time']= date(get_date_format().' '.get_time_format(), strtotime($receiving_info['receiving_time']));
		
		$this->load->view("receivings/receipt",$data);
		$this->receiving_lib->clear_all();
		$this->removeDuplicateSessionCookieHeaders();
	}

	function receipt($receiving_id)
	{
		$receiving_info = $this->Receiving->get_info($receiving_id)->row_array();
		$this->receiving_lib->copy_entire_receiving($receiving_id);
		$data['cart']=$this->receiving_lib->get_cart();
		$data['total']=$this->receiving_lib->get_total();
		$data['receipt_title']=ucfirst(str_replace('_',' ',$receiving_info['receiving_type'])).' Receipt';
		$data['transaction_time']= date(get_date_format().' '.get_time_format(), strtotime($receiving_info['receiving_time']));
		$supplier_id=$this->receiving_lib->get_supplier();
		$emp_info=$this->Employee->get_info($receiving_info['employee_id']);
		$data['payment_type']=$receiving_info['payment_type'];
		$data['receiving_type']=$receiving_info['receiving_type'];
		$data['po_id']  = $receiving_info['po_id'];
		$data['mro_id'] = $receiving_info['mro_id'];
		$data['mode']  = $receiving_info['receiving_type'];
		$data['employee']=$emp_info->first_name.' '.$emp_info->last_name;
		$location_info=$this->Location->get_info($receiving_info['location_id']);
		$data['location']=$location_info->name;
		if($receiving_info['new_location_id']!='-1'){
			$location_info=$this->Location->get_info($receiving_info['new_location_id']);
			$data['location2']=$location_info->name;
		}else{
			$data['location2']='';
		}
		
		$data['comment']=$receiving_info['comment'];

		if($supplier_id!=-1)
		{
			$supplier_info=$this->Supplier->get_info($supplier_id);
						
			$data['supplier']=$supplier_info->company_name;
			if ($supplier_info->first_name || $supplier_info->last_name)
			{
				$data['supplier'] .= ' ('.$supplier_info->first_name.' '.$supplier_info->last_name.')';
			}
		}
		$data['receiving_id']='RECV '.$receiving_id;
		$this->load->view("receivings/receipt",$data);
		$this->receiving_lib->clear_all();
		$this->removeDuplicateSessionCookieHeaders();

	}
	
	function edit($receiving_id)
	{
		$data = array();

		$data['suppliers'] = array('' => 'No Supplier');
		foreach ($this->Supplier->get_all()->result() as $supplier)
		{
			$data['suppliers'][$supplier->person_id] = $supplier->company_name.' ('.$supplier->first_name . ' '. $supplier->last_name.')';
		}

		$data['employees'] = array();
		foreach ($this->Employee->get_all()->result() as $employee)
		{
			$data['employees'][$employee->person_id] = $employee->first_name . ' '. $employee->last_name;
		}

		$data['receiving_info'] = $this->Receiving->get_info($receiving_id)->row_array();
		$this->load->view('receivings/edit', $data);
	}
	
	function delete($receiving_id)
	{
		$data = array();
		
		if ($this->Receiving->delete($receiving_id))
		{
			$data['success'] = true;
		}
		else
		{
			$data['success'] = false;
		}
		
		$this->load->view('receivings/delete', $data);
		
	}
	
	function undelete($receiving_id)
	{
		$data = array();
		
		if ($this->Receiving->undelete($receiving_id))
		{
			$data['success'] = true;
		}
		else
		{
			$data['success'] = false;
		}
		
		$this->load->view('receivings/undelete', $data);
		
	}
	
	function save($receiving_id)
	{
		$receiving_data = array(
			'receiving_time' => date('Y-m-d', strtotime($this->input->post('date'))),
			'supplier_id' => $this->input->post('supplier_id') ? $this->input->post('supplier_id') : null,
			'employee_id' => $this->input->post('employee_id'),
			'comment' => $this->input->post('comment')
		);
		
		if ($this->Receiving->update($receiving_data, $receiving_id))
		{
			echo json_encode(array('success'=>true,'message'=>lang('receivings_successfully_updated')));
		}
		else
		{
			echo json_encode(array('success'=>false,'message'=>lang('receivings_unsuccessfully_updated')));
		}
	}

	function _reload($data=array(), $is_ajax = true)
	{
		$data['max_lot_no'] = $this->Receiving->get_max_lot_no();
		
		$data['po_nos'] = $this->po->get_all_pos();
	
		$person_info = $this->Employee->get_logged_in_employee_info();
		$data['cart']=$this->receiving_lib->get_cart();
		$data['modes']=array('receive'=>lang('receivings_receiving'),'return'=>lang('receivings_return'));
		$data['locations_allocated'] = $this->Location->get_locations_allocated();

		
		
		//if ($this->Location->count_all() > 1 && $this->session->userdata('employee_current_location_id') == 1 ){
			//$data['modes']['transfer']= lang('receivings_transfer');
            //$data['modes']['transfer_return'] = 'Return Transfer';
		//}
        if($this->config->item('supplier_store_accounts')) 
		{
			$data['modes']['supplier_store_accounts'] = "Credit Account Payment";
		}
		$data['mode']=$this->receiving_lib->get_mode();
                
		$data['total']=$this->receiving_lib->get_total();
		$data['items_in_cart'] = $this->receiving_lib->get_items_in_cart();
		$data['items_module_allowed'] = $this->Employee->has_module_permission('items', $person_info->person_id);
		$data['payment_options']=array(
			lang('sales_cash') => lang('sales_cash'),
			lang('sales_check') => lang('sales_check'),
			lang('sales_debit') => lang('sales_debit'),
			lang('sales_credit') => lang('sales_credit'),
                        lang('return_expire') => lang('return_expire'),
                        lang('return_valid') => lang('return_valid'),
                        lang('return_damage') => lang('return_damage'),
		);
                 if($this->config->item('supplier_store_accounts') && $this->receiving_lib->get_mode() != 'supplier_store_accounts') 
		{
			$data['payment_options']=array_merge($data['payment_options'],	array(lang('sales_store_account') => lang('sales_store_account')		
					));
		}
		
		
		$supplier_id=$this->receiving_lib->get_supplier();
		if($supplier_id!=-1)
		{
			$info=$this->Supplier->get_info($supplier_id);
			$data['supplier']=$info->company_name;
			if ($info->first_name || $info->last_name)
			{
				$data['supplier'] .= ' ('.$info->first_name.' '.$info->last_name.')';
			}
			$data['suplier_balance'] =to_currency($info->balance);
			$data['supplier_id']=$supplier_id;
                        $data['receiving_payment'] = $this->Receiving->get_supplier_receive_payment($supplier_id);
                        $data['receiving_item_payment'] = $this->Receiving->get_item_receive_payment($supplier_id);
                        //echo '<pre>';print_r($data['receiving_item_payment']); exit;
		}

		$location_id=$this->receiving_lib->get_location();
		if($location_id!=-1)
		{
			$info=$this->Location->get_info($location_id);
			$data['location']=$info->name;
			$data['location_id']=$location_id;
		}
		
		if ($is_ajax)
		{
                    $this->load->view("receivings/receiving",$data);
		}
		else
		{
                    $this->load->view("receivings/receiving_initial",$data);
		}
		
		$this->removeDuplicateSessionCookieHeaders();
	}
        

    function cancel_receiving()
    {
    	$this->receiving_lib->clear_all();
    	$this->_reload();
    }

}
?>