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

class Mros extends Secure_area
{
	var $CI;
	function __construct()
	{
		parent::__construct('mros');
		$this->CI =& get_instance();
		$this->load->library('mro_lib');
		$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->mro_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->mro_lib->set_location($location_id);
		}
		else
		{
			$data['error']=lang('receivings_unable_to_add_location');
		}
		$this->_reload($data);
	}

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


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

	function add()
	{       $location = $this->session->userdata('employee_current_location_id');
		$data=array();
		$mode = $this->mro_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->mro_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->mro_lib->is_valid_receipt($item_id_or_number_or_item_kit_or_receipt) && $mode=='return')
		{
			$this->mro_lib->return_entire_receiving($item_id_or_number_or_item_kit_or_receipt);
		}
		elseif($this->mro_lib->is_valid_item_kit($item_id_or_number_or_item_kit_or_receipt))
		{
			$this->mro_lib->add_item_kit($item_id_or_number_or_item_kit_or_receipt);
		}
		elseif(!$this->mro_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->mro_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->mro_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->mro_lib->edit_item($item_id,$description,$serialnumber,$quantity,$discount,$price,$lot_no,$expiry);
					}
			}else{
				$this->mro_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->mro_lib->delete_item($item_number);
		$this->_reload();
	}

	function delete_supplier()
	{
		$this->mro_lib->delete_supplier();
		$this->_reload();
	}
        
	function complete()
	{
		$data['cart']=$this->mro_lib->get_cart();
		if (empty($data['cart']))
		{
			redirect('mros');
		}
		
		$data['receipt_title']='Material Request Order Receipt';
		$employee_id=$this->Employee->get_logged_in_employee_info()->person_id;
		$comment = $this->input->post('comment');
		$emp_info=$this->Employee->get_info($employee_id);
		$mro_purpos = $this->input->post('mro_purpos');
		$data['mro_purpos']=$this->input->post('mro_purpos');
		$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 Mro to database
		$mroID =  $this->mro->save($data['cart'],$employee_id,$data['employee'],$comment,$mro_purpos,'');		
		$data['receiving_id']='MRO '.$mroID;
                                
		if ($data['receiving_id'] == 'MRO -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
		$mro_info = $this->mro->get_info($mroID)->row_array();
		$data['transaction_time']= date(get_date_format().' '.get_time_format(), strtotime($mro_info['mro_time']));
		$this->load->view("mros/receipt",$data);
		$this->mro_lib->clear_all();
		$this->removeDuplicateSessionCookieHeaders();
	}

	function receipt($mro_id)
	{
		$receiving_info = $this->mro->get_info($mro_id)->row_array();
		$this->mro_lib->copy_entire_receiving($mro_id);
		$data['cart']=$this->mro_lib->get_cart();
		$data['total']=$this->mro_lib->get_total();
		$data['receipt_title']=('Material Request Order Receipt');
		$data['transaction_time']= date(get_date_format().' '.get_time_format(), strtotime($receiving_info['mro_time']));
		$supplier_id=$this->mro_lib->get_supplier();
		$emp_info=$this->Employee->get_info($receiving_info['employee_id']);
		$data['mro_purpos']=$receiving_info['mro_purpos'];

		$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;
		$data['comment']=$receiving_info['comment'];

		$data['receiving_id']='MRO '.$mro_id;
		$this->load->view("mros/receipt",$data);
		$this->mro_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['mro_no'] = $this->mro->get_max_id();
		$person_info = $this->Employee->get_logged_in_employee_info();
		$data['employee_id'] = $person_info->person_id;
		$data['cart']=$this->mro_lib->get_cart();
		$data['modes']=array('mro'=>'Mro');
		$data['locations_allocated'] = $this->Location->get_locations_allocated();
		$data['mode']=$this->mro_lib->get_mode();
                
		$data['total']=$this->mro_lib->get_total();
		$data['items_in_cart'] = $this->mro_lib->get_items_in_cart();
		$data['items_module_allowed'] = $this->Employee->has_module_permission('items', $person_info->person_id);

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

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

}
?>