<?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('Warehouse_Model');
        $this->load->model('Stock_Counter_Model');
        $this->load->model('Common_Model');
        $this->load->model('Product_Type_Model');
        
    }
    public function index()
    {
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = $this->sub_menu_name;
        $this->load->view('product/products', $data);
    }
    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['product_type']      = $this->Product_Type_Model->getActiveProductTypeList();
        $data['tax']            = $this->product_models->getTax();
        $data['page'] =$this->input->get('page');
        $this->load->view('product/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;
        }
    }
    function save_product()
    {
        $this->load->library('form_validation'); //form validation lib
        $this->form_validation->set_rules('product_name', 'Product Name', 'required');
        $product_code            = $this->input->post('product_code');
        if($product_code){
           $this->form_validation->set_rules('product_code', 'Product Code', 'is_unique[product.product_code]'); 
        }
        $this->form_validation->set_rules('product_cost', 'Product Cost', 'required');
        $this->form_validation->set_rules('product_type', 'Product Type', 'required');
        $this->form_validation->set_rules('category', 'Product Category', 'required');
        $this->form_validation->set_rules('subcategory', 'Item Category', 'required');
        $this->form_validation->set_rules('unit', 'UOM', 'required');
        $this->form_validation->set_rules('product_weight', 'UOM Weight', 'required');
        if ($this->form_validation->run() == FALSE) {
            $st = array(
                'status' => 0,
                'validation' => validation_errors()
            );
            echo json_encode($st);
        } else {
            $is_hw = $this->input->post('is_hw');
            $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->price_filter($this->input->post('product_cost'));
            
			$product_price           = $this->input->post('product_price');
				if($product_price)$product_price = $this->price_filter($product_price);
            $wholesale_price         = $this->input->post('wholesale_price');
				if($wholesale_price)$wholesale_price = $this->price_filter($wholesale_price);
            $credit_salling_price    = $this->input->post('credit_salling_price');
				if($credit_salling_price)$credit_salling_price = $this->price_filter($credit_salling_price);
            $retail_cash             = $this->input->post('retail_cash');
				if($retail_cash)$retail_cash = $this->price_filter($retail_cash);
            $retail_credit           = $this->input->post('retail_credit');
				if($retail_credit)$retail_credit = $this->price_filter($retail_credit);
            $retail_wholesale        = $this->input->post('retail_wholesale');
				if($retail_wholesale)$retail_wholesale = $this->price_filter($retail_wholesale);
            $brand_id                = $this->input->post('brand_id');
            $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');
            $daily_rental_days       = $this->input->post('daily_rental_days');
            $tax                     = $this->input->post('tax');
            $product_type = $this->input->post("product_type");
            $quantity = $this->input->post("pr_quantity");
            $sub_product_of = $this->input->post('sub_product_of');
            $is_export_scale = $this->input->post('is_export_scale');
            $product_weight = $this->input->post('product_weight');
            $is_batch_validate = $this->input->post('is_batch_validate');
            
            $rep_commisison          = "";            
            $down_payment            = ""; 
            $per_day_rental          = ""; 
             if($product_type==2){
                $pre_code='IP';
                $pre_code_no='003';
            }else{
                $pre_code='FP';
                $pre_code_no='001';
            }
             if(!$product_code){
             $product_code=$this->Common_Model->gen_ref_number('product_id','product',$pre_code);
            }
             if($is_export_scale==1){
               $product_code=$this->Common_Model->gen_product_scale_ref_number('product_id','product',$pre_code_no);  
             }
            $pd = array(
            'cat_id' => $category,
            'sub_cat_id' => $subcategory,
            'product_name' => $product_name,
            'product_code' => $product_code,
            'product_alert_qty' => $alert_quty,
            'product_unit' => $unit,
            'product_cost' => $product_cost,
            'product_price' => $product_price,
            'wholesale_price' => $wholesale_price,
            'credit_salling_price' => $credit_salling_price,
            'tax' => $tax,
            'product_details' => $product_details,
            'product_part_no' => $product_part_no,
            'product_oem_part_number' => $product_oem_part_number,
            'store_position' => $store_position,
            'product_max_qty' => $product_max_qty,
            'brand_id' => $brand_id,
			'is_hw'	=> $is_hw,
			'product_type_id'=>$product_type,
			'pr_quantity'=>$quantity,
			'is_export_scale'=>$is_export_scale,
			'product_weight'=>$product_weight,
			'is_batch_validate'=>$is_batch_validate
        );
            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);
                    exit();
                } 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'];
                        $pd['product_image'] = $imgName['file_name'];
                        $pd['product_thumb'] = $imageThumb;
                        
                        $this->image_lib->clear();
                    }
                }
            }
            $last_id    = $this->product_models->save_product($pd);
            if($last_id && $product_code == ""){
                $this->product_models->update_product_code($last_id);
            }
            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 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');
        $unit                    = $this->input->post('unit');
        $product_cost            = $this->price_filter($this->input->post('product_cost'));
        $product_price           = $this->price_filter($this->input->post('product_price'));
        $wholesale_price         = $this->price_filter($this->input->post('wholesale_price'));
        $credit_salling_price    = $this->price_filter($this->input->post('credit_salling_price'));
        $retail_cash             = $this->price_filter($this->input->post('retail_cash'));
        $retail_credit           = $this->price_filter($this->input->post('retail_credit'));
        $retail_wholesale        = $this->price_filter($this->input->post('retail_wholesale'));
        $brand_id                = $this->input->post('brand_id');
        $is_hw                   = $this->input->post('is_hw');
        $tax                     = $this->input->post('tax');
        $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');
        $daily_rental_days       = $this->input->post('daily_rental_days');
        $is_special_rep_commisson= $this->input->post('is_special_rep_commisson');
        $commission_cash_within = $this->input->post('commission_cash_within');
        $commission_cash_after = $this->input->post('commission_cash_after');
        $commission_credit_within = $this->input->post('commission_credit_within');
        $commission_credit_after = $this->input->post('commission_credit_after');
        $product_type = $this->input->post("product_type");
        $sub_product_of = $this->input->post('sub_product_of');
        $quantity = $this->input->post('pr_quantity');
        $is_export_scale = $this->input->post('is_export_scale');
        $product_weight = $this->input->post('product_weight');
        $is_batch_validate = $this->input->post('is_batch_validate');
        
        
        $rep_commisison          = "";      
        $down_payment            = ""; 
        $per_day_rental          = ""; 
        $pd = array(
            'cat_id' => $category,
            'sub_cat_id' => $subcategory,
            'product_name' => $product_name,
            'product_code' => $product_code,
            'product_alert_qty' => $alert_quty,
            'product_unit' => $unit,
            'product_cost' => $product_cost,
            'product_price' => $product_price,
            'wholesale_price' => $wholesale_price,
            'credit_salling_price' => $credit_salling_price,
            'tax' => $tax,
            'product_details' => $product_details,
            'product_part_no' => $product_part_no,
            'product_oem_part_number' => $product_oem_part_number,
            'store_position' => $store_position,
            'product_max_qty' => $product_max_qty,
            'rep_commision' => $rep_commisison,
            'retail_cash' => $retail_cash,
            'retail_credit' => $retail_credit,
            'retail_wholesale' => $retail_wholesale,
            'brand_id' => $brand_id,
			'is_hw'	=> $is_hw,
			'is_special_rep_commisson'	=> $is_special_rep_commisson,
			'commission_cash_within'	=> $commission_cash_within,
			'commission_cash_after'	=> $commission_cash_after,
			'commission_credit_within'	=> $commission_credit_within,
			'commission_credit_after'	=> $commission_credit_after,
			'sub_product_of'=>$sub_product_of,
			'product_type_id'=>$product_type,
			'pr_quantity'=>$quantity,
			'is_export_scale'=>$is_export_scale,
			'product_weight'=>$product_weight,
			'is_batch_validate'=>$is_batch_validate
        );
        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);
                exit();
            } 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'];

                    $pd['product_image'] = $imgName['file_name'];
                    $pd['product_thumb'] = $imageThumb;

                    $this->image_lib->clear();
                }
            }
        } 
        if ($this->product_models->update_product($this->input->post('product_id'), $pd)) {
            $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 price_filter($amount = '')
    {
        $s = explode("Rs.", $amount);
        return str_replace(',', '', $s[1]);
    }
    public function get_list_product($value = '')
    {
        $search_key     = $this->input->get('search');
        $search_key_val = $search_key['value'];
        $start          = $this->input->get('start');
        $length         = $this->input->get('length');
        $totalData      = 0;
        $values         = $this->product_models->get_product_list($start, $length, $search_key_val);
        $value_count    = $this->product_models->get_product_list('', '', '');
        if ($search_key_val) {
            $values_c  = $this->product_models->get_product_list('', '', $search_key_val);
            $totalData = 100;  
        }
        $totalData     = $value_count;
        $totalFiltered = $totalData;
        $open = "";$close = "";
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $products) {
                $k = '';
                if ($products->product_status == 0) {
                    $k = "btn-danger";
                    $m = "fa-minus-circle";
                } else {
                    $k = "btn-green";
                    $m = "fa-check";
                }
                if ($products->product_status == 0) {
                        $open = '<a class="list-group-item list-group-item-danger">';
                        $close = '</a>';
                    } else if ($products->product_status == 1) {
                        $open = '<a class="list-group-item" style="border: none; background: inherit">';
                        $close = '</a>';
                    }
                $retVal              = (empty($products->sub_cat_name)) ? "--:--" : $products->sub_cat_name;
                $row                 = array();
                $ss_warehouse_id =  "";
               $qty=$this->Stock_Counter_Model->get_stock_balance($ss_warehouse_id,$products->product_id);
                $row[]               = '<div style="margin-bottom: 0px; width: 50px; height: 50px;" class="fileupload-new thumbnail"><img alt="" src="' . asset_url() . "uploads/thumbs/" . $products->product_thumb . '"></div>';
                $row[]               = $open.$products->product_code.$close;
                $row[]               = $open.$products->product_name.$close;
                $row[]               = $open.$products->cat_name.$close;
                $row[]               = $retVal;
                $row[]               = $open.$products->unit_name.$close;
                $bbreak = '';
                $row[] = $products->product_cost;
                $row[]  = $open.$qty.$close;
                $actdes = '';
                $disable = '<li><a style="cursor: pointer;" onclick="disable_product(' . $products->product_id . ')"><i class="glyphicon fa fa-minus-circle"></i> Disable </a></li>';
                $enable = '<li><a style="cursor: pointer;" onclick="enable_product(' . $products->product_id . ')"><i class="glyphicon fa fa-plus-circle"></i> Enable </a></li>';
                
                $actdes = $actdes . '<div class="btn-group text-left">
                            <button data-toggle="dropdown" class="btn btn-default btn-xs ' . $k . ' 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> Details</a></li>
                            ';
                    if($this->common_model->check_permission(113,$this->session->userdata( 'ss_group_id' ), 1 )){
                        if ($products->product_status == 0) {
                            $actdes .= $enable;
                        } else if ($products->product_status == 1) {
                            $actdes .= $disable;
                        }
                    }
                   
                    if($this->common_model->check_permission(112,$this->session->userdata( 'ss_group_id' ), 1 )){
                        $actdes = $actdes . '
                            <li><a href="' . base_url('products/edit') . '/' . $products->product_id . '"><i class="fa fa-edit"></i> Edit</a></li>
                           <!-- <li class="divider"></li><li><a onclick="product_delete(' . $products->product_id . '); return false;" href="#"><i class="fa fa-trash-o"></i> Delete </a></li> -->
                            ';
                    }
                $actdes = $actdes . '    
                            <li><a onclick=" print_barcode(' . $products->product_id . '); return false;" href="#"><i class="fa fa-print"></i>  Print Barcode</a></li>
                            '.$bbreak.'
                            </ul></div>';
                            
                if($this->common_model->check_permission(112,$this->session->userdata( 'ss_group_id' ), 1 )){
                       $row[]  = $actdes;
                    }else{
                      $row[]  = "";  
                    }
                $data[] = $row;
            }
            $output = array(
                'data' => $data,
                "recordsTotal" => intval($totalData),
                "recordsFiltered" => intval($totalFiltered)
            );
            echo json_encode($output);
        } else {
            $output = array(
                'data' => ''
            );
            echo json_encode($output);
        }
    }
    public function view($product_id = "")
    {
        $data['main_menu_name']     = $this->main_menu_name;
        $data['sub_menu_name']      = $this->sub_menu_name;
        $this->load->model('Batch_Process_Model');
        
        
        $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);
            $warehouses         = $this->Warehouse_Model->get_all_warehouse();
            $batch_list= $this->Batch_Process_Model->get_batch_list_by_product_id($product_id);
            
            $warehouse_batch_qty_array=array();
            foreach ($warehouses as $w) {
                 foreach($batch_list as $keyt => $row){
                $batch_stock=$this->Stock_Counter_Model->get_availble_stock_for_invoicing_and_order($w->id,$product_id,$row->batch_id);
                $nested_array=array(
                    'batch_ref_number'=>$row->batch_ref_number,
                    'warehouse_id'=>$w->id,
                    'retail_cash'=>$row->retail_cash,
                    'retail_wholesale'=>$row->retail_wholesale,
                    'product_cost'=>$row->product_cost,
                    'batch_status'=>$row->batch_status,
                    'batch_id'=>$row->batch_id,
                    'batch_stock'=>$batch_stock,
                    );
                    $warehouse_batch_qty_array[]=$nested_array;
            }
            }
            $data['warehouse_batch_qty_array'] =$warehouse_batch_qty_array;
            $data['warehouses']=$warehouses;
            $data['available_qty'] = $this->Stock_Counter_Model->get_availble_stock_for_invoicing_and_order('',$product_id);
            $batch_list_array=array();
            foreach($batch_list as $keyt => $row){
                $batch_stock=$this->Stock_Counter_Model->get_availble_stock_for_invoicing_and_order('',$product_id,$row->batch_id);
                $nested_array=array(
                    'batch_ref_number'=>$row->batch_ref_number,
                    'retail_cash'=>$row->retail_cash,
                    'retail_wholesale'=>$row->retail_wholesale,
                    'product_cost'=>$row->product_cost,
                    'batch_status'=>$row->batch_status,
                    'batch_id'=>$row->batch_id,
                    'batch_stock'=>$batch_stock,
                    );
                    $batch_list_array[]=$nested_array;
            }
            $data['batch_list'] =$batch_list_array;
            $this->load->view('product/view_product', $data);
        } else {
            show_404();
        }
    }
    public function edit($product_id = '')
    {
        if($this->common_model->check_permission(112,$this->session->userdata( 'ss_group_id' ), 1 )){
            $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['product_type']      = $this->product_models->getProductType();
            //$data['tax']             = $this->product_models->getTax();
            $data['product_details'] = $this->product_models->get_product_by_id($product_id);
            
            if(!empty($data['product_details'])){
                $data['sub_category']    = $this->category_models->getSubCategory($data['product_details']->cat_id);
                $this->load->view('product/edit_product', $data);
            }else show_404();
        }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);
    }
    public function single_barcode_test($product_id = '')
    {
        $data['product_details'] = $this->product_models->get_product_by_id($product_id);
        $this->load->view('barcode/product_barcode_test', $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 enable() {
        $product_id = $this->input->get('product_id');
        $result = $this->product_models->enable($product_id);
        return $result;
    }
    public function disable() {

        $product_id = $this->input->get('product_id');
        $result = $this->product_models->disable($product_id);
        return $result;
    }
    public function getProducts()
    {
        $str    = $this->input->get('search_string');
        $result = $this->product_models->get_search_products($str);
        echo json_encode($result);
    }
    public function getProductMaterial()
    {
        $str    = $this->input->get('search_string');
        $result = $this->product_models->get_search_products_material($str);
        echo json_encode($result);
    }
     public function export_for_scale_machine()
    {
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = "export_for_scale_machine";
        $this->load->view('product/scale_product', $data);
    }
    
     public function get_list_product_scale_export($value = '')
    {
       
        $search_key     = $this->input->get('search');
        $search_key_val = $search_key['value'];
        $start          = $this->input->get('start');
        $length         = $this->input->get('length');
        $totalData      = 0;
        $values         = $this->product_models->getScaleProducts();
        $totalData     = 1000;
        $totalFiltered = 1000;
        $open = "";$close = "";
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $products) {
                $k = '';
                if ($products->product_status == 0) {
                    $k = "btn-danger";
                    $m = "fa-minus-circle";
                } else {
                    $k = "btn-green";
                    $m = "fa-check";
                }
                if ($products->product_status == 0) {
                        $open = '<a class="list-group-item list-group-item-danger">';
                        $close = '</a>';
                    } else if ($products->product_status == 1) {
                        $open = '<a class="list-group-item" style="border: none; background: inherit">';
                        $close = '</a>';
                    }
                $retVal              = (empty($products->sub_cat_name)) ? "--:--" : $products->sub_cat_name;
                $row                 = array();
                $ss_warehouse_id =  $this->session->userdata('ss_warehouse_id');
                $currant_stock=$this->Stock_Counter_Model->get_stock_balance($ss_warehouse_id,$products->product_id);
                $row[]               = '<div style="margin-bottom: 0px; width: 50px; height: 50px;" class="fileupload-new thumbnail"><img alt="" src="' . asset_url() . "uploads/thumbs/" . $products->product_thumb . '"></div>';
                $row[]               = $open.$products->product_code.$close;
                $row[]               = $open.$products->product_name.$close;
                $row[]               = $open.$products->cat_name.$close;
                $row[]               = $retVal;
                $row[]               = $open.$products->product_cost.$close;
                $row[]               = $open.$products->retail_wholesale.$close;
                $row[]               = $open.$products->retail_credit.$close;
                $row[]               = $open.$products->retail_cash.$close;
                $row[]               = $open.$currant_stock.$close;
                $data[] = $row;
            }
            $output = array(
                'data' => $data,
                "recordsTotal" => intval($totalData),
                "recordsFiltered" => intval($totalFiltered)
            );
            echo json_encode($output);
        } else {
            $output = array(
                'data' => ''
            );
            echo json_encode($output);
        }
    }
    function export_notepad(){
        
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = "export_for_scale_machine";
        $data['product_list'] = $values         = $this->product_models->getScaleProducts();;
        $this->load->view('product/export_text', $data);
    }
    public function create_new_block() {
        $product_id = $this->input->get('product_id');
        $data=array(
            'product_id'=>$product_id,
            'added_user_id'=>$this->session->userdata('ss_user_id'),
            'added_date_time'=>date("Y-m-d H:i:s"),
            'product_block_code'=>$this->Common_Model->gen_ref_number('pbm_id','production_block_master','BL')
        );
        $result = $this->product_models->save_product_block($data);
        $status=0;
        if($result>0){
           $status=1; 
        }
        $retun_data=array(
            'result'=>$result,
            'status'=>$status,
            );
        echo json_encode($retun_data);
    }
    
    public function product_md()
    {
        $data['main_menu_name'] = 'products';
        $data['sub_menu_name']  = 'product_md';
        $this->load->view('product/manufacture_products', $data);
    }
    
     public function get_list_md_product($value = '')
    {
        $search_key     = $this->input->get('search');
        $search_key_val = $search_key['value'];
        $start          = $this->input->get('start');
        $length         = $this->input->get('length');
        $totalData      = 0;
        $values         = $this->product_models->getProducts($start, $length, $search_key_val);
        $value_count    = $this->product_models->getProducts('', '', '');
        if ($search_key_val) {
            $values_c  = $this->product_models->getProducts('', '', $search_key_val);
            $totalData = 100;  
        }
        $totalData     = $value_count;
        $totalFiltered = $totalData;
        $open = "";$close = "";
        $data          = array();
        if (!empty($values)) {
            foreach ($values as $products) {
                $k = '';
                if ($products->product_status == 0) {
                    $k = "btn-danger";
                    $m = "fa-minus-circle";
                } else {
                    $k = "btn-green";
                    $m = "fa-check";
                }
                if ($products->product_status == 0) {
                        $open = '<a class="list-group-item list-group-item-danger">';
                        $close = '</a>';
                    } else if ($products->product_status == 1) {
                        $open = '<a class="list-group-item" style="border: none; background: inherit">';
                        $close = '</a>';
                    }
                $retVal              = (empty($products->sub_cat_name)) ? "--:--" : $products->sub_cat_name;
                $row                 = array();
                $ss_warehouse_id =  "";
                $qty=$this->Stock_Counter_Model->get_availble_stock_for_invoicing_and_order($ss_warehouse_id,$products->product_id);
                $row[]               = '<div style="margin-bottom: 0px; width: 50px; height: 50px;" class="fileupload-new thumbnail"><img alt="" src="' . asset_url() . "uploads/thumbs/" . $products->product_thumb . '"></div>';
                $row[]               = $open.$products->product_code.$close;
                $row[]               = $open.$products->product_name.$close;
                $row[]               = $open.$products->cat_name.$close;
                $row[]               = $retVal;
                
                $bbreak = '';
                $row[]               = $open.$products->product_price;
                $row[]               = $open.$products->credit_salling_price;
                $row[]               = $open.$products->wholesale_price;
                $row[]               = $open.$products->unit_name.$close;
                $row[] = $products->product_cost;
               
                $row[]  = $open.$qty.$close;
                $actdes = '';
                $disable = '<li><a style="cursor: pointer;" onclick="disable_product(' . $products->product_id . ')"><i class="glyphicon fa fa-minus-circle"></i> Disable </a></li>';
                $enable = '<li><a style="cursor: pointer;" onclick="enable_product(' . $products->product_id . ')"><i class="glyphicon fa fa-plus-circle"></i> Enable </a></li>';
                
                $actdes = $actdes . '<div class="btn-group text-left">
                            <button data-toggle="dropdown" class="btn btn-default btn-xs ' . $k . ' 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> Details</a></li>
                            ';
                    if($this->common_model->check_permission(113,$this->session->userdata( 'ss_group_id' ), 1 )){
                        if ($products->product_status == 0) {
                            $actdes .= $enable;
                        } else if ($products->product_status == 1) {
                            $actdes .= $disable;
                        }
                    }
                    
                    if($this->common_model->check_permission(112,$this->session->userdata( 'ss_group_id' ), 1 )){
                        $actdes = $actdes . '
                            <li><a href="' . base_url('products/edit') . '/' . $products->product_id . '"><i class="fa fa-edit"></i> Edit</a></li>
                            
                           <!-- <li class="divider"></li><li><a onclick="product_delete(' . $products->product_id . '); return false;" href="#"><i class="fa fa-trash-o"></i> Delete </a></li> -->                            ';
                    }
                    
                    if(isset($products->pbm_id)){
                    //$actdes.='<li><a href="' . base_url('production_process/create_new_product_block?product_id='). $products->pbm_id . '"><i class="fa fa-edit"></i> Update Basic Formula</a></li>';
                    }else{
                        //$actdes.='<li class="divider"></li><li><a onclick="create_new_block(' . $products->product_id . '); return false;" href="#"><i class="fa fa-plus"></i> New Basic Formula</a></li>';
                    
                    }
                    
                $actdes = $actdes . '    
                            <li><a onclick=" print_barcode(' . $products->product_id . '); return false;" href="#"><i class="fa fa-print"></i>  Print Barcode</a></li>
                            '.$bbreak.'
                            </ul></div>';
                            
                if($this->common_model->check_permission(112,$this->session->userdata( 'ss_group_id' ), 1 )){
                       $row[]  = $actdes;
                    }else{
                      $row[]  = "";  
                    }
                $data[] = $row;
            }
            $output = array(
                'data' => $data,
                "recordsTotal" => intval($totalData),
                "recordsFiltered" => intval($totalFiltered)
            );
            echo json_encode($output);
        } else {
            $output = array(
                'data' => ''
            );
            echo json_encode($output);
        }
    }
    
    function name_suggess(){
        
        $this->load->library('form_validation'); //form validation lib
        $this->form_validation->set_rules('category', 'Product Category', 'trim|xss_clean');
        $this->form_validation->set_rules('subcategory', 'Item Category', 'trim|xss_clean');
        $this->form_validation->set_rules('unit', 'UOM', 'trim|xss_clean');
        $this->form_validation->set_rules('product_weight', 'UOM Weight', 'trim|xss_clean');
        $this->form_validation->set_rules('product_weight', 'UOM Weight', 'trim|xss_clean');
        if ($this->form_validation->run() == FALSE) {
            $st = array(
                'status' => 0,
                'validation' => validation_errors()
            );
            echo json_encode($st);
        } else {
            
            $category                = $this->input->post('category');
            $subcategory             = $this->input->post('subcategory');
            $unit                    = $this->input->post('unit');
            $product_weight          = $this->input->post('product_weight');
            $brand_id                = $this->input->post('brand_id');
            $brand_name='';
            $cat_name='';
            $sub_cat_name='';
            $uom_name='';
            $wight_unit='';
            if($brand_id){
             $brand_name=$this->product_models->get_brand_name($brand_id);  
            }
            if($subcategory){
             $sub_cat_name=$this->product_models->get_sub_cat_name($subcategory);  
            }
            if($category){
             $cat_name=$this->product_models->get_cat_name($category);
            }
             if($unit){
             $uom_name=$this->product_models->get_uom_name($unit);  
            }
            
            if($product_weight!=''&&$product_weight>=1){
              $wight_unit=$product_weight.'Kg';  
            }else{
                if($product_weight!=''){
                    $product_weight=$product_weight*1000;
                 $wight_unit=$product_weight.'g'; 
                }else{
                   $wight_unit=''; 
                }
                
               
            }
           
            $p_name=$brand_name." ".$sub_cat_name." ".$cat_name." ".$wight_unit." ".$uom_name;
            
            $st = array(
                'status' => 0,
                'validation' => $p_name
            );
            echo json_encode($st);
            
            
        }
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    }
}