<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Inventory_purchase_receive extends REF_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->library('upload');
        $this->load->model('purchase_management_model', '', TRUE);
        $this->uri_key_index = 0;
    }
    
    public function index() {
        $data 				= array();
        //$data['results'] 	= $this->purchase_management_model->list_all();
        
		if (!empty($this->session->flashdata('success'))) 
            $data['success'] = $this->session->flashdata('success');
        else 
            $data['error'] = $this->session->flashdata('error');
        
        $service_menu_id 			= get_inventory_controller_id($actions['controller']);
        $data['add_btn']    		= 'Purchase Received Item';
		$data['add_link']   		= base_url().'inventory_purchase_receive/purchase_received_item';
		$data['view_link']   		= base_url().'inventory_purchase_receive/received_details/';
		$data['service_menu_id'] 	= array('service_menu_id' => $service_menu_id, 'menu_type' => '5');
		$data['results'] 			= $this->purchase_management_model->purchase_received_list();
		//echo "<pre>"; print_r($data['results']); exit;
		$this->render($data, 'inventory_purchase_receive/list');
    }
	
	public function received_details($id) {
        $data 						= array();
        
		$data['purchase_order'] 	= $this->purchase_management_model->get_by_id($id);
		$data['supplier'] 			= $this->purchase_management_model->get_supplier_by_id($data['purchase_order']->supplier_id);
		$data['purchase_received'] 	= $this->purchase_management_model->purchase_received_order($id);
		//echo "<pre>"; print_r($data['purchase_order']);print_r($data['purchase_received']); echo "</pre>";
        $this->render($data, 'inventory_purchase_receive/view');
    }
	
	public function purchase_received_item() {
        $data 				= array();
        //$data['results'] 	= $this->purchase_management_model->list_all();
        
		if (!empty($this->session->flashdata('success'))) 
            $data['success'] = $this->session->flashdata('success');
        else 
            $data['error'] = $this->session->flashdata('error');
        
        $service_menu_id 			= get_inventory_controller_id($actions['controller']);
        $data['service_menu_id'] 	= array('service_menu_id' => $service_menu_id, 'menu_type' => '5');
		$data['results'] 			= $this->purchase_management_model->purchase_order_list();
        $this->render($data, 'inventory_purchase_receive/add');
    }
    
    private function get_purchase_url_key($name, $id = '') {
        $url_key = get_url_key($name);
        if ($this->purchase_management_model->purchase_url_key_exists($url_key, $id)) {
            $this->uri_key_index ++;
            return $this->get_purchase_url_key($name . '_' . $this->uri_key_index, $id);
        }
        
        return $url_key;
    }
    
    function update_avail_qty($items = array()){
        /*
         *  Update "General Inventory" Qty
         */
        $is_add = $items['page'] == 'add' ? TRUE : FALSE;
        unset($items['page']);
        
        $inv_items = $pois = array();
        foreach($items as $item_id => $itm) :                
			/*
			 * Get Prev. Avail Qty
			 */
			$this->db->order_by('id desc');
			$q 		= $this->db->get_where(TBL_INV_LOG, array('inv_item_id' => $item_id, 'status' => 1, 'type' => 3));
			$log 	= $q->row_array();

			// Mark prev. row as Inactive
			$this->db->update(TBL_INV_LOG, array('status' => 0), array('id' => $log['id']));
			
			/*
			 * Get Inventory Items
			 */
			if( !array_key_exists( $item_id, $inv_items) ) :
				$this->db->order_by('id desc');
				$q 						= $this->db->get_where(TBL_INVENTORY_ITEM, array('id' => $item_id));
				$item 					= $q->row_array();                
				$inv_items[$item_id] 	= $item;
			else :
				$item 					= $inv_items[$item_id];
			endif;               
			
			/*
			 * Get Last Purchase Entry Item
			 */
			
			$itm['category_id'] 	= $log['inv_cat_id'];
			$itm['item_id']     	= $log['inv_item_id'];
			$itm['uom']         	= $log['uom'];
			$itm['unit_price']  	= $log['cost_price'];
			$itm['sell_price']  	= $log['sell_price'];
			$itm['quantity']    	= $log['inv_qty']; 			
			$now_avail_qty     	 	= $log['now_avail_qty'] + $itm['received_qty'];
			
			
			$args = array(
				'type'          => 3,
				'inv_cat_id'    => $itm['category_id'],
				'inv_item_id'   => $itm['item_id'],
				'uom'           => $itm['uom'],
				'cost_price'    => $itm['unit_price'],//$poi['unit_price'],
				'sell_price'    => !empty( $itm['sell_price'] ) ? $itm['sell_price'] : 0,
				'inv_qty'       => $itm['quantity'],
				'prev_avail_qty'=> !empty( $log['now_avail_qty'] ) ? $log['now_avail_qty'] : 0,
				'now_avail_qty' => $now_avail_qty,
				'total_issued_qty'=> !empty( $log['total_issued_qty'] ) ? $log['total_issued_qty'] : 0,
				'bal_issued_qty'=> !empty( $log['bal_issued_qty'] ) ?  $log['bal_issued_qty'] : 0,    
				'desc'          => 'Received Purchase Item qty .'.$itm['received_qty'],
				'status'        => $now_avail_qty > 0 ? 1 : 2,
				'created_on'    => date("Y-m-d H:i:s"),
				'created_by'    => $this->user_data['user_id'],
			);
			
			$this->db->insert( TBL_INV_LOG, $args );
                    
        endforeach;
    }
    
    public function edit() {       
        $ref_no					= $_POST['ref_no'];
		
        $data 					= array();
        $data['suppliers'] 		= $this->purchase_management_model->supplier_list();
        $data['categories'] 	= $this->purchase_management_model->category_list();
        $data['purchase'] 		= $this->purchase_management_model->get_by_purchase_ref_no($ref_no);
		$data['po_items'] 		= $this->purchase_management_model->get_items_by_po_id($data['purchase']->id);
        //$data['used_po_items'] 	= $this->purchase_management_model->get_used_items_by_po_id($data['purchase']->id);
        $actions 				= $this->actions();
        $data['form_action'] 	= $actions['update'] . '/' . $data['purchase']->id;
		
		if($data['purchase']){
			$html = $this->load->view('inventory_purchase_receive/edit', $data, true);
			echo $html;
		}else{
			$html = '';					
			echo $html;
		}
    }
    
    public function update($id = '') {
        
        if (empty($id)) {
            show_400_error();
        }
        $items					= array();
        $post 					= $this->input->post();
		$total_recedived_qty	= 0;
       //echo '<pre>'; print_r( $post ); die; 
	   
	  //	$purchase_rec_order		= $this->purchase_management_model->get_purchase_rec_order_by_ref($this->input->post('purchase_ref_no'));
        //echo "<pre>"; print_r($purchase_rec_order); exit;
		
		
		$insert_receive 		= array(
									'po_id' => $this->input->post('hidden_id'),
									'purchase_ref' => $this->input->post('purchase_ref_no'),
									'received_date' => date('Y-m-d',strtotime($post['received_date'])),
									'created_at' => date('Y-m-d H:i:s')
								);
		$insertID				= $this->purchase_management_model->insert_receive($insert_receive);
	
		
		for($i = 0; $i < count($post['item_id']); $i++){
			if(!empty($post['receive_qty'][$i])){
				$total_recedived_qty	= $total_recedived_qty + $post['receive_qty'][$i];
				$insert = array(
					'por_id'	=> $insertID,
					'purchase_Id' => $this->input->post('hidden_id'),
					'purchase_ref' => $this->input->post('purchase_ref_no'),
					'received_date' => date('Y-m-d',strtotime($post['received_date'])),
					'category_Id' => $post['category_id'][$i],
					'item_Id' => $post['item_id'][$i],
					'total_qty' => $post['qty'][$i],
					'received_qty' => $post['receive_qty'][$i],
					'balance_qty' => $post['qty'][$i] - ($post['received_qty'][$i] + $post['receive_qty'][$i]),
					'status' => 1,
					'created_by' => $this->user_data['user_id'],
					'created_on' => date('Y-m-d H:i:s')
				);
				
				$items[$post['item_id'][$i]] = $insert;			
				if($this->purchase_management_model->insert_receive_qty($insert)){					
					$this->session->set_flashdata('success', 'Purchase received qty details updated successfully');
				}else{
					$this->session->set_flashdata('error', 'Purchase received qty details not updated!'); 
				}				
			}else{
				$this->session->set_flashdata('error', 'Purchase received qty not updated!'); 
			}
		}
		
		$update_args	= array('received_qty' => $total_recedived_qty);
		$this->purchase_management_model->update_receive_qty($update_args, $insertID);
		
		$items['page'] = 'add';
        $this->update_avail_qty($items);
        redirect('inventory_purchase_receive','refresh');
    }
	  
    public function get_items_by_cat_id(){
        $data['items'] =  $this->purchase_management_model->get_items_by_cat_id($_POST['category_id']);
        echo json_encode($data);
        exit(0);
    }
    
    public function get_unit_by_item_id() {
        $data['item'] =  $this->purchase_management_model->get_unit_by_item_id($_POST['item_id']);
        echo json_encode($data);
        exit(0);
    }
    
    public function check_valid_qty() {
        $data =  $this->purchase_management_model->check_valid_qty($_POST['po_item_id']);
        echo json_encode($data);
        exit(0);
    }
    
    function ajax(){
        echo json_encode( $this->purchase_management_model->ajax() );        
    }
	
	public function get_received_items(){
		$item_id 		= $_POST['itemID'];
		$receivedItems	= $this->purchase_management_model->purchase_received_items($item_id);
		
		//echo "<pre>"; print_r($receivedItems); echo "</pre>";
		$html			= '';
		
		if($receivedItems){
			$html .= '<td colspan="6"><table class="table table-bordered table-striped">';
			$html .= '<tr><th>S.No</th><th>Received Item</th><th>Received Date</th></tr>';			
			foreach($receivedItems as $jo => $item){
				$html .= '<tr><td>'.++$jo.'</td><td>'.$item->received_qty.'</td><td>'.date("d-m-Y", strtotime($item->received_date)).'</td></tr>';	
			}
            $html .= '</table></td>';
		}else{
			$html .= '<td colspan="6">Not yet received items</td>';
		}
		
		echo $html;
	}
}
?>