<?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();
        error_reporting(E_ALL);
        ini_set('display_errors', 1);
        $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('Customer_Order_Process_Model');
        $this->load->model('Product_Discount_Model');
        $this->load->model('Pos_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['departments']       = $this->product_models->getDepartment();
        $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');
        $this->form_validation->set_rules('department_id', 'Department', '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]'); 
        }
        $product_type = $this->input->post("product_type");
      
         if($product_type==2){
          // $this->form_validation->set_rules('sub_product_of', 'GRN Material Code For Re-Manufacture', 'required|is_unique[product.sub_product_of]'); 
        }
        
        $this->form_validation->set_rules('product_cost', 'Product Cost', 'required');
        $this->form_validation->set_rules('product_type', 'Product Type', 'required');
        $is_hw = $this->input->post('is_hw');
        if ($is_hw) {
            //$this->form_validation->set_rules('retail_cash', 'Retail Cash Price', 'required');
        } else {
            //$this->form_validation->set_rules('product_price', 'Distribution Cash Price', '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->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');
             $department_id = $this->input->post('department_id');
            $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);  
             }
             if(!$subcategory){
                 $subcategory=0;
             }
              if($product_type==2){
             $pd_material = array(
            'mat_cat_id' => $category,
            'mat_sub_cat_id' => $subcategory,
            'product_mat_name' => $product_name,
            'product_mat_code' => $product_code,
            'product_mat_alert_qty' => $alert_quty,
            'product_mat_unit' => $unit,
            'product_mat_cost' => $product_cost,
            'product_mat_price' => $product_price,
            'mat_wholesale_price' => $wholesale_price,
            'mat_credit_salling_price' => $credit_salling_price,
            'mat_tax' => $tax,
            'product_mat_details' => $product_details,
            //'product_mat_part_no' => $product_part_no,
            //'product_mat_oem_part_number' => $product_oem_part_number,
            'mat_store_position' => $store_position,
            'product_mat_max_qty' => $product_max_qty,
            'mat_brand_id' => $brand_id,
			'product_mat_type_id'=>$product_type,
			'mat_pr_quantity'=>$quantity,
			'mat_is_export_scale'=>$is_export_scale,
			'department_id'=>$department_id
            );
            $last_id_pdm    = $this->product_models->save_product_material_table($pd_material);
            }else{
                  $last_id_pdm=$sub_product_of;
                  if(!$last_id_pdm){
                      $last_id_pdm=0;
                  }
            }
            $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,
			'sub_product_of'=>$last_id_pdm,
			'department_id'=>$department_id
        );
            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');
        $department_id = $this->input->post('department_id');
        
        
        $rep_commisison          = "";      
        $down_payment            = ""; 
        $per_day_rental          = ""; 
        
         if($product_type==2){
             $pd_material = array(
            'mat_cat_id' => $category,
            'mat_sub_cat_id' => $subcategory,
            'product_mat_name' => $product_name,
            'product_mat_code' => $product_code,
            'product_mat_alert_qty' => $alert_quty,
            'product_mat_unit' => $unit,
            'product_mat_cost' => $product_cost,
            'product_mat_price' => $product_price,
            'mat_wholesale_price' => $product_price,
            'mat_credit_salling_price' => $product_price,
            'mat_tax' => $tax,
            'product_mat_details' => $product_details,
            'product_mat_part_no' => $product_part_no,
            'product_mat_oem_part_number' => $product_oem_part_number,
            'mat_store_position' => $store_position,
            'product_mat_max_qty' => $product_max_qty,
            'mat_brand_id' => $brand_id,
			'product_mat_type_id'=>$product_type,
			'mat_pr_quantity'=>$quantity,
			'mat_is_export_scale'=>$is_export_scale,
			'department_id'=>$department_id
            );
            $last_id_pdm    = $this->product_models->update_product_material($sub_product_of,$pd_material);
            }
        $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_cash,
            'retail_wholesale' => $retail_cash,
            '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,
			'department_id'=>$department_id
        );
        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 = '')
    {
        //$this->load->model('Marketing_Delivery_Model');
        $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->getRowMaterials($start, $length, $search_key_val);
        $value_count    = $this->product_models->getRowMaterials('', '', '');
        if ($search_key_val) {
            $values_c  = $this->product_models->getRowMaterials('', '', $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($products->product_type_id==2||$products->product_type_id==2){
                        $actdes.='<li class="divider"></li><li><a onclick="create_new_block(' . $products->product_id . '); return false;" href="#"><i class="fa fa-trash-o"></i> Create New Block</a></li>';
                    }
                    if(true/*$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(true/*$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');
        $warehouses         = $this->Warehouse_Model->get_all_warehouse();
        $data['warehouses']=$warehouses;
        $sd = $this->product_models->get_product_by_id($product_id);
        //--------------------------------if finish product 
        if (!empty($sd)) {
            $data['product_details']    = $this->product_models->get_product_by_id($product_id);
            if($data['product_details']->product_type_id==3){
            $batch_list= $this->Batch_Process_Model->get_final_product_all_limited_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->getFinalProductStockBalance($w->id,$product_id,$row->pbi_id);
                if($batch_stock==0){
                    $data_set_batch=array(
                        'stock_clean'=>1
                        );
                        //$this->Batch_Process_Model->update_production_batch_items($data_set_batch,$row->pbi_id);
                    }
                $nested_array=array(
                    'batch_ref_number'=>$row->pbi_ref_no,
                    'warehouse_id'=>$w->id,
                    'retail_cash'=>0,
                    'retail_wholesale'=>0,
                    'product_cost'=>$row->pbi_unit_cost,
                    'batch_status'=>1,
                    'batch_id'=>$row->pbi_id,
                    'batch_stock'=>$batch_stock,
                    );
                    $warehouse_batch_qty_array[]=$nested_array;
            }
            }
           }
           //--------------------------------if value added product 
            if($data['product_details']->product_type_id==2){
            $batch_list= $this->Batch_Process_Model->get_final_value_added_product_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_final_value_added_batch_stock_count($w->id,$product_id,$row->bfp_id);
                $nested_array=array(
                    'batch_ref_number'=>$row->bfp_batch_code,
                    'warehouse_id'=>$w->id,
                    'retail_cash'=>0,
                    'retail_wholesale'=>0,
                    'product_cost'=>0,
                    'batch_status'=>1,
                    'batch_id'=>$row->bfp_id,
                    'batch_stock'=>$batch_stock,
                    );
                    $warehouse_batch_qty_array[]=$nested_array;
            }
            }
           }
            $data['warehouse_batch_qty_array'] =$warehouse_batch_qty_array;
           
           
           //if finish product 
           if($data['product_details']->product_type_id==3){
            $data['available_qty'] = $this->Stock_Counter_Model->getFinalProductStockBalance('',$product_id);
            
            $batch_list_array=array();
            foreach($batch_list as $keyt => $row){
                $batch_stock=$this->Stock_Counter_Model->getFinalProductStockBalance('',$product_id,$row->pbi_id);
                $nested_array=array(
                    'batch_ref_number'=>$row->pbi_ref_no,
                    'retail_cash'=>0,
                    'retail_wholesale'=>0,
                    'product_cost'=>$row->pbi_unit_cost,
                    'batch_status'=>1,
                    'stock_clean'=>$row->stock_clean,
                    'batch_id'=>$row->pbi_id,
                    'batch_stock'=>$batch_stock,
                    );
                    $batch_list_array[]=$nested_array;
            }
            $data['batch_list'] =$batch_list_array;
            }
            
            //if finish product 
           if($data['product_details']->product_type_id==2){
                 $batch_list= array();//$this->Batch_Process_Model->get_final_value_added_product_batch_list_by_product_id($product_id);
            $data['available_qty'] = $this->Stock_Counter_Model->get_final_value_added_batch_stock_count('',$product_id);
            $batch_list_array=array();
            foreach($batch_list as $keyt => $row){
                $batch_stock=$this->Stock_Counter_Model->get_final_value_added_batch_stock_count('',$product_id,$row->bfp_id);
                $nested_array=array(
                    'batch_ref_number'=>$row->bfp_batch_code,
                    'retail_cash'=>0,
                    'retail_wholesale'=>0,
                    'product_cost'=>0,
                    'batch_status'=>1,
                    'batch_id'=>$row->bfp_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['departments']       = $this->product_models->getDepartment();
            $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 =  "";
                if($products->product_type_id==3){
                $qty=$this->Stock_Counter_Model->getFinalProductStockBalance('',$products->product_id);
                }else{
                   $qty=0; 
                }
                $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->mpt_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> -->                            ';
                    }
                    
                    if(isset($products->pbm_id)){
                        if(!($this->session->userdata('ss_group_id')==18)){
                            if(!($this->session->userdata('ss_group_id')==2 )){
                    $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{
                          if(!($this->session->userdata('ss_group_id')==18 )){
                                if(!($this->session->userdata('ss_group_id')==2 )){
                        $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(true/*$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);
        }
    }
}