<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
class Products extends CI_Controller
{
    var $main_menu_name = "products";
    var $sub_menu_name = "products";
    public function __construct()
    {
        parent::__construct();
        $this->load->model('category_models');
        $this->load->model('product_models');
        $this->load->model('common_model');
        $this->load->model('Sales_Model');
        $this->load->model('Transfer_Model');
        $this->load->model('Purchases_Model');
        $this->load->model('Product_Damage_Model');
        $this->load->model('Sales_Return_Model');
        $this->load->model('Unit_Model');
        $this->load->model('Product_Models');
        $this->load->model('Menu_Items_List_Model');
    }
    public function index()
    {
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = $this->sub_menu_name;
        $this->load->view('products', $data);
    }
    public function menu_extra_item_suggestions($value = '')
    {
        $term          = $this->input->get('term');
        $warehouse_id  = $this->input->get('w');
        $data['items'] = $this->Product_Models->get_menu_extra_items_suggestions($term);
        //print_r($data['items']);
        $json          = array();
        foreach ($data['items'] as $row) {
            //get unit code by id
            //echo "unitid:".$row['item_unit'];
            $unit_dtls  = $this->Unit_Model->get_unit_info($row['item_unit']);
            //print_r($row);
            $unit_code  = $unit_dtls['unit_code'];
            $item_code  = $row['item_code'];
            //echo "item_code:".$row['item_code'];
            $item_code  = $row['item_code'];
            $item_name  = $row['item_name'];
            $item_price = $row['item_price_' . $warehouse_id];
            $json_itm   = array(
                'id' => $row['item_id'],
                'item_id' => $row['item_id'],
                'item_id' => $row['item_id'],
                'item_code' => $item_code,
                'item_name' => $row['item_name'],
                'item_price' => $row['item_price_' . $warehouse_id],
                'unit_code' => $unit_code,
                'value' => $row['item_code'] . " " . $item_code . "",
                'label' => $row['item_name'] . " (" . $item_code . ")"
            );
            array_push($json, $json_itm);
        }
        echo json_encode($json);
    }
    public function booking_extra_item_save()
    {
        $disMsg     = '';
        $error      = '';
        //print_r($this->input->post());
        //insert sale item data
        $row        = $this->input->post('row_e');
        $rowCount_e = $this->input->post('rowCount_e');
        //$menu_id=$this->input->post('menu_id');
        $product_id = $this->input->post('product_id');
        $data_item  = array();
        //echo "rowCount_e:".$rowCount_e;
        //print_r($this->input->post('row_e'));
        //delete old items
        $this->Product_Models->delete_booking_assign_item($product_id, 'Extra');
        //echo $this->db->last_query();
        for ($i = 1; $i <= $rowCount_e; $i++) {
            //    echo "/ $rowCount , Test:".$row[$i]['product_id'][0];
            if (isset($row[$i]['item_id'][0])) {
                $data_item = array(
                    'item_id' => $row[$i]['item_id'][0],
                    'product_id' => $product_id,
                    'bkng_itm_price' => $row[$i]['price'][0],
                    'bkng_itm_type' => 'Extra',
                    'bkng_extra_item' => 'Extra',
                    'bkng_itm_note' => $row[$i]['bkng_itm_note'][0],
                    'bkng_itm_qty' => $row[$i]['itm_qty'][0], //need add
                    'tot_amount' => $row[$i]['sub_tot'][0], //need add
                    'bkng_itm_added_date' => date("Y-m-d H:i:s"),
                    'user_id' => $this->session->userdata('ss_user_id')
                );
                //add items
                $this->Product_Models->save_menu_assign_item($data_item);
                //echo $this->db->last_query();
            }
            //save booking payment dtls
            //$this->add_booking_dtls();
        }
        echo json_encode(array(
            'error' => $error,
            'disMsg' => $disMsg
        ));
    }
    public function add_product()
    {
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'add_products';
        $data['main_category']  = $this->category_models->getCategory();
        $data['unit_type']      = $this->product_models->getUnit();
        $data['tax']            = $this->product_models->getTax();
        $this->load->view('add_product', $data);
    }
    public function get_sub_category_by_id()
    {
        $parent_category = $this->input->get('category_id');
        if ($parent_category) {
            $val = $this->category_models->get_sub_category($this->input->get('category_id'));
            if (!empty($val)) {
                echo '<select name="subcategory" id="subcategory" class="form-control search-select">';
                echo "<option value=''></option>";
                foreach ($val as $key => $lst) {
                    echo "<option value='$lst->sub_cat_id'>$lst->sub_cat_name</option>";
                }
                echo '</select>';
            }
        } else {
            echo NULL;
        }
    }
    public function save_product()
    {
        $this->load->library('form_validation'); //form validation lib
        $this->form_validation->set_rules('product_name', 'Product Name', 'required');
        $this->form_validation->set_rules('product_code', 'Product Code', 'required|is_unique[product.product_code]');
        // $this->form_validation->set_rules('product_cost', 'product cost', 'required');
        //  $this->form_validation->set_rules('product_price', 'product price', 'required');
        // $this->form_validation->set_rules('wholesale_price', 'wholesale price', 'required');
        // $this->form_validation->set_rules('credit_salling_price', 'credit salling price', 'required');
        // $this->form_validation->set_rules('alert_quty', 'alert quty', 'required');
        if ($this->form_validation->run() == FALSE) {
            $st = array(
                'status' => 0,
                'validation' => validation_errors()
            );
            echo json_encode($st);
        } else {
            $product_name            = $this->input->post('product_name');
            $product_code            = $this->input->post('product_code');
            $category                = $this->input->post('category');
            $subcategory             = $this->input->post('subcategory');
            $unit                    = $this->input->post('unit');
            $product_cost            = ($this->input->post('product_cost'))?$this->input->post('product_cost'):null;
            $product_price           = $this->input->post('product_price');
            $wholesale_price         = $this->input->post('wholesale_price');
            $credit_salling_price    = $this->input->post('credit_salling_price');
            $tax                     = $this->input->post('tax');
            $alert_quty              = $this->input->post('alert_quty');
            //$image_name             = $this->input->post('product_image');
            $product_details         = $this->input->post('product_details');
            $product_part_no         = $this->input->post('product_part_no');
            $product_oem_part_number = $this->input->post('product_oem_part_number');
            $product_id              = $this->input->post('product_id');
            $store_position          = $this->input->post('store_position');
            $product_max_qty         = $this->input->post('product_max_qty');
            $product_commision       = $this->input->post('product_commision');
            
            if($product_commision>0){} else{$product_commision=0;}  
            
            $is_ko                   = floatval($this->input->post('is_ko'));
            if (!$subcategory)
                $subcategory = 0;
            if (!is_numeric($product_max_qty))
                $product_max_qty = 0;
            if (!is_numeric($alert_quty))
                $alert_quty = 0;
            if (!$wholesale_price)
                $wholesale_price = 0;
            if (!$product_part_no)
                $product_part_no = 0;
            if (!$product_oem_part_number)
                $product_oem_part_number = 0;
            if (!$store_position)
                $store_position = '_';
            if (!$credit_salling_price)
                $credit_salling_price = 0;
            if (!empty($_FILES["userfile"]['name'])) {
                $image_name_enc = "PRODUCT_" . time() . $_FILES["userfile"]['name'];
                $this->load->library('upload', $this->image_manipulation->image_config($image_name_enc));
                if (!$this->upload->do_upload()) {
                    $st = array(
                        'status' => 0,
                        'validation' => $this->upload->display_errors()
                    );
                    echo json_encode($st);
                } else {
                    $this->load->library('image_lib', $this->image_manipulation->image_thumb($image_name_enc, 100, 100));
                    if (!$this->image_lib->resize()) {
                        echo $this->image_lib->display_errors();
                    } else {
                        $imgName    = $this->upload->data();
                        $imageThumb = $imgName['raw_name'] . "_thumb" . $imgName['file_ext'];
                        $last_id    = $this->product_models->save_product($product_name, $product_code, $category, $subcategory, $unit, $product_cost, $product_price, $wholesale_price, $credit_salling_price, $tax, $alert_quty, $imgName['file_name'], $imageThumb, $product_details, $product_part_no, $product_oem_part_number, $product_id, $store_position, $product_max_qty, $product_commision,$is_ko);
                        if ($last_id) {
                            $st = array(
                                'status' => 1,
                                'validation' => 'Done!',
                                'last_id' => "PD" . sprintf("%04d", $last_id + 1)
                            );
                            echo json_encode($st);
                        } else {
                            $st = array(
                                'status' => 0,
                                'validation' => 'error occurred please contact your system administrator'
                            );
                            echo json_encode($st);
                        }
                        $this->image_lib->clear();
                    }
                }
            } else {
                $last_id = $this->product_models->save_product($product_name, $product_code, $category, $subcategory, $unit, $product_cost, $product_price, $wholesale_price, $credit_salling_price, $tax, $alert_quty, NULL, NULL, $product_details, $product_part_no, $product_oem_part_number, $product_id, $store_position, $product_max_qty, $product_commision,$is_ko);
                if ($last_id) {
                    $st = array(
                        'status' => 1,
                        'validation' => 'Done!',
                        'last_id' => "PD" . sprintf("%04d", $last_id + 1)
                    );
                    echo json_encode($st);
                } else {
                    $st = array(
                        'status' => 0,
                        'validation' => 'error occurred please contact your system administrator'
                    );
                    echo json_encode($st);
                }
            }
        }
    }
    function price_filter($amount = '')
    {
        $s = explode("Rs.", $amount);
        return str_replace(',', '', $s[1]);
    }
    public function get_list_product($value = '')
    {
        $values = $this->product_models->getProducts();
        $data   = array();
        if (!empty($values)) {
            foreach ($values as $products) {
                if ($products->product_status == 0) {
                    $k = "btn-warning";
                    $m = "fa-minus-circle";
                } else {
                    $k = "btn-green";
                    $m = "fa-check";
                }
                $retVal                   = (empty($products->sub_cat_name)) ? "--:--" : $products->sub_cat_name;
                $qty                      = $this->product_models->get_item_qty($products->product_id);
                $qty                      = (empty($qty[0]->qty)) ? "--:--" : $qty[0]->qty;
                $row                      = array();
                //get transferd qty
                $transferd_qty            = 0;
                $transfer_reseve_qty      = 0;
                $row[]                    = '<center><div style="margin-bottom: 0px; width: 50px; height: 50px;" class="fileupload-new thumbnail"><img alt="" src="' . asset_url() . "uploads/thumbs/" . $products->product_thumb . '"></div></center>';
                //start get product cost 
                //end get product cost 
                $selected_extra_menu_list = $this->Product_Models->get_booking_selected_menu_items_by_type($products->product_id, '', 'Extra');
                //print_r($selected_extra_menu_list);
                $product_cost_cal         = 0;
                if (isset($selected_extra_menu_list)) {
                    foreach ($selected_extra_menu_list as $row_itm) {
                        $item_dtls        = $this->Menu_Items_List_Model->get_item_info($row_itm->item_id);
                        $item_price_1     = $item_dtls['item_price_1'];
                        $bkng_itm_qty     = $row_itm->bkng_itm_qty;
                        $amount_this      = 0;
                        $amount_this      = $bkng_itm_qty * $item_price_1;
                        $product_cost_cal = $product_cost_cal + $amount_this;
                    }
                }
                $each_product_cost = '';
                if ($products->product_oem_part_number) {
                    $each_product_cost = $product_cost_cal / $products->product_oem_part_number;
                    $each_product_cost = number_format($each_product_cost, 2, '.', ',');
                } else if ($products->product_cost)
                    $each_product_cost = $products->product_cost;
                else
                    $each_product_cost = $products->product_price;
                $row[]  = $products->product_code;
                // $row[] = $products->product_part_no;
                $row[]  = $products->product_name;
                $row[]  = $products->cat_name;
                $row[]  = $retVal;
                $row[]  = $products->product_price;
                $row[]  = $products->wholesale_price;
                $row[]  = $products->credit_salling_price;
                $row[]  = $products->product_cost; //$each_product_cost;
                $row[]  = $products->product_oem_part_number;
                $row[]  = "n/a";
                $row[]  = $products->is_ko ? '<i class="fa fa-check"></i> Print K.O.T':'<i class="fa fa-times"></i>';
                $actdes = '';
                $action_class="btn-primary";
                if($products->product_status==0){
                  $action_class="btn-danger";   
                    $edbutton='<li class="divider"></li><li><a onclick="product_enable(' . $products->product_id . '); return false;" href="#"><i class="fa fa-check"></i> Enable Product</a></li>'; 
                }else{
                   $edbutton='<li class="divider"></li><li><a onclick="product_delete(' . $products->product_id . '); return false;" href="#"><i class="fa fa-trash-o"></i> Disable Product</a></li>';  
                    
                }
                $actdes = $actdes . '<div class="btn-group text-left">
                            <button data-toggle="dropdown" class="btn btn-default btn-xs '.$action_class.' dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                            <ul role="menu" class="dropdown-menu pull-right">
                            <li><a href="' . base_url('products/view') . '/' . $products->product_id . '"><i class="fa fa-file-text-o"></i> Product Details</a></li>
                            ';
                if ($this->session->userdata('ss_group_id') == 1 || $this->session->userdata('ss_group_id') == 2  ) {
                    $actdes = $actdes . '<li><a target="_edit_product" href="' . base_url('products/edit') . '/' . $products->product_id . '"><i class="fa fa-edit"></i> Edit Product</a></li>
                            '.$edbutton.'
                            ';
                }
                $actdes = $actdes . '    
                            <li><a onclick=" print_barcode(' . $products->product_id . '); return false;" href="#"><i class="fa fa-print"></i> Print Barcode</a></li>
                            
                            </ul></div>';
                $row[]  = $actdes;
                $data[] = $row;
            }
            $output = array(
                'data' => $data
            );
            echo json_encode($output);
        } else {
            $output = array(
                'data' => ''
            );
            echo json_encode($output);
        }
    }
    public function view($product_id = "")
    {
        $sd = $this->product_models->get_product_by_id($product_id);
        if (!empty($sd)) {
            $data['product_details']          = $this->product_models->get_product_by_id($product_id);
            $data['warehouses']               = $this->product_models->get_warehouse_product($product_id);
            $data['main_menu_name']           = $this->main_menu_name;
            $data['sub_menu_name']            = $this->sub_menu_name;
            $data['selected_extra_menu_list'] = $this->Product_Models->get_booking_selected_menu_items_by_type($product_id, '', 'Extra');
            $this->load->view('view_product', $data);
        } else {
            show_404();
        }
    }
    public function edit($product_id = '')
    {
        $data['product_details'] = $this->product_models->get_product_by_id($product_id);
        if ($data['product_details']) {
            $data['main_menu_name']           = $this->main_menu_name;
            $data['sub_menu_name']            = $this->sub_menu_name;
            $data['main_category']            = $this->category_models->getCategory();
            $data['unit_type']                = $this->product_models->getUnit();
            $data['tax']                      = $this->product_models->getTax();
            $data['sub_category']             = $this->category_models->getSubCategory($data['product_details']->cat_id);
            $data['selected_extra_menu_list'] = $this->Product_Models->get_booking_selected_menu_items_by_type($product_id, '', 'Extra');
            $this->load->view('edit_product', $data);
        } else
            show_404();
    }
    public function single_barcode($product_id = '')
    {
        $data['product_details'] = $this->product_models->get_product_by_id($product_id);
        $this->load->view('barcode/product_barcode', $data);
    }
    function gen_barcode($product_code = NULL, $height = 80)
    {
        if ($this->input->get('code')) {
            $product_code = $this->input->get('code');
        }
        if ($this->input->get('height')) {
            $height = $this->input->get('height');
        }
        //load library
        $this->load->library('zend');
        //load in folder Zend
        $this->zend->load('Zend/Barcode');
        //'drawText' => FALSE
        $barcodeOptions  = array(
            'text' => $product_code,
            'barHeight' => $height,
            'stretchText' => TRUE
        );
        $rendererOptions = array(
            'imageType' => 'png',
            'horizontalPosition' => 'center',
            'verticalPosition' => 'middle'
        );
        $imageResource   = Zend_Barcode::render('code128', 'image', $barcodeOptions, $rendererOptions);
        return $imageResource;
    }
    function delete_product($product_id = '')
    {
        $d = $this->product_models->delete_product($this->input->post('product_id'));
        if ($d) {
            $e = array(
                'status' => 1
            );
            echo json_encode($e);
        } else {
            $e = array(
                'status' => 0,
                'validation' => 'This product is already linked. You cannot delete it.'
            );
            echo json_encode($e);
        }
    }
    public function edit_product()
    {
        $product_name            = $this->input->post('product_name');
        $product_code            = $this->input->post('product_code');
        $category                = $this->input->post('category');
        $subcategory             = $this->input->post('subcategory');
        $product_cost            = $this->input->post('product_cost');
        $unit                    = $this->input->post('unit');
        $product_cost            = floatval($this->input->post('product_cost')); //$this->price_filter($this->input->post('product_cost'));
        $product_price           = floatval($this->input->post('product_price'));
        $wholesale_price         = floatval($this->input->post('wholesale_price'));
        $credit_salling_price    = floatval($this->input->post('credit_salling_price'));
        $product_commision       = floatval($this->input->post('product_commision'));
        $tax                     = floatval($this->input->post('tax'));
        $is_ko                   = floatval($this->input->post('is_ko'));
        $alert_quty              = $this->input->post('alert_quty');
        $product_details         = $this->input->post('product_details');
        $product_part_no         = $this->input->post('product_part_no');
        $product_oem_part_number = $this->input->post('product_oem_part_number');
        $store_position          = $this->input->post('store_position');
        $product_max_qty         = $this->input->post('product_max_qty');
        if (!empty($_FILES["userfile"]['name'])) {
            $image_name_enc = "PRODUCT_" . time() . $_FILES["userfile"]['name'];
            $this->load->library('upload', $this->image_manipulation->image_config($image_name_enc));
            if (!$this->upload->do_upload()) {
                $st = array(
                    'status' => 0,
                    'validation' => $this->upload->display_errors()
                );
                echo json_encode($st);
            } else {
                $this->load->library('image_lib', $this->image_manipulation->image_thumb($image_name_enc, 100, 100));
                if (!$this->image_lib->resize()) {
                    echo $this->image_lib->display_errors();
                } else {
                    $imgName    = $this->upload->data();
                    $imageThumb = $imgName['raw_name'] . "_thumb" . $imgName['file_ext'];
                    if ($this->product_models->update_product($this->input->post('product_id'), $is_ko, $product_name, $product_code, $category, $subcategory, $unit, $product_cost, $product_price, $wholesale_price, $credit_salling_price, $tax, $alert_quty, $imgName['file_name'], $imageThumb, $product_details, $product_part_no, $product_oem_part_number, $store_position, $product_max_qty, $product_commision)) {
                        $st = array(
                            'status' => 1,
                            'validation' => 'Done!'
                        );
                        echo json_encode($st);
                    } else {
                        $st = array(
                            'status' => 0,
                            'validation' => 'error occurred please contact your system administrator'
                        );
                        echo json_encode($st);
                    }
                    $this->image_lib->clear();
                }
            }
        } else {
            if ($this->product_models->update_product($this->input->post('product_id'), $is_ko, $product_name, $product_code, $category, $subcategory, $unit, $product_cost, $product_price, $wholesale_price, $credit_salling_price, $tax, $alert_quty, 0, 0, $product_details, $product_part_no, $product_oem_part_number, $store_position, $product_max_qty, $product_commision)) {
                $st = array(
                    'status' => 1,
                    'validation' => 'Done!'
                );
                echo json_encode($st);
            } else {
                $st = array(
                    'status' => 0,
                    'validation' => 'error occurred please contact your system administrator'
                );
                echo json_encode($st);
            }
        }
    }
    
    
     function enable_product($product_id = '')
    {
        $d = $this->product_models->enable_product($this->input->post('product_id'));
        if ($d) {
            $e = array(
                'status' => 1
            );
            echo json_encode($e);
        } else {
            $e = array(
                'status' => 0,
                'validation' => 'This product is already linked. You cannot delete it.'
            );
            echo json_encode($e);
        }
    }
}