<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Items extends CI_Controller {
    
    public function __construct() {
        parent::__construct();
         if (! $this->session->userdata ( 'user_logged_in' ) && ! $this->session->userdata ( 'user_logged_in' )) {
            redirect ( 'login', 'refresh' );
        }
        $this->load->vars ( array (
                'global' => 'Available to all views',
                'header' => 'common/header',
                'left' => 'common/left',
                'footer' => 'common/footer' 
        ) );

        $this->load->model('Item_model');
    }

    public function index(){
        $data['item_list'] = $this->Item_model->get_items();
        $this->load->view('item_list',$data);
    }

    public function newitem(){
        $data['item_id'] = !empty($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        if ($data['item_id'] > 0) {
            $data['item_details'] = $this->Item_model->get_item_details($data['item_id']);
        }
        $this->load->view('new_item',$data);
    }

    public function add_items(){
        $item_id = $this->input->post('item_id');
        $item_name = $this->input->post('item_name');
        $item_description = $this->input->post('item_description');
        $unit = $this->input->post('unit');
        $rate_purchase = $this->input->post('rate_purchase');
        $hsn_code = $this->input->post('hsn_code');
        $gst_rate = $this->input->post('gst_rate');
        $rate_sale = $this->input->post('rate_sale');

        $item_data = array(
                'item_name' => $item_name,
                'item_description' => $item_description,
                'unit' => $unit,
                'hsn_code' => $hsn_code,
                'rate_sale' => $rate_sale,
                'rate_purchase' => $rate_purchase,
                'gst_rate' => $gst_rate,
                'date_added' => date('Y-m-d'),
                'date_edited' => date('Y-m-d'),
                'status' => 1
            );
        if ($item_id == 0) {
            $this->Item_model->insert_data('items',$item_data);
        } else {
            $this->Item_model->update_data('items',$item_data,array('item_id' => $item_id));
        }
        echo 1;
    }

    public function get_item_stock(){
        $item = $this->input->post('item_id');
        $item_stock = $this->Item_model->get_stock($item);
        echo !empty($item_stock->stock) ? $item_stock->stock : 0;
    }
}
?>