<?php
require_once ("secure_area.php");

class Pos extends Secure_area
{
	var $CI;
	function __construct()
	{
		parent::__construct('pos');
		$this->CI =& get_instance();
		$this->load->library('po_lib');
		$this->load->model('po');
		$this->load->model('mro');
	}

	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->po_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->po_lib->set_location($location_id);
		}
		else
		{
			$data['error']=lang('receivings_unable_to_add_location');
		}
		$this->_reload($data);
	}

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


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

	function add()
	{       $location = $this->session->userdata('employee_current_location_id');
		$data=array();
		$mode = $this->po_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);
		$exist=1;
		if($exist>0 || $mode == 'receive' || $mode=='transfer_return'){
                $quantity = $mode=="receive" ? 1:1;
			if($mode=='transfer_return'){
				$quantity = 1;
				$location_id=$this->po_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->po_lib->is_valid_receipt($item_id_or_number_or_item_kit_or_receipt) && $mode=='return')
		{
			$this->po_lib->return_entire_receiving($item_id_or_number_or_item_kit_or_receipt);
		}
		elseif($this->po_lib->is_valid_item_kit($item_id_or_number_or_item_kit_or_receipt))
		{
			$this->po_lib->add_item_kit($item_id_or_number_or_item_kit_or_receipt);
		}
		elseif(!$this->po_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->po_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->po_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->po_lib->edit_item($item_id,$description,$serialnumber,$quantity,$discount,$price,$lot_no,$expiry);
					}
			}else{
				$this->po_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->po_lib->delete_item($item_number);
		$this->_reload();
	}

	function delete_supplier()
	{
		$this->po_lib->delete_supplier();
		$this->_reload();
	}
        
	function complete()
	{
		$data['cart']=$this->po_lib->get_cart();
		if (empty($data['cart']))
		{
			redirect('pos');
		}
		$data['receipt_title']='Purchase Order Report';
		$employee_id=$this->Employee->get_logged_in_employee_info()->person_id;
		$comment = $this->input->post('comment');
		$emp_info=$this->Employee->get_info($employee_id);
		$po_purpos = $this->input->post('po_purpos');
 		$mro_id = $this->input->post('mro_id');
		$req_location_id = $this->input->post('req_location_id');
		$supplier_id = $this->input->post('supplier_id');
		$data['po_purpos']=$this->input->post('po_purpos');
		$data['mro_id'] = $this->input->post('mro_id');
		$data['req_location_id'] = $this->input->post('req_location_id');
		$data['supplier_id'] = $this->input->post('supplier_id');
		$data['employee']=$emp_info->first_name.' '.$emp_info->last_name;
		$data['location_id'] = $this->Employee->get_current_location_id();
		
		$user_info = $this->Employee->get_info($employee_id);
		//SAVE po to database
		//echo $mro_id;
		$poID =  $this->po->save($data['cart'],$employee_id,$data['employee'],$comment,$po_purpos,$mro_id,$req_location_id,$supplier_id,'');		
		$data['receiving_id']='PO '.$poID;
                                
		if ($data['receiving_id'] == 'PO -1')
		{
			$data['error_message'] = lang('receivings_transaction_failed');
		}
		
		$req_location_info=$this->Location->get_info($req_location_id);
		$data['req_location']=$req_location_info->name.' '.$req_location_info->address.' '.$req_location_info->phone;
		
		$supplier_info = $this->Supplier->get_info($supplier_id);
		$data['supplier_info'] = $supplier_info->company_name.' '.$supplier_info->address_1.' '.$supplier_info->phone_number;
		
		$location_info=$this->Location->get_info($this->Employee->get_logged_in_employee_current_location_id());
		$data['location']=$location_info->name;
		$data['comment']=$comment;
		$data['total']=$this->po_lib->get_total();
		// getting receiving time
		$po_info = $this->po->get_info($poID)->row_array();
		$data['transaction_time']= date(get_date_format().' '.get_time_format(), strtotime($po_info['po_time']));
		$this->load->view("pos/receipt",$data);
		$this->po_lib->clear_all();
		$this->removeDuplicateSessionCookieHeaders();
	}

	function receipt($po_id)
	{
		$po_info = $this->po->get_info($po_id)->row_array();
		$this->po_lib->copy_entire_receiving($po_id);
		$data['cart']=$this->po_lib->get_cart();
		$data['total']=$this->po_lib->get_total();
		$data['receipt_title']=('Purchase Order Report');
		$data['transaction_time']= date(get_date_format().' '.get_time_format(), strtotime($po_info['po_time']));
		$supplier_id=$this->po_lib->get_supplier();
		$emp_info=$this->Employee->get_info($po_info['employee_id']);
		$data['po_purpos']=$po_info['po_purpos'];
		$data['mro_id'] = $po_info['mro_id'];
		$data['employee']=$emp_info->first_name.' '.$emp_info->last_name;
		
		$req_location_info=$this->Location->get_info($po_info['req_location_id']);
		$data['req_location']=$req_location_info->name.' '.$req_location_info->address.' '.$req_location_info->phone;
		
		$supplier_info = $this->Supplier->get_info($po_info['supplier_id']);
		$data['supplier_info'] = $supplier_info->company_name.' '.$supplier_info->address_1.' '.$supplier_info->phone_number;
		
		
		$location_info=$this->Location->get_info($po_info['location_id']);
		$data['location']=$location_info->name;
		$data['comment']=$po_info['comment'];

		$data['receiving_id']='PO '.$po_id;
		$this->load->view("pos/receipt",$data);
		$this->po_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('pos/edit', $data);
	}
	
	function delete($receiving_id)
	{
		$data = array();
		
		if ($this->Receiving->delete($receiving_id))
		{
			$data['success'] = true;
		}
		else
		{
			$data['success'] = false;
		}
		
		$this->load->view('pos/delete', $data);
		
	}
	
	function undelete($receiving_id)
	{
		$data = array();
		
		if ($this->Receiving->undelete($receiving_id))
		{
			$data['success'] = true;
		}
		else
		{
			$data['success'] = false;
		}
		
		$this->load->view('pos/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['mro_nos'] = $this->mro->get_all_mros();
		
		//$data['mro_nos'] = $this->mro->get_all_mros();
		
		$data['po_no'] = $this->po->get_max_id();
		$person_info = $this->Employee->get_logged_in_employee_info();
		$data['employee_id'] = $person_info->person_id;
		$data['cart']=$this->po_lib->get_cart();
		$data['modes']=array('po'=>'Po');
		$data['locations_allocated'] = $this->Location->get_locations_all();
		$data['all_suppliers'] = $this->Supplier->get_all_active_suppliers();
		
		$data['mode']=$this->po_lib->get_mode();
                
		$data['total']=$this->po_lib->get_total();
		$data['items_in_cart'] = $this->po_lib->get_items_in_cart();
		$data['items_module_allowed'] = $this->Employee->has_module_permission('items', $person_info->person_id);

		$location_id=$this->po_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("pos/receiving",$data);
		}
		else
		{
                    $this->load->view("pos/receiving_initial",$data);
		}
		
		$this->removeDuplicateSessionCookieHeaders();
	}
        

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

}
?>