<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Purchase_management 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');
        
        $actions = $this->actions();
        $data['add_btn']    = 'New Inventory Purchase';
        $data['view_link']  = $actions['view'] . '/';
        $data['add_link']   = $actions['add'];
        $data['edit_link']  = $actions['edit'] . '/';
        $data['delete_link']= $actions['delete'] . '/';
        
        $service_menu_id = get_inventory_controller_id($actions['controller']);
        $data['service_menu_id'] = array('service_menu_id' => $service_menu_id, 'menu_type' => '2');
        $this->render($data, 'inventory_purchase/list');
    }
    
    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;
    }
    
    public function add() {
        $data 					= array();
        $actions 				= $this->actions();
        $inv_no 				=  _get(TBL_INVENTORY_PURCHASE, '', array('limit' => 1, 'select' => 'id', 'order_by' => 'id DESC'))['id'];
        //$inv_no = str_replace(INV_PREFIX, '', $inv_no);
        
		$data['suppliers'] 		= $this->purchase_management_model->supplier_list();
        $data['categories'] 	= $this->purchase_management_model->category_list();
		$last_ref_no			= $this->purchase_management_model->get_last_purchase_ref_no();
		
        $data['inv_no']     		= INV_PREFIX . fill_digits( empty( $inv_no ) ? 1 : ++$inv_no, 4 );
		
		if($last_ref_no > 0){
			$data['purchase_ref_no']	= $last_ref_no + 1;
		}else{
			$data['purchase_ref_no']	= 100001;
		}
		
        $data['form_action'] 	= $actions['insert'];
        $this->render($data, 'inventory_purchase/add');
    }
    
    public function insert() {
         
        $insert = array(
			'purchase_ref_no' => $this->input->post('purchase_ref_no'),
            'supplier_id' => $this->input->post('supplier_id'),
            'invoice_no' => $this->input->post('invoice_no'),
            'invoice_date' => date('Y-m-d',strtotime($this->input->post('invoice_date'))),
			'purchase_for' => $this->input->post('purchase_for'),
            'receivable_date' => date('Y-m-d',strtotime($this->input->post('received_date'))),
            'total_amount' => $this->input->post('total'),
            'payment' => $this->input->post('payment'),
			'desc' => $this->input->post('desc'),
            'url_key' => $this->get_purchase_url_key($this->input->post('invoice_no')),
            #'status' => $this->input->post('status'),
            'created_by' => $this->user_data['user_id'],
            'created_on' => date('Y-m-d H:i:s')
        );
        
        $insert_id = $this->purchase_management_model->insert($insert);  
        if ($insert_id > 0) {
            $this->session->set_flashdata('success', 'Purchase Entry details are added successfully');
           
            $cat_id = $this->input->post('category_id');
            $item_id = $this->input->post('item_id');
            $qty = $this->input->post('qty');
            $price = $this->input->post('price');
            $amount = $this->input->post('amount');
            $unit = $this->input->post('hidden_uom');
            
            $items = array();
            foreach($cat_id as $key=>$item) {
                $insert = array(
                    'po_id' => $insert_id,
                    'category_id' => $item,
                    'item_id' => $item_id[$key],
                    'uom' => $unit[$key],
                    'unit_price' => $price[$key],
                    'quantity' => $qty[$key],
                    'not_issued_qty' => $qty[$key],
                    'amount' => $amount[$key],
                    'url_key' => $this->get_purchase_url_key($this->input->post('insert_id')),
                    'created_by' => $this->user_data['user_id'],
                    'created_on' => date('Y-m-d H:i:s')
                );
                $this->purchase_management_model->insert_po_item($insert);
                
                $items[$insert['item_id']] = $insert;
            } 
            
            $items['page'] = 'add';
            $this->update_avail_qty($items);
        }
        else
            $this->session->set_flashdata('error', 'Purchase Entry details are not added!');
        
        redirect('purchase_management', 'refresh');
    }
    
    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) :
            
            if( $is_add || ( !$is_add && ( empty($itm['old_qty']) || ( !empty($itm['old_qty']) && $itm['old_qty'] != $itm['quantity']) ) ) ) :
                
                $itm_qty = $itm['quantity'] < $itm['old_qty'] ? $itm['quantity'] - $itm['old_qty'] : $itm['quantity'];
                
                /*
                 * 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();
				
				if($log){
					// 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
                 */
                
                if( $itm['status'] == 2 ) :
                    // PO Item is Deleted
                    $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['quantity']    = $log['inv_qty'];
                endif;
                
                $args = array(
					'type'          => 3,
                    'inv_cat_id'    => $itm['category_id'],
                    'inv_item_id'   => $itm['item_id'],
                    'uom'           => $item['uom'],
                    'cost_price'    => $itm['unit_price'],//$poi['unit_price'],
                    'sell_price'    => !empty( $item['selling_price'] ) ? $item['selling_price'] : 0,
                    'inv_qty'       => $itm['quantity'],                       
                    'desc'          => 'Added from Inventory Purchase Entry',
                    'status'        => 1,
                    'created_on'    => date("Y-m-d H:i:s"),
                    'created_by'    => $this->user_data['user_id'],
                );
                
               $this->db->insert( TBL_INV_LOG, $args );
            endif;
                    
        endforeach;
    }
    
    public function edit($id = '') {
        if (empty($id)) {
            show_400_error();
        }
        
        $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_id($id);
        $data['po_items'] 		= $this->purchase_management_model->get_items_by_po_id($id);
        $data['used_po_items'] 	= $this->purchase_management_model->get_used_items_by_po_id($id);
        $actions 				= $this->actions();
        $data['form_action'] 	= $actions['update'] . '/' . $id;
        $this->render($data, 'inventory_purchase/edit');
    }
    
    public function update($id = '') {
        
        if (empty($id)) {
            show_400_error();
        }
        
        /*$post = $this->input->post();
        echo '<pre>'; print_r( $post ); die; */
        
        $update = array(
			'purchase_ref_no' => $this->input->post('purchase_ref_no'),
            'supplier_id' => $this->input->post('supplier_id'),
            'invoice_no' => $this->input->post('invoice_no'),
            'invoice_date' => date('Y-m-d',strtotime($this->input->post('invoice_date'))),
			'purchase_for' => $this->input->post('purchase_for'),
            'receivable_date' => date('Y-m-d',strtotime($this->input->post('received_date'))),
            'total_amount' => $this->input->post('total'),
            'payment' => $this->input->post('payment'),
			'desc' => $this->input->post('desc'),
            'url_key' => $this->get_purchase_url_key($this->input->post('invoice_no')),
            #'status' => $this->input->post('status'),
            'updated_by' => $this->user_data['user_id'],
            'updated_on' => date('Y-m-d H:i:s')
        );
        
        if ( $this->purchase_management_model->update($update, $id) > 0) {
            $this->session->set_flashdata('success', 'Purchase Entry details updated successfully');
            
            /*** Update Old Item ***/
            $poi_id 		= $this->input->post('poi_id');
            $edit_item_id 	= $this->input->post('edit_item_id');
            
            if(!empty($edit_item_id)) {
                $old_cat_id = $this->input->post('category_id');
                $old_item_id = $this->input->post('item_id');
                $old_qty = $this->input->post('qty');
                $old_price = $this->input->post('price');
                $old_amount = $this->input->post('amount');
                $old_unit = $this->input->post('hidden_uom');
                $prev_qty = $this->input->post('old_qty');
                $inv_item_ids = $this->input->post('inv_item_ids');
                
                $gen_items = array();
                foreach( $edit_item_id as $k => $poi_idd ) :
                    $item_id = $inv_item_ids[$k];
                    $prev_old_qty = $prev_qty[$poi_idd];
                
                    if( in_array( $poi_idd, $poi_id ) ) :
                        $items = array(
                            'po_id' => $id,
                            'category_id' => $old_cat_id[$k],
                            'item_id' => $item_id,
                            'uom' => $old_unit[$k],
                            'unit_price' => $old_price[$k],
                            'quantity' => $old_qty[$k],
                            'not_issued_qty' => $old_qty[$k],
                            'amount' => $old_amount[$k],
                            'url_key' => $this->get_purchase_url_key($this->input->post('insert_id')),
                            'status' => 1,
                            'updated_by' => $this->user_data['user_id'],
                            'updated_on' => date('Y-m-d H:i:s')
                        );
                    
                        $this->purchase_management_model->update_po_item($items,$poi_id[$k]);
                    
                        $items['old_qty'] = $prev_old_qty;
                        $gen_items[$item_id] = $items;
                    else :
                        // Deleted
                        
                        $gen_items[$item_id] = array(
                            'status' => 2,
                            'old_qty'=> $prev_old_qty,
                        );
                        $this->db->update( TBL_PO_ITEMS, array('status' => 2), array( 'id' => $poi_idd ) );
                    endif;
                    
                endforeach;
                
                $this->update_avail_qty($gen_items);
            }
            
            /*** Insert New Item ***/
            if (!empty($this->input->post('new_category_id'))) {
                $cat_id = $this->input->post('new_category_id');
                $item_id = $this->input->post('new_item_id');
                $qty = $this->input->post('new_qty');
                $price = $this->input->post('new_price');
                $amount = $this->input->post('new_amount');
                $unit = $this->input->post('new_hidden_uom');
                
                $items = array();
                foreach($cat_id as $key=>$item) {
                    $insert = array(
                        'po_id' => $id,
                        'category_id' => $item,
                        'item_id' => $item_id[$key],
                        'uom' => $unit[$key],
                        'unit_price' => $price[$key],
                        'quantity' => $qty[$key],
                        'not_issued_qty' => $qty[$key],
                        'amount' => $amount[$key],
                        'url_key' => $this->get_purchase_url_key($this->input->post('insert_id')),
                        'status' => 1,
                        'created_by' => $this->user_data['user_id'],
                        'created_on' => date('Y-m-d H:i:s')
                    );
                    $this->purchase_management_model->insert_po_item($insert);
                    
                    $items[$insert['item_id']] = $insert;
                 } 

                 $this->update_avail_qty($items);
            }
        }
        else
            $this->session->set_flashdata('error', 'Purchase Entry details not updated!');    
        
        redirect('purchase_management','refresh');
    }
    
    public function view($id = '') {
        if (empty($id)) {
            show_400_error();
        }
        $data = array();
        $data['purchase'] = $this->purchase_management_model->get_by_id($id);
        $data['po_items'] = $this->purchase_management_model->get_view_items($id);
        $this->render($data, 'inventory_purchase/view');
    }
    
    public function delete($id = '') {
        if (empty($id)) {
            show_400_error();
        }
        
        $now = date("Y-m-d H:i:s");
        
        /*
         *  Update Log Avail. Qty
         */
        $q 		= $this->db->get_where( TBL_INVENTORY_PURCHASE_ITEM, array('po_id' => $id, 'status' => 1) );
        $items 	= $q->result_array();
        foreach( $items as $k => $itm ) :
            $q 		= $this->db->get_where( TBL_INV_LOG, array('inv_item_id' => $itm['item_id'], 'status' => 1, 'type' => 3) );
            $log 	= $q->row_array();
            
            $this->db->update( TBL_INV_LOG, array('status' => 2), array('id' => $log['id']) );
            
            $args = array(
                'type'          => 3,
                'inv_cat_id'    => $log['inv_cat_id'],
                'inv_item_id'   => $log['inv_item_id'],
                'uom'           => $log['uom'],
                'cost_price'    => $log['cost_price'],
                'sell_price'    => $log['sell_price'],
                'inv_qty'       => $itm['quantity'],
                'prev_avail_qty'=> $log['now_avail_qty'],
                'now_avail_qty' => $log['now_avail_qty'] - $itm['quantity'],
                'total_issued_qty'=> $log['total_issued_qty'],
                'bal_issued_qty'=> $log['bal_issued_qty'],
                'desc'          => 'Deleted from Inventory Purchase Entry',
				'status'		=> 2,
                'created_on'    => $now,
                'created_by'    => $this->user_data['user_id'],
            );
            
           // $args['status'] = empty( $args['now_avail_qty'] ) ? 2 : 1;
            
            $this->db->insert( TBL_INV_LOG, $args );
        endforeach;
        
        $args = array(
            'status'    => 2,
            'updated_on'=> $now,
            'updated_by'=> $this->user_data['user_id'],    
        );
        
        // Delete PO Items
        $this->db->update( TBL_INVENTORY_PURCHASE_ITEM, $args, array('po_id' => $id, 'status !=' => 2));
        
        // Delete PO
        $this->db->update( TBL_INVENTORY_PURCHASE, $args, array('id' => $id) );
        
        $this->session->set_flashdata('success', 'Purchase Entry details deleted successfully');
        redirect( 'purchase_management', '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() );
        
    }
}
?>