<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Item extends REF_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->library('upload');
        $this->load->model('item_model', '', TRUE);
        $this->uri_key_index = 0;
    }
    
    public function index() {
        $data = array();
        $data['results'] = $this->item_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']    = 'Create New Item';
        $data['view_link']  = $actions['view'] . '/';
        $data['add_link']   = $actions['add'];
        $data['edit_link']  = $actions['edit'] . '/';
        $data['delete_link']= $actions['delete'] . '/';
        
        $service_menu_id = get_master_controller_id($actions['controller']);
        $data['service_menu_id'] = array('service_menu_id' => $service_menu_id, 'menu_type' => '1');
        $this->render($data, 'item/list');
    }
    
    public function add() {
        $data = array();
        $actions = $this->actions();
        $data['form_action'] = $actions['insert'];
        $data['seq_no'] = $this->item_model->active_item_count() + 1;
        $data['category'] = $this->item_model->category_list();
        $data['inv_cats'] = _get( TBL_INV_CATEGORY, array('status' => 1), array('select' => 'id, name') );
        
        $this->render($data, 'item/add');
    }
    
    private function get_item_url_key($item_name, $id = '') {
        $url_key = get_url_key($item_name);
        if ($this->item_model->item_url_key_exists($url_key, $id)) {
            $this->uri_key_index ++;
            return $this->get_item_url_key($item_name . '_' . $this->uri_key_index, $id);
        }
        
        return $url_key;
    }
    
    public function insert() {
        $general = get_general_setting();
        $seq_no = $this->item_model->active_item_count() + 1;
        $seq_no = (!empty($this->input->post('seq_no'))) ? $this->input->post('seq_no') : $seq_no;
        $insert = array(
            'category_id' => ((!empty($this->input->post('category_id'))) ? $this->input->post('category_id') : ''),
            'name' => $this->input->post('item_name'),
            'item_slug'  => get_var_name($this->input->post('item_name')),
            'tamil_name' => htmlspecialchars( $this->input->post('tamil_item_name') ),
            'price' => $this->input->post('price'),
            #'priority' => $this->input->post('proirity'),
            'receipt' => $this->input->post('receipt'),
            'is_inventory' => $this->input->post('is_inventory'),
            'is_enable_footer' => $this->input->post('is_enable'),
            'order_sequence'=> $seq_no,
            'god_name' => $this->input->post('god_name'),
            'item_top_color' => $this->input->post('color_top'),
            'item_bottom_color' => $this->input->post('color_bottom'),
            'prefix' => $this->input->post('prefix'), 
            'url_key' => $this->get_item_url_key($this->input->post('item_name')),
            'status' => $this->input->post('status'),
            'created_by' => $this->user_data['user_id'],
            'created_on' => date('Y-m-d H:i:s')
        );
        
        if($general->is_category == 1) :
           $insert['item_top_color'] = '';
           $insert['item_bottom_color'] = '';
        else :
           $insert['item_top_color'] = $this->input->post('color_top');
           $insert['item_bottom_color'] = $this->input->post('color_bottom'); 
        endif;
        
        if( $insert['is_inventory'] == "1" ) :
            $insert['inv_cat_id'] = $this->input->post('inv_cat');
        else :
            $insert['inv_cat_id'] = '';
        endif;
        
        $image_name = '';
        if (!empty($_FILES['image']['name'])) {
            $config = array();
            $config['upload_path'] = DIR_ITEM_IMAGE;
            $config['allowed_types'] = implode('|', image_extensions());
            $this->upload->initialize($config);
            if (!file_exists(DIR_ITEM_IMAGE)) {
                mkdir(DIR_ITEM_IMAGE, 0777, true);
            }
            if ($this->upload->do_upload('image')) {
                $upload_data = $this->upload->data();
                $insert['image'] = $upload_data['file_name'];
            }
            else { 
                $this->session->set_flashdata('error', $this->upload->display_errors());
            }
        }
        
        $insert_id = $this->item_model->insert($insert);  
        if ($insert_id > 0) {
            $this->session->set_flashdata('success', 'Item added successfully');  
            
            if( $insert['is_inventory'] ) :
                /*
                 * Insert / Update "Inventory General"
    "            */
                
                $insert['item_id'] = $insert_id;
                $this->update_inv_gen($insert);
                
            endif;    
        }
        else{
            $this->session->set_flashdata('error', 'Item not added!');   
        }
        
        redirect('item', 'refresh');
    }
    
    function update_inv_gen($args) {
        $now = date("Y-m-d H:i:s");
        $post = $this->input->post();
        $inv_item_id = $this->input->post('inv_item');
        
        // Inventory Item exists
        if( empty( $inv_item_id ) ) :
            // Insert New Inventory Item
            
            $a = array(
                'code'      => generate_rec_no(TBL_INV_ITEM, array('is_statue_item' => 0)),
                'category_id'=> $args['inv_cat_id'],
                'item_name' => $args['name'],
                'item_slug'  => $args['item_slug'],
                'is_statue_item' => 0,
                'is_master' => 1,
                //'uom'       => 1,
                'description'=> 'Added by Inventory is checked in Item Master',
                'created_on'=> $now,    
                'created_by'=> $this->user_data['user_id'],
            );
            
            $this->db->insert( TBL_INV_ITEM, $a );
            $inv_item_id = $this->db->insert_id();
        endif;
        
        // If Inventory is checked, then the id of Inventory Item id will be stored, for Archanai Performance
        $this->db->update(TBL_ITEM, array('inv_item_id' => $inv_item_id), array('id' => $args['item_id']));
        
    }
    
    public function edit($id = '') {
        if (empty($id)) {
            show_400_error();
        }
        
        $data = array();
        $data['category'] = $this->item_model->category_list();
        $data['inv_cats'] = _get( TBL_INV_CATEGORY, array('status' => 1), array('select' => 'id, name') );
        $data['item'] = $this->item_model->get_item_by_id($id);
        $actions = $this->actions();
        $data['form_action'] = $actions['update'] . '/' . $id;
        $this->render($data, 'item/edit');
    }
    
    public function update($id = '') {
        if (empty($id)) {
            show_400_error();
        }
        $seq_no = $this->item_model->active_item_count() + 1;
        $seq_no = (!empty($this->input->post('seq_no'))) ? $this->input->post('seq_no') : $seq_no;
        $update = array(
            'category_id' => ((!empty($this->input->post('category_id'))) ? $this->input->post('category_id') : ''),
            'name' => $this->input->post('item_name'),
            'item_slug'  => get_var_name($this->input->post('item_name')),
            'tamil_name' => htmlspecialchars( $this->input->post('tamil_item_name') ),
            'price' => $this->input->post('price'),
            #'priority' => $this->input->post('proirity'),
            'receipt' => $this->input->post('receipt'),
            'is_inventory' => $this->input->post('is_inventory'),
            'is_enable_footer' => $this->input->post('is_enable'),
            'order_sequence'=> $seq_no,
            'god_name' => $this->input->post('god_name'),
            'prefix' => $this->input->post('prefix'), 
            'url_key' => $this->get_item_url_key($this->input->post('item_name')),
            'status' => $this->input->post('status'),
            'updated_by' => $this->user_data['user_id'],
            'updated_on' => date('Y-m-d H:i:s')
        );
        
        if( $update['is_inventory'] == "1" ) :
            $update['inv_cat_id'] = $this->input->post('inv_cat');
        else :
            $update['inv_cat_id'] = '';
        endif;
        
        if($general->is_category == 1) :
           $update['item_top_color'] = '';
           $update['item_bottom_color'] = '';
        else :
           $update['item_top_color'] = $this->input->post('color_top');
           $update['item_bottom_color'] = $this->input->post('color_bottom'); 
        endif;
        
        $item = $this->item_model->get_item_by_id($id);
        
        if($this->input->post('img_delete') != 1) {
            if (!empty($_FILES['image']['name'])) {
                $config = array();
                $config['upload_path'] = DIR_ITEM_IMAGE;
                $config['allowed_types'] = implode('|', image_extensions());
                $this->upload->initialize($config);
                if (!file_exists(DIR_ITEM_IMAGE)) {
                    mkdir(DIR_ITEM_IMAGE, 0777, true);
                }
                if ($this->upload->do_upload('image')) {
                    if (!empty($item->image)) {
                        if (file_exists(DIR_ITEM_IMAGE . $item->image)) {
                            unlink(DIR_ITEM_IMAGE . $item->image);
                        }
                    }
                    $upload_data = $this->upload->data();
                    $update['image'] = $upload_data['file_name'];
                }
                else { 
                    $this->session->set_flashdata('error', $this->upload->display_errors());
                }
            }
        }
        else {
            $update['image'] = '';
                if (!empty($item->image)) {
                    if (file_exists(DIR_ITEM_IMAGE . $item->image)) {
                        unlink(DIR_ITEM_IMAGE . $item->image);
                    }
                }
        }
        if ($this->item_model->update($update, $id) > 0) :
            $this->session->set_flashdata('success', 'Item updated successfully'); 
        
             if( $update['is_inventory'] ) :
                /*
                 * Insert / Update "Inventory General"
    "            */

                $update['item_id'] = $id;
                $this->update_inv_gen($update);
                
            endif; 
        
        else :
            $this->session->set_flashdata('error', 'Item not updated!');    
        endif;
        
        redirect('item','refresh');
    }
    
    public function view($id = '') {
        if (empty($id)) {
            show_400_error();
        }
        
        $data = array();
        $data['item'] = $this->item_model->get_item_by_id($id);
        $this->render($data, 'item/view');
    }
    
    public function delete($id = '') {
        if (empty($id)) {
            show_400_error();
        }
        
        $update = array ( 
            'status' => 2,
            'updated_by' => $this->user_data['user_id'],
            'updated_on' => date('Y-m-d H:i:s')
        );
        
        $item = $this->item_model->get_item_by_id($id);
        if ($this->item_model->update($update,$id) > 0) {
            $this->session->set_flashdata('success', 'Item deleted successfully');
            if (!empty($item->image)) {
                if (file_exists(DIR_ITEM_IMAGE . $item->image)) {
                    unlink(DIR_ITEM_IMAGE . $item->image);
                }
            }
        }
        else 
            $this->session->set_flashdata('error', 'Item not deleted!');
        
        redirect( 'item', 'refresh');
    }
    
    public function item_name_exists() {
        $data =  $this->item_model->item_name_exists($_POST['category_name'], $_POST['id'],$_POST['item_name']);
        echo json_encode($data);
        exit(0);
    }
    
    function ajax(){
        echo json_encode( $this->item_model->ajax() );
    }
}
?>