<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Purchase extends REF_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->library('upload');
        $this->load->model('purchase_model', '', TRUE);
        $this->uri_key_index = 0;
    }
    
    public function index() {
        $data = array();
        $data['results'] = $this->purchase_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 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' => '3');
        $this->render($data, 'purchase/list');
    }
    
    private function get_purchase_url_key($name, $id = '') {
        $url_key = get_url_key($name);
        if ($this->purchase_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_PURCHASE, '', array('limit' => 1, 'select' => 'id', 'order_by' => 'id DESC'))['id'];
        //$inv_no = str_replace(INV_PREFIX, '', $inv_no);
        
        $data['suppliers'] = $this->purchase_model->supplier_list();
        $data['categories'] = $this->purchase_model->category_list();
        $data['inv_no']     = INV_PREFIX . fill_digits( empty( $inv_no ) ? 1 : ++$inv_no, 4 );    
        $data['form_action'] = $actions['insert'];
        $this->render($data, 'purchase/add');
    }
    
    public function insert() {
         
        $insert = array(
            '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'))),
            'total_amount' => $this->input->post('total'),
            'payment' => $this->input->post('payment'),
            '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_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_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', '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));
                $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_INV_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( !array_key_exists( $item_id, $pois) ) :
                    $this->db->order_by('id desc');
                    $q = $this->db->get_where(TBL_PO_ITEMS, array('item_id' => $item_id, 'status' => 1));
                    $poi = $q->row_array();
                
                    $pois[$item_id] = $poi;
                else :
                    $poi = $pois[$item_id];
                endif;*/
                
                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'];  
                    
                    $now_avail_qty      = $log['now_avail_qty'] - $itm['old_qty'];
                elseif( !$is_add ) :
                    $edit_qty = $itm['quantity'] - $itm['old_qty'];
                    $now_avail_qty = $edit_qty + $log['now_avail_qty'];
                else :
                    $now_avail_qty = $log['now_avail_qty'] + $itm_qty;
                endif;
                
                $args = array(
                    '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'],
                    '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'          => ($itm['status'] == 2 ? 'Item is Deleted' : ($is_add ? 'Added' : 'Edited') ) .' from Purchase Entry',
                    '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 );
            endif;
                    
        endforeach;
        
            
        
    }
    
    public function edit($id = '') {
        if (empty($id)) {
            show_400_error();
        }
        
        $data = array();
        $data['suppliers'] = $this->purchase_model->supplier_list();
        $data['categories'] = $this->purchase_model->category_list();
        $data['purchase'] = $this->purchase_model->get_by_id($id);
        $data['po_items'] = $this->purchase_model->get_items_by_po_id($id);
        $data['used_po_items'] = $this->purchase_model->get_used_items_by_po_id($id);
        $actions = $this->actions();
        $data['form_action'] = $actions['update'] . '/' . $id;
        $this->render($data, 'purchase/edit');
    }
    
    public function update($id = '') {
        
        if (empty($id)) {
            show_400_error();
        }
        
        /*$post = $this->input->post();
        echo '<pre>'; print_r( $post ); die; */
        
        $update = array(
            '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'))),
            'total_amount' => $this->input->post('total'),
            'payment' => $this->input->post('payment'),
            '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_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_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_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','refresh');
    }
    
    public function view($id = '') {
        if (empty($id)) {
            show_400_error();
        }
        $data = array();
        $data['purchase'] = $this->purchase_model->get_by_id($id);
        $data['po_items'] = $this->purchase_model->get_view_items($id);
        $this->render($data, '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_PO_ITEMS, 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) );
            $log = $q->row_array();
            
            $this->db->update( TBL_INV_LOG, array('status' => 2), array('id' => $log['id']) );
            
            $args = array(
                'type'          => 1,
                '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 Purchase Entry',
                '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_PO_ITEMS, $args, array('po_id' => $id, 'status !=' => 2));
        
        // Delete PO
        $this->db->update( TBL_PURCHASE, $args, array('id' => $id) );
        
        $this->session->set_flashdata('success', 'Purchase Entry details deleted successfully');
        redirect( 'purchase', 'refresh');
    }
    
    public function get_items_by_cat_id(){
        $data['items'] =  $this->purchase_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_model->get_unit_by_item_id($_POST['item_id']);
        echo json_encode($data);
        exit(0);
    }
    
    public function check_valid_qty() {
        $data =  $this->purchase_model->check_valid_qty($_POST['po_item_id']);
        echo json_encode($data);
        exit(0);
    }
    
    function ajax(){
        echo json_encode( $this->purchase_model->ajax() );
        
    }
}
?>