<?php

use PhpParser\Node\Expr\AssignOp\Mod;

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

class Products extends MY_Controller
{

    function __construct() {
        parent::__construct();


        if (!$this->loggedIn) {
            redirect('login');
        }

        $this->load->library('form_validation');
        $this->load->model('products_model');

        require("funciones.php");
    }

    public function index() {
        //var_dump($this->Admin);exit;
        //exit;
        $data['error'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('error');
        $this->data['page_title'] = lang('products');
        $this->data['warehouses'] = $this->site->getAllWarehouses();
        $biz = array(
            "ruc_number" => (string)($this->session->userdata('ruc'))
        );
        
        $context_data['business_information'] = $biz;
        $urlCategories = "categories";

        $context = stream_context_create(array(
            'http' => array(
                'method' => 'GET',
                'header' => "Authorization: application/json\r\n" . 
                "Content-Type: application/json\r\n",
                'content' => json_encode($context_data)
            )
        ));

        $url = $this->config->item('api_almacen');
        $response = file_get_contents($url . $urlCategories, false, $context);
        $res = json_decode($response, true);
        $categories = $res['data']['list'];
        $this->data['categories'] = $categories;
        $bc = array(array('link' => '#', 'page' => lang('products')));
        $meta = array('page_title' => lang('products'), 'bc' => $bc);
        $this->page_construct('products/index', $this->data, $meta);



    }

    function get_products() {
        $columnas = array(
            0 => 'image',
            1 => 'code',
            2 => 'name',
            3 => 'type',
            4 => 'category_id',
            5 => 'quantity',
            6 => 'tax_method',
            7 => 'currency',
            8 => 'cost',
            9 => 'price',
            10 => 'view',
            11 => 'print_codebar',
            12 => 'print_labels',
            13 => 'view_codebar',
            14 => 'view_image',
            15 => 'edit',
            15 => 'delete'
        );

        $data = $_GET;
        $filtro = $_GET["search"]['value'];
        $orderby = $columnas[$data['order'][0]['column']];
        $orderdir = $_GET['order'][0]['dir'];
        $start = $_GET['start'];
        $length = $_GET['length'];
        $draw = $_GET["draw"];

        if(!empty($this->input->get("warehouse_id") && $this->input->get("warehouse_id") !=0)){
            $warehouse_id = $this->input->get("warehouse_id");
        }else{
            $warehouse_id = "";
        }
        if(!empty($this->input->get("category_id") && $this->input->get("category_id") !=0)){
            $category_id = $this->input->get("category_id");
        }else{
            $category_id = "";
        }
        
        $filter = [
                'category_id' => $category_id,
                'warehouse_id' => $warehouse_id,
        ];
        
        $rows = array();
        $temporal = array();

        $biz = array(
            "ruc_number"=> (string)($this->session->userdata('ruc'))
        );


        $context_data["business_information"] = $biz;
        $context_data["filters"] = $filter;
        $context_data["search"] = $filtro ;
        $context_data["orderby"] = $orderby ;
        $context_data["orderdir"] = $orderdir ;
        $context_data["start"] = $start ;
        $context_data["length"] = $length;

        $urlDoc = "products";

        $context = stream_context_create(array(
            'http' => array(
                'method' => 'GET',
                'header' => "Authorization: application/json\r\n" . "Content-Type: application/json\r\n",
                'content' => json_encode($context_data)
            )
        ));

        $url = $this->config->item('api_almacen');
        $response = file_get_contents($url . $urlDoc, false, $context);
        $response = json_decode($response, true);

        $products = $response['data'];

        $contador_total = $products['total'];
        $contador_filtrado = $products['total'];


        $rows['draw'] = $draw;

        $rows['recordsTotal'] = $contador_total;
        $rows['recordsFiltered'] = $contador_filtrado;

        foreach ($products['list'] as $item) {
            $image = "";

            $id = $item['id'];
            $image = $item['image'];
            $code = $item['code'];
            $name = $item['name'];
            $type = $item['type'];
            $category_id = $item['category_id'];
            $quantity = $item['quantity'];
            $barcode_symbology = $item['barcode_symbology'];
            $tax_method = $item['tax_method'];
            $currency = $item['currency'];
            $cost = $item['cost'];
            $price = $item['price'];

            $category_data = $this->site->getCategoryByID($category_id);
            $quantity_data = $this->site->getStockProductByID($id);

            if ($image == "no_image.png") {
                $view_image = '<a href="' . base_url() . 'uploads/thumbs/' . $image . '" class="image-modal tip image btn btn-primary btn-xs" data-title="' . $name . ' (' . $code . ')" title="' . lang("view_image") . '"><i class="fa fa-picture-o"></i></a>';
                $image = '<a href="' . base_url() . 'uploads/thumbs/' . $image . '" class="image-modal" data-title="' . $name . ' (' . $code . ')"><img src="' . base_url() . 'uploads/thumbs/' . $image . '" class="img-responsive" width="32" style="margin: auto;" /></a>';
            } else {
                $view_image = '<a href="' . base_url() . 'uploads/' . $image . '" class="image-modal tip image btn btn-primary btn-xs" data-title="' . $name . ' (' . $code . ')" title="' . lang("view_image") . '"><i class="fa fa-picture-o"></i></a>';
                $image = '<a href="' . base_url() . 'uploads/' . $image . '" class="image-modal" data-title="' . $name . ' (' . $code . ')"><img src="' . base_url() . 'uploads/' . $image . '" class="img-responsive" width="32" style="margin: auto;" /></a>';
            }

            if ($type == "standard") { $type_data = "<span>" . lang('standard') . "</span>"; }
            if ($type == "service") { $type_data = "<span>" . lang('service') . "</span>"; }
            if ($type == "combo") { $type_data = "<span>" . lang('combo') . "</span>"; }

            if ($tax_method == "0") { $tax_method_data = "<span class='label label-primary'>" . lang('inclusive') . "</span>"; }
            if ($tax_method == "1") { $tax_method_data = "<span class='label label-warning'>" . lang('exclusive') . "</span>"; }
            if ($tax_method == "2") { $tax_method_data = "<span class='label label-default'>" . lang('inaffected') . "</span>"; }
            if ($tax_method == "3") { $tax_method_data = "<span class='label label-info'>" . lang('exonerated') . "</span>"; }

            if ($currency == "PEN") { $currency_data = "<span class='label label-primary'>" . lang('currency_pen') . "</span>"; }
            if ($currency == "USD") { $currency_data = "<span class='label label-success'>" . lang('currency_usd') . "</span>"; }
            
            $view = '<span class="btn"><a href="' . site_url('products/view/' . $id) . '" title="' . lang("view") . '" data-toggle="ajax"><i class="fa fa-file-text-o"></i></a></span>';
            $print_codebar = '<span class="btn"><a href="' . site_url('products/print_barcodes/' . $id) . '" title="' . lang("print_barcodes") . '" class="print-modal"><i class="fa fa-print"></i></a></span>';
            $print_labels = '<span class="btn"><a href="' . site_url('products/single_label/' . $id) . '" title="' . lang("print_labels") . '" class="print-modal"><i class="fa fa-print"></i></a></span>';
            $view_codebar = '<span class="btn"><a href="' . site_url('products/gen_barcode/' . $code . '/'. $barcode_symbology) . '" title="' . lang("view_barcode") . '" class="image-modal" data-title="' . $name . ' (' . $code . ')"><i class="fa fa-barcode"></i></a></span>';
            
            $edit = '<span class="btn"><a href="' . site_url('products/edit/' . $id) . '" title="' . lang("edit_product") . '"><i class="fa fa-edit"></i></a></span>';
            $delete = '<span class="btn"><a href="' . site_url('products/delete/' . $id) . '" onClick="return confirm(&#39;' . lang("delete_product") . '&#39;)" title="' . lang("delete_product") . '"><i class="fa fa-trash-o"></i></a></span>';
            

            $html_action = "<div class='text-center'>";
            $html_action .= "<div class='btn-group'>";
            $html_action .= '<a href="' . site_url('products/view/' . $id) . '" title="' . lang("view") . '" class="tip btn btn-primary btn-xs" data-toggle="ajax"><i class="fa fa-file-text-o"></i></a>';
            $html_action .= '<a href="' . site_url('products/print_barcodes/' . $id) . '" title="' . lang("print_barcodes") . '" class="print-modal tip btn btn-default btn-xs"><i class="fa fa-print"></i></a>';
            $html_action .= '<a href="' . site_url('products/single_label/' . $id) . '" title="' . lang("print_labels") . '" class="print-modal tip btn btn-default btn-xs"><i class="fa fa-print"></i></a>';
            $html_action .= '<a href="' . site_url('products/gen_barcode/' . $code . '/'. $barcode_symbology) . '" title="' . lang("view_barcode") . '" class="image-modal barcode tip btn btn-primary btn-xs" data-title="' . $name . ' (' . $code . ')"><i class="fa fa-barcode"></i></a>';
            $html_action .= $view_image;
        
            
            $html_action .= '<a href="' . site_url('products/edit/' . $id) . '" title="' . lang("edit_product") . '" class="tip btn btn-warning btn-xs"><i class="fa fa-edit"></i></a>';
            $html_action .= '<a href="' . site_url('products/delete/' . $id) . '" onClick="return confirm(&#39;' . lang("question_remove_product") . '&#39;)" title="' . lang("delete_product") . '" class="tip btn btn-danger btn-xs"><i class="fa fa-trash-o"></i></a>';
            $html_action .= "</div>";
            $html_action .= "</div>";
            
            

            /*"<div class='text-center'>".
            "   <div class='btn-group'>".
            "       <a href='".site_url('products/view/' . $id)."' title='" . lang("view") . "' class='tip btn btn-primary btn-xs' data-toggle='ajax'>".
            "           <i class='fa fa-file-text-o'></i>".
            "       </a>".
            "       <a onclick=\"window.open('".site_url('products/print_barcodes/' . $id). "', 'pos_popup', 'width=900,height=600,menubar=yes,scrollbars=yes,status=no,resizable=yes,screenx=0,screeny=0'); return false;\" href='#' title='" .lang('print_barcodes'). "' class='tip btn btn-default btn-xs'>".
            "           <i class='fa fa-print'></i>".
            "       </a>".
            "       <a onclick=\"window.open('".site_url('products/single_label/' . $id). "', 'pos_popup', 'width=900,height=600,menubar=yes,scrollbars=yes,status=no,resizable=yes,screenx=0,screeny=0'); return false;\" href='#' title='" .lang('print_labels'). "' class='tip btn btn-default btn-xs'>".
            "           <i class='fa fa-print'></i>".
            "       </a>".
            "       <a id='$4 ($3)' href='" . site_url('products/gen_barcode/$3/$5') . "' title='" . lang("view_barcode") . "' class='barcode tip btn btn-primary btn-xs'>".
            "            <i class='fa fa-barcode'></i>".
            "       </a>".
            "       <a class='tip image btn btn-primary btn-xs' id='$4 ($3)' href='" . base_url('uploads/$2') . "' title='" . lang("view_image") . "'>".
            "            <i class='fa fa-picture-o'></i>".
            "       </a>".
            "       <a href='" . site_url('products/edit/$1') . "' title='" . lang("edit_product") . "' class='tip btn btn-warning btn-xs'>".
            "           <i class='fa fa-edit'></i>".
            "       </a>".
            "       <a href='" . site_url('products/delete/$1') . "' onClick=\"return confirm('" . lang('alert_x_product') . "')\" title='" . lang("delete_product") . "' class='tip btn btn-danger btn-xs'>".
            "            <i class='fa fa-trash-o'></i>".
            "       </a>".
            "    </div>".
            "</div>";*/


            $datos = (array('image' => $image, 'code' => $code, 'name' => $name, 'type' => $type_data,
                'category_id' => $category_data->name, 'quantity' => $quantity_data->quantity,
                'tax_method' => $tax_method_data, 'currency' => $currency_data, 'cost' => $cost,
                'cost' => $cost, 'price' => $price, 'view' => $view, 'print_codebar' => $print_codebar,
                'print_labels' => $print_labels, 'view_codebar' => $view_codebar, 'view_image' => $view_image,
                'edit' => $edit, 'delete' => $delete, 'actions' => $html_action));
            array_push($temporal,$datos);
        }

        $rows['listados'] = $temporal;

        echo json_encode($rows);
    }



    function get_products_search() {
        $this->load->library('datatables');

        switch($this->session->userdata('category')){
            case 0:
                $this->datatables->select($this->db->dbprefix('products').".id as pid,  ".$this->db->dbprefix('products').".code as code2, concat('<a href=\'#\' style=\'text-decoration:underline\'>',  ".$this->db->dbprefix('products').".code,'</a>') as code,  ".$this->db->dbprefix('products').".name as pname,  ".$this->db->dbprefix('categories').".name as cname, maker, price, IFNULL(stock, 0) as stock, price - cost as margen  ", FALSE); //quantity
                break;
            case 1:
                $this->datatables->select($this->db->dbprefix('products').".id as pid,  ".$this->db->dbprefix('products').".code as code2, concat('<a href=\'#\' style=\'text-decoration:underline\'>',  ".$this->db->dbprefix('products').".code,'</a>') as code,  ".$this->db->dbprefix('products').".name as pname, custom_field_1, custom_field_2,  ".$this->db->dbprefix('categories').".name as cname, maker, price, IFNULL(stock, 0) as stock, price - cost as margen  ", FALSE); //quantity
                break;
        }

        $this->datatables->join('categories', 'categories.id=products.category_id')
        ->join('makers', 'makers.id=products.maker_id', 'left')
        ->join('tec_warehouse_stock', 'tec_warehouse_stock.product_id=products.id AND warehouse_id='.$this->Settings->default_warehouse, 'left')
        ->from('products')
        //->where('category_id', $this->input->post('product_search') )
        ->where('products.estado =', 1)
        // ->where('stock >', 0)
        ->group_by('products.id');

        $v1 =  $this->input->post('product_search' );
        $v2 =  $this->input->post('prin_activ_search') ;
        $v3 =  $this->input->post('acc_farm_search') ;

        if(trim($v1)!=""){
             $this->datatables->where($this->db->dbprefix('products').".name like '%".$v1."%'");
        }
        if(trim($v2)!=""){
             $this->datatables->where("custom_field_1 like '%".$v2."%'");
        }
        if(trim($v3)!=""){
             $this->datatables->where("custom_field_2 like '%".$v3."%'");
        }

        //$this->datatables->add_column("Actions", "<div class='text-center'><div class='btn-group'><a href='".site_url('products/view/$1')."' title='" . lang("view") . "' class='tip btn btn-primary btn-xs' data-toggle='ajax'><i class='fa fa-file-text-o'></i></a></div></div>", "pid");

        $this->datatables->add_column("Actions", "<input type='hidden' value='$1'><div class='text-center'><div class='btn-group'><button  vid='$1' title='" . lang("add") . "' class='tip btn btn-primary btn-xs' ><i class='fa fa-plus'></i></button></div></div>", "code2");


        //$this->datatables->unset_column('pid')->unset_column('barcode_symbology');
        $this->datatables->unset_column('pid');
        $this->datatables->unset_column('code2');
        echo $this->datatables->generate();
    }

    function view($id = NULL) {
        $data['error'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('error');
        $product = $this->site->getProductByID($id);

        $mk = $this->site->getMakerByID($product->maker_id);
        $maker = "";
        if($mk){
            $maker = $mk->maker;
        }
        $this->data['maker'] = $maker;
        $this->data['product'] = $product;
        $this->data['category'] = $this->site->getCategoryByID($product->category_id);
        $this->data['combo_items'] = $product->type == 'combo' ? $this->products_model->getComboItemsByPID($id) : NULL;
        $this->load->view($this->theme.'products/view', $this->data);
    }

    function barcode($product_code = NULL) {
        if ($this->input->get('code')) {
            $product_code = $this->input->get('code');
        }

        $data['product_details'] = $this->products_model->getProductByCode($product_code);
        $data['img'] = "<img src='" . base_url() . "index.php?products/gen_barcode&code={$product_code}' alt='{$product_code}' />";
        $this->load->view('barcode', $data);
    }

    function product_barcode($product_code = NULL, $bcs = 'code39', $height = 60) {
        if ($this->input->get('code')) {
            $product_code = $this->input->get('code');
        }
        return "<img src='" . base_url() . "products/gen_barcode/{$product_code}/{$bcs}/{$height}' alt='{$product_code}' />";
    }

    function gen_barcode($product_code = NULL, $bcs = 'code39', $height = 60, $text = 1) {
        $drawText = ($text != 1) ? FALSE : TRUE;
        $this->load->library('zend');
        $this->zend->load('Zend/Barcode');
        $barcodeOptions = array('text' => $product_code, 'barHeight' => $height, 'drawText' => $drawText);
        $rendererOptions = array('imageType' => 'png', 'horizontalPosition' => 'center', 'verticalPosition' => 'middle');
        $imageResource = Zend_Barcode::render($bcs, 'image', $barcodeOptions, $rendererOptions);
        return $imageResource;
    }

    function print_barcodes() {
        $this->load->library('pagination');

        $per_page = $this->input->get('per_page') ? $this->input->get('per_page') : 0;

        $config['base_url'] = site_url('products/print_barcodes');
        $config['total_rows'] = $this->products_model->products_count();
        $config['per_page'] = 20;
        $config['num_links'] = 5;

        $config['full_tag_open'] = '<ul class="pagination pagination-sm">';
        $config['full_tag_close'] = '</ul>';
        $config['first_tag_open'] = '<li>';
        $config['first_tag_close'] = '</li>';
        $config['last_tag_open'] = '<li>';
        $config['last_tag_close'] = '</li>';
        $config['next_tag_open'] = '<li>';
        $config['next_tag_close'] = '</li>';
        $config['prev_tag_open'] = '<li>';
        $config['prev_tag_close'] = '</li>';
        $config['num_tag_open'] = '<li>';
        $config['num_tag_close'] = '</li>';
        $config['cur_tag_open'] = '<li class="active"><a>';
        $config['cur_tag_close'] = '</a></li>';

        $this->pagination->initialize($config);

        $products = $this->products_model->fetch_products($config['per_page'], $per_page);
        $r = 1;
        $html = "";
        $html .= '<table class="table table-bordered">
        <tbody><tr>';
        foreach ($products as $pr) {
            if ($r != 1) {
                $rw = (bool)($r & 1);
                $html .= $rw ? '</tr><tr>' : '';
            }
            $html .= '<td><h4>' . $this->Settings->site_name . '</h4><strong>' . $pr->name . '</strong><br>' . $this->product_barcode($pr->code, $pr->barcode_symbology, 60); // . '<br><span class="price">'.lang('price') .': ' .$this->Settings->currency_prefix. ' ' . $pr->price . '</span></td>';
            $r++;
        }
        $html .= '</tr></tbody>
        </table>';

        $this->data['html'] = $html;
        $this->data['page_title'] = lang("print_barcodes");
        $this->load->view($this->theme.'products/print_barcodes', $this->data);
    }

    function print_labels() {
        $this->load->library('pagination');

        $per_page = $this->input->get('per_page') ? $this->input->get('per_page') : 0;

        $config['base_url'] = site_url('products/print_labels');
        $config['total_rows'] = $this->products_model->products_count();
        $config['per_page'] = 10;
        $config['num_links'] = 5;

        $config['full_tag_open'] = '<ul class="pagination pagination-sm">';
        $config['full_tag_close'] = '</ul>';
        $config['first_tag_open'] = '<li>';
        $config['first_tag_close'] = '</li>';
        $config['last_tag_open'] = '<li>';
        $config['last_tag_close'] = '</li>';
        $config['next_tag_open'] = '<li>';
        $config['next_tag_close'] = '</li>';
        $config['prev_tag_open'] = '<li>';
        $config['prev_tag_close'] = '</li>';
        $config['num_tag_open'] = '<li>';
        $config['num_tag_close'] = '</li>';
        $config['cur_tag_open'] = '<li class="active"><a>';
        $config['cur_tag_close'] = '</a></li>';

        $this->pagination->initialize($config);

        $products = $this->products_model->fetch_products($config['per_page'], $per_page);

        $html = "";

        foreach ($products as $pr) {
            $html .= '<div class="labels"><strong>' . $pr->name . '</strong><br>' . $this->product_barcode($pr->code, $pr->barcode_symbology, 25) . '<br><span class="price">'.lang('price') .': ' .$this->Settings->currency_prefix. ' ' . $pr->price . '</span></div>';
        }

        $this->data['html'] = $html;
        $this->data['page_title'] = lang("print_labels");
        $this->load->view($this->theme.'products/print_labels', $this->data);
    }

    function single_barcode($product_id = NULL) {
        $product = $this->site->getProductByID($product_id);
        $detail = $this->products_model->getProductStock($product_id);

        $html = "";
        $html .= '<table class="table table-bordered">
        <tbody><tr>';
        if($detail->stock > 0) {
            for ($r = 1; $r <= $detail->stock; $r++) {
                if ($r != 1) {
                    $rw = (bool)($r & 1);
                    $html .= $rw ? '</tr><tr>' : '';
                }
                $html .= '<td><h4>' . $this->Settings->site_name . '</h4><strong>' . $product->name . '</strong><br>' . $this->product_barcode($product->code, $product->barcode_symbology, 60); //. ' <br><span class="price">'.lang('price') .': ' .$this->Settings->currency_prefix. ' ' . $product->price . '</span></td>';
            }
        } else {
            for ($r = 1; $r <= 20; $r++) {
            if ($r != 1) {
                $rw = (bool)($r & 1);
                $html .= $rw ? '</tr><tr>' : '';
            }
            $html .= '<td><h4>' . $this->Settings->site_name . '</h4><strong>' . $product->name . '</strong><br>' . $this->product_barcode($product->code, $product->barcode_symbology, 60); //. ' <br><span class="price">'.lang('price') .': ' .$this->Settings->currency_prefix. ' ' . $product->price . '</span></td>';
        }
        }
        $html .= '</tr></tbody>
        </table>';

        $this->data['html'] = $html;
        $this->data['page_title'] = lang("print_barcodes");
        $this->load->view($this->theme . 'products/single_barcode', $this->data);
    }

    function single_label($product_id = NULL, $warehouse_id = NULL) {
        $product = $this->site->getProductByID($product_id);
        $detail = $this->products_model->getProductStock($product_id);
        $html = "";
        if($detail->stock > 0) {
            for ($r = 1; $r <= $detail->stock; $r++) {
                $html .= '<div class="labels"><strong>' . $product->name . '</strong><br>' . $this->product_barcode($product->code, $product->barcode_symbology, 25) . ' <br><span class="price">'.lang('price') .': ' .$this->Settings->currency_prefix. ' ' . $product->price . '</span></div>';
            }
        } else {
            for ($r = 1; $r <= 10; $r++) {
                $html .= '<div class="labels"><strong>' . $product->name . '</strong><br>' . $this->product_barcode($product->code, $product->barcode_symbology, 25) . ' <br><span class="price">'.lang('price') .': ' .$this->Settings->currency_prefix. ' ' . $product->price . '</span></div>';
            }
        }
        $this->data['html'] = $html;
        $this->data['page_title'] = lang("barcode_label");
        $this->load->view($this->theme . 'products/single_label', $this->data);
    }

    function add() 
    {
        // if (!$this->Admin) {
        //     $this->session->set_flashdata('error', lang('access_denied'));
        //     redirect('pos');
        // } 

        $response_api = "";

        $this->form_validation->set_rules('code', lang("product_code"), 'trim|min_length[2]|max_length[50]|required|alpha_numeric');
        //$this->form_validation->set_rules('category', lang("category"), 'required');
        $this->form_validation->set_rules('name', lang("product_name"), 'required');
        // $this->form_validation->set_rules('short_name', lang("short_name"), 'required');
        // $this->form_validation->set_rules('maker_id', lang("maker"), 'required');
        // $this->form_validation->set_rules('brand_id', lang("brand"), 'required');
        $this->form_validation->set_rules('price', lang("product_price"), 'required|is_numeric');
        $this->form_validation->set_rules('cost', lang("product_cost"), 'required|is_numeric');
        // $this->form_validation->set_rules('product_tax', lang("product_tax"), 'required|is_numeric');
        //$this->form_validation->set_rules('quantity', lang("quantity"), 'is_numeric');
        // $this->form_validation->set_rules('alert_quantity', lang("alert_quantity"), 'is_numeric');
        // $this->form_validation->set_rules('currency', lang("currency_name"), 'required');
        // $this->form_validation->set_rules('unit_measure_id', lang("unit_measure"), 'required');

        if ($this->form_validation->run() == true) {
            if ($this->input->post('requires_lot_number') == false) {
                $requires_lot_number = 0;
            } else {
                $requires_lot_number = 1;
            }

            if ($this->input->post('requires_serial_number') == false) {
                $requires_serial_number = 0;
            } else {
                $requires_serial_number = 1;
            }

            $quantity = 0;

            $context_data = array(
                'type' => $this->input->post('type'),
                'name' => $this->input->post('name'),
                'code' => $this->input->post('code'),
                'short_name' => $this->input->post('short_name'),
                'requires_lot_number' => $requires_lot_number,
                'requires_serial_number' => $requires_serial_number,
                'category_id' => $this->input->post('category'),
                'maker_id' => $this->input->post('maker'),
                'brand_id' => $this->input->post('brand'),
                'model_id' => $this->input->post('model'),
                'unit_measure_id' => $this->input->post('unit_measure'),
                'barcode_symbology' => $this->input->post('barcode_symbology'),
                'presentation' => $this->input->post('presentation'),
                'alert_quantity' => $this->input->post('alert_quantity'),
                'currency' => $this->input->post('currency'),
                'cost' => $this->input->post('cost'),
                'price' => $this->input->post('price'),
                'tax_method' => $this->input->post('tax_method'),
                'details' => $this->input->post('details'),
                'uCrea' => $this->session->userdata('user_id'),
                'fCrea' => date("Y-m-d H:i:s"),
                'estado' => 1,
                'tax' => 0,
                // 'tax' => $this->input->post('product_tax'),
                'quantity' => $quantity,
                'custom_field_1' => $this->input->post('custom_field_1'),
                'custom_field_2' => $this->input->post('custom_field_2'),
                'custom_field_3' => $this->input->post('custom_field_3')
            );

            if ($this->input->post('type') == 'combo') {
                $c = sizeof($_POST['combo_item_code']) - 1;
                for ($r = 0; $r <= $c; $r++) {
                    if (isset($_POST['combo_item_code'][$r]) && isset($_POST['combo_item_quantity'][$r])) {
                        $items[] = array(
                            'item_code' => $_POST['combo_item_code'][$r],
                            'quantity' => $_POST['combo_item_quantity'][$r]
                        );
                    }
                }
            } else {
                $items = array();
            }

            $context_data['items'] = $items;

            if ($_FILES['userfile']['size'] > 0) {
                $this->load->library('upload');

                $config['upload_path'] = 'uploads/';
                $config['allowed_types'] = 'gif|jpg|png';
                $config['max_size'] = '500';
                $config['max_width'] = '800';
                $config['max_height'] = '800';
                $config['overwrite'] = FALSE;
                $config['encrypt_name'] = TRUE;
                $this->upload->initialize($config);

                if (!$this->upload->do_upload()) {
                    $error = $this->upload->display_errors();
                    $this->session->set_flashdata('error', $error);
                    $this->session->set_flashdata('form_data', $_POST);
                    redirect("products/add", 'refresh');
                }

                $photo = $this->upload->file_name;
                $context_data['image'] = $photo;

                $this->load->library('image_lib');
                $config['image_library'] = 'gd2';
                $config['source_image'] = 'uploads/' . $photo;
                $config['new_image'] = 'uploads/thumbs/' . $photo;
                $config['maintain_ratio'] = TRUE;
                $config['width'] = 110;
                $config['height'] = 110;

                $this->image_lib->clear();
                $this->image_lib->initialize($config);

                if (!$this->image_lib->resize()) {
                    $this->session->set_flashdata('error', $this->image_lib->display_errors());
                    $this->session->set_flashdata('form_data', $_POST);
                    redirect("products/add");
                }
            } else {
                $photo = "box.png";
            }

            $context_data['image'] = $photo;

            $biz = array(
                "ruc_number"=> (string)($this->session->userdata('ruc'))
            );

            $context_data["business_information"] = $biz;

            $urlDoc = "products";

            $context = stream_context_create(array(
                'http' => array(
                    'method' => 'POST',
                    'header' => "Authorization: application/json\r\n" . "Content-Type: application/json\r\n",
                    'content' => json_encode($context_data)
                )
            ));

            $url = $this->config->item('api_almacen');

            $response = file_get_contents($url . $urlDoc, false, $context);
            $response = json_decode($response, true);

            $response_api = $response['result'];
        } elseif ($this->input->post('add_product')) {
            $this->session->set_flashdata('error', validation_errors());
            $this->session->set_flashdata('form_data', $_POST);
            redirect("products/add");
        }

        
        if ($this->form_validation->run() == true && isset($response)) {
            if ($response['result'] == "failed") {
                $dataError = [];
                if (is_array($response['message'])) {
                    foreach ($response['message'] as $key => $value) {
                        for ($i = 0; $i < count($response['message'][$key]); $i++) {
                            array_push($dataError, $response['message'][$key][$i]);
                        }
                    }
                } else {
                    array_push($dataError, $response['message']);
                }
                $this->session->set_flashdata('error', str_replace(',', '<br/>', implode(',', $dataError)));
                $this->session->set_flashdata('form_data', $_POST);
                redirect("products/add");
            }
            if ($response['result'] == "ok") {
            $this->session->set_flashdata('message', lang("product_added"));
            redirect("products");
            }
        } else {
            $biz = array(
                "ruc_number"=> (string)($this->session->userdata('ruc'))
            );

            $context_data["business_information"] = $biz;

            $urlDoc = "brands";

            $context = stream_context_create(array(
                'http' => array(
                    'method' => 'GET',
                    'header' => "Authorization: application/json\r\n" .
                    "Content-Type: application/json\r\n",
                    'content' => json_encode($context_data)
                )
            ));

            $url = $this->config->item('api_almacen');
            $response = file_get_contents($url . $urlDoc, false, $context);
            $res = json_decode($response, true);
            $brands = $res['data']['list'];
            

            $urlDoc = "unitmeasure";

            $context = stream_context_create(array(
                'http' => array(
                    'method' => 'GET',
                    'header' => "Authorization: application/json\r\n" .
                    "Content-Type: application/json\r\n",
                    'content' => json_encode($context_data)
                )
            ));

            $url = $this->config->item('api_almacen');
            $response = file_get_contents($url . $urlDoc, false, $context);
            $res = json_decode($response, true);
            $unit_measure = $res['data']['list'];

            $urlCategories = "categories";

            $context = stream_context_create(array(
                'http' => array(
                    'method' => 'GET',
                    'header' => "Authorization: application/json\r\n" . 
                    "Content-Type: application/json\r\n",
                    'content' => json_encode($context_data)
                )
            ));

            $url = $this->config->item('api_almacen');
            $response = file_get_contents($url . $urlCategories, false, $context);
            $res = json_decode($response, true);
            $categories = $res['data']['list'];

            $urlMakers = "makers";

            $context = stream_context_create(array(
                'http' => array(
                    'method' => 'GET',
                    'header' => "Authorization: application/json\r\n" . 
                    "Content-Type: application/json\r\n",
                    'content' => json_encode($context_data)
                )
            ));

            $url = $this->config->item('api_almacen');
            $response = file_get_contents($url . $urlMakers, false, $context);
            $res = json_decode($response, true);
            $makers = $res['data']['list'];

            $this->data['error'] = (validation_errors() ? validation_errors() : $this->session->flashdata('error'));
            $this->data['form_data'] = $this->session->flashdata('form_data');
            $this->session->set_flashdata('form_data','');
            $this->data['categories'] = $categories;
            $this->data['brands'] = $brands;
            $this->data['unit_measure'] = $unit_measure;
            $this->data['makers'] = $makers;
            $this->data['page_title'] = lang('add_product');
            $bc = array(array('link' => site_url('products'), 'page' => lang('products')), array('link' => '#', 'page' => lang('add_product')));
            $meta = array('page_title' => lang('add_product'), 'bc' => $bc);
            $this->page_construct('products/add', $this->data, $meta);
        }
    }

    function edit($id = NULL)
     {

        // if (!$this->Admin) {
        //     $this->session->set_flashdata('error', lang('access_denied'));
        //     redirect('pos');
        // }
        
        
        if ($this->input->get('id')) {
            $id = $this->input->get('id');
        }

        $response_api = "";

        $biz = array(
            "ruc_number"=> (string)($this->session->userdata('ruc'))
        );

        $context_data["business_information"] = $biz;

        $urlDoc = "products/" . $id;

        $context = stream_context_create(array(
            'http' => array(
                'method' => 'GET',
                'header' => "Authorization: application/json\r\n" . "Content-Type: application/json\r\n",
                'content' => json_encode($context_data)
            )
        ));

        $url = $this->config->item('api_almacen');
        $response = file_get_contents($url . $urlDoc, false, $context);
        $res = json_decode($response, true);
        $product = (object) $res['data'];

        if ($this->input->post('code') != $product->code) {
            $this->form_validation->set_rules('code', lang("product_code"), 'is_unique[products.code]');
        }
        $this->form_validation->set_rules('code', lang("product_code"), 'trim|min_length[2]|max_length[50]|required|alpha_numeric');
        $this->form_validation->set_rules('name', lang("product_name"), 'required');
        $this->form_validation->set_rules('short_name', lang("short_name"), 'required');
        $this->form_validation->set_rules('price', lang("product_price"), 'required|is_numeric');
        $this->form_validation->set_rules('cost', lang("product_cost"), 'required|is_numeric');
        // $this->form_validation->set_rules('product_tax', lang("product_tax"), 'required|is_numeric');
        //$this->form_validation->set_rules('quantity', lang("quantity"), 'is_numeric');
        // $this->form_validation->set_rules('alert_quantity', lang("alert_quantity"), 'is_numeric');
        $this->form_validation->set_rules('currency', lang("currency_name"), 'required');

        if ($this->form_validation->run() == true) {
            if ($this->input->post('requires_lot_number') == false) {
                $requires_lot_number = 0;
            } else {
                $requires_lot_number = 1;
            }

            if ($this->input->post('requires_serial_number') == false) {
                $requires_serial_number = 0;
            } else {
                $requires_serial_number = 1;
            }

            $context_data = array(
                'type' => $this->input->post('type'),
                'name' => $this->input->post('name'),
                'code' => $this->input->post('code'),
                'short_name' => $this->input->post('short_name'),
                'requires_lot_number' => $requires_lot_number,
                'requires_serial_number' => $requires_serial_number,
                'category_id' => $this->input->post('category'),
                'maker_id' => $this->input->post('maker'),
                'brand_id' => $this->input->post('brand'),
                'model_id' => $this->input->post('model'),
                'unit_measure_id' => $this->input->post('unit_measure'),
                'barcode_symbology' => $this->input->post('barcode_symbology'),
                'presentation' => $this->input->post('presentation'),
                'alert_quantity' => $this->input->post('alert_quantity'),
                'currency' => $this->input->post('currency'),
                'cost' => $this->input->post('cost'),
                'price' => $this->input->post('price'),
                'tax_method' => $this->input->post('tax_method'),
                'details' => $this->input->post('details'),
                'uActualiza' => $this->session->userdata('user_id'),
                'fActualiza' => date("Y-m-d H:i:s"),
                'tax' => 0,
                // 'tax' => $this->input->post('product_tax'),
                'quantity' => $this->input->post('quantity'),
                'custom_field_1' => $this->input->post('custom_field_1'),
                'custom_field_2' => $this->input->post('custom_field_2'),
            );

            if ($this->input->post('type') == 'combo') {
                $c = sizeof($_POST['combo_item_code']) - 1;
                for ($r = 0; $r <= $c; $r++) {
                    if (isset($_POST['combo_item_code'][$r]) && isset($_POST['combo_item_quantity'][$r])) {
                        $items[] = array(
                            'item_code' => $_POST['combo_item_code'][$r],
                            'quantity' => $_POST['combo_item_quantity'][$r]
                        );
                    }
                }
            } else {
                $items = array();
            }
            if($this->session->userdata('precios_tipos_cliente') == 1) { 

                if(count($_POST['customer_type_id'])>0){
                    $prices=[];
                    $cantidadTiposCliente = sizeof($_POST['customer_type_id']) - 1;
                    for ($index = 0; $index <= $cantidadTiposCliente; $index++) {
                        if (isset($_POST['customer_type_id'][$index]) && isset($_POST['prices'][$index])) {
                            $prices[] = array(
                                'customer_type_id' => $_POST['customer_type_id'][$index],
                                'price' => $_POST['prices'][$index]
                            );
                        }
                    }
                    $pricesData = array(
                        "business_information"=>[
                            "ruc_number"=>$this->session->userdata('ruc'),
                        ],
                        "product_id"=>$id,
                        "created_by" => $this->session->userdata('user_id'),
                        "price"=>$prices,
                    );

                    $curl = curl_init();

                    curl_setopt_array($curl, array(
                    CURLOPT_URL =>$this->config->item('api_almacen').'products/tipo-cliente/precios',
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_ENCODING => '',
                    CURLOPT_MAXREDIRS => 10,
                    CURLOPT_TIMEOUT => 0,
                    CURLOPT_FOLLOWLOCATION => true,
                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST => 'POST',
                    CURLOPT_POSTFIELDS =>json_encode($pricesData),
                    CURLOPT_HTTPHEADER => array(
                        'Content-Type: application/json'
                    ),
                    ));

                    $response = curl_exec($curl);
                    curl_close($curl);
                }
            }

            $context_data['items'] = $items;

            if ($_FILES['userfile']['size'] > 0) {
                $this->load->library('upload');

                $config['upload_path'] = 'uploads/';
                $config['allowed_types'] = 'gif|jpg|png';
                $config['max_size'] = '500';
                $config['max_width'] = '800';
                $config['max_height'] = '800';
                $config['overwrite'] = FALSE;
                $config['encrypt_name'] = TRUE;
                $this->upload->initialize($config);

                if (!$this->upload->do_upload()) {
                    $error = $this->upload->display_errors();
                    $this->session->set_flashdata('error', $error);
                    redirect("products/edit/" . $id);
                }

                $photo = $this->upload->file_name;
                $context_data['image'] = $photo;

                $this->load->library('image_lib');
                $config['image_library'] = 'gd2';
                $config['source_image'] = 'uploads/' . $photo;
                $config['new_image'] = 'uploads/thumbs/' . $photo;
                $config['maintain_ratio'] = TRUE;
                $config['width'] = 110;
                $config['height'] = 110;

                $this->image_lib->clear();
                $this->image_lib->initialize($config);

                if (!$this->image_lib->resize()) {
                    $this->session->set_flashdata('error', $this->image_lib->display_errors());
                    redirect("products/edit/" . $id);
                }
            } else {
                $photo = "box.png";
            }

            $context_data["image"] = $photo;

            $biz = array(
                "ruc_number"=> (string)($this->session->userdata('ruc'))
            );

            $context_data["business_information"] = $biz;

            $url = $this->config->item('api_almacen');
            $urlDoc = "products/" . $id;
            $curl = curl_init();

                curl_setopt_array($curl, array(
                CURLOPT_URL =>$url . $urlDoc,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'PUT',
                CURLOPT_POSTFIELDS =>json_encode($context_data),
                CURLOPT_HTTPHEADER => array(
                    'Content-Type: application/json'
                ),
                ));

                $response = curl_exec($curl);
                curl_close($curl);
                $response = json_decode($response, true);

            $response_api = $response['result'];
        }

        if ($this->form_validation->run() == true && isset($response)) {
            if ($response['result'] == "failed") {
                $dataError = [];
                if (is_array($response['message'])) {
                    foreach ($response['message'] as $key => $value) {
                        for ($i = 0; $i < count($response['message'][$key]); $i++) {
                            array_push($dataError, $response['message'][$key][$i]);
                        }
                    }
                } else {
                    array_push($dataError, $response['message']);
                }
                $this->session->set_flashdata('error', str_replace(',', '<br/>', implode(',', $dataError)));
                $this->session->set_flashdata('form_data', $_POST);
                redirect("products/edit/".$id);
            }
            if ($response['result'] == "ok") {
            $this->session->set_flashdata('message', lang("product_added"));
            redirect("products");
            }
        } else {
            $urlDoc = "brands";

            $context = stream_context_create(array(
                'http' => array(
                    'method' => 'GET',
                    'header' => "Authorization: application/json\r\n" .
                    "Content-Type: application/json\r\n",
                    'content' => json_encode($context_data)
                )
            ));

            $url = $this->config->item('api_almacen');
            $response = file_get_contents($url . $urlDoc, false, $context);
            $res = json_decode($response, true);
            $brands = $res['data']['list'];

            $urlDoc = "unitmeasure";

            $context = stream_context_create(array(
                'http' => array(
                    'method' => 'GET',
                    'header' => "Authorization: application/json\r\n" .
                    "Content-Type: application/json\r\n",
                    'content' => json_encode($context_data)
                )
            ));

            $url = $this->config->item('api_almacen');
            $response = file_get_contents($url . $urlDoc, false, $context);
            $res = json_decode($response, true);
            $unit_measure = $res['data']['list'];

            $urlCategories = "categories";

            $context = stream_context_create(array(
                'http' => array(
                    'method' => 'GET',
                    'header' => "Authorization: application/json\r\n" . 
                    "Content-Type: application/json\r\n",
                    'content' => json_encode($context_data)
                )
            ));

            $url = $this->config->item('api_almacen');
            $response = file_get_contents($url . $urlCategories, false, $context);
            $res = json_decode($response, true);
            $categories = $res['data']['list'];

            $urlMakers = "makers";

            $context = stream_context_create(array(
                'http' => array(
                    'method' => 'GET',
                    'header' => "Authorization: application○/json\r\n" . 
                    "Content-Type: application/json\r\n",
                    'content' => json_encode($context_data)
                )
            ));

            $url = $this->config->item('api_almacen');
            $response = file_get_contents($url . $urlMakers, false, $context);
            $res = json_decode($response, true);
            $makers = $res['data']['list'];
            
            //obtener los precios del producto por tipo de cliente
            if ($this->session->userdata('precios_tipos_cliente') == 1) { 
                $urlDoc = "products/tipo-cliente/precios";

                $context_data['product_id']=$id;
                $context = stream_context_create(array(
                    'http' => array(
                        'method' => 'GET',
                        'header' => "Authorization: application/json\r\n" .
                        "Content-Type: application/json\r\n",
                        'content' => json_encode($context_data)
                    )
                ));

                $url = $this->config->item('api_almacen');
                $response = file_get_contents($url . $urlDoc, false, $context);
                $res = json_decode($response, true);
                $product_prices = $res['data'];
                $this->data['product_prices'] = $product_prices;
            }
            $this->data['error'] = (validation_errors() ? validation_errors() : $this->session->flashdata('error'));

            if($product->type == 'combo') {
                $combo_items = $product->items;

                foreach ($combo_items as $combo_item) {
                    $cpr = $this->site->getProductByCode($combo_item['item_code']);
                    $cpr->qty = $combo_item['quantity'];
                    $items[] = array('id' => $cpr->id, 'row' => $cpr);
                }

                $this->data['items'] = $items;
            }
            $this->data['form_data'] = $this->session->flashdata('form_data');
            $this->session->set_flashdata('form_data','');
            $this->data['product'] = $product;
            $this->data['categories'] = $categories;
            $this->data['brands'] = $brands;
            $this->data['unit_measure'] = $unit_measure;
            $this->data['makers'] = $makers;
            $this->data['page_title'] = lang('edit_product');
            $bc = array(array('link' => site_url('products'), 'page' => lang('products')), array('link' => '#', 'page' => lang('edit_product')));
            $meta = array('page_title' => ( lang('product'). ": ".$product->code), 'bc' => $bc);
            $this->page_construct('products/edit', $this->data, $meta);
        }
    }

    function delete($id = NULL) {
        if(DEMO) {
            $this->session->set_flashdata('error', lang('disabled_in_demo'));
            redirect(isset($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : 'welcome');
        }

        // if (!$this->Admin) {
        //     $this->session->set_flashdata('error', lang('access_denied'));
        //     redirect('pos');
        // }

        if ($this->input->get('id')) {
            $id = $this->input->get('id');
        }

        $biz = array(
            "ruc_number"=> (string)($this->session->userdata('ruc'))
        );

        $context_data["business_information"] = $biz;

        $urlDoc = "products/" . $id;

        $context = stream_context_create(array(
            'http' => array(
                'method' => 'DELETE',
                'header' => "Authorization: application/json\r\n" . "Content-Type: application/json\r\n",
                'content' => json_encode($context_data)
            )
        ));

        $url = $this->config->item('api_almacen');
        $response = file_get_contents($url . $urlDoc, false, $context);
        $res = json_decode($response, true);
        $product = (object) $res['data'];

        if ($this->products_model->deleteProduct($id)) {
            $this->session->set_flashdata('message', lang("product_deleted"));

            $dataP = array(
                'uActualiza' => $this->session->userdata('user_id'),
                'fActualiza' => date("Y-m-d H:i:s")
            );

            $this->products_model->updateProduct($id, $dataP);

            redirect('products');
        }

    }

    function import() {
        // if (!$this->Admin) {
        //     $this->session->set_flashdata('error', lang('access_denied'));
        //     redirect('pos');
        // }
        $this->load->helper('security');
        $this->form_validation->set_rules('userfile', lang("upload_file"), 'xss_clean');

        if ($this->form_validation->run() == true) {
            if (DEMO) {
                $this->session->set_flashdata('warning', lang("disabled_in_demo"));
                redirect('pos');
            }

            if (isset($_FILES["userfile"])) {

                $this->load->library('upload');

                $config['upload_path'] = 'uploads/';
                $config['allowed_types'] = 'csv';
                $config['max_size'] = '500';
                $config['overwrite'] = TRUE;

                $this->upload->initialize($config);

                if (!$this->upload->do_upload()) {
                    $error = $this->upload->display_errors();
                    $this->session->set_flashdata('error', $error);
                    redirect("products/import");
                }


                $csv = $this->upload->file_name;

                $arrResult = array();
                $handle = fopen("uploads/" . $csv, "r");
                if ($handle) {
                    while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
                        $arrResult[] = $row;
                    }
                    fclose($handle);
                }
                array_shift($arrResult);

                switch($this->session->userdata('negocio')){
                    case 0:
                        $keys = array('code', 'name', 'cost', 'price', 'category', 'maker', 'presentation');
                        break;
                    case 1:
                        $keys = array('code', 'name', 'cost', 'price', 'category', 'maker', 'custom_field_1', 'custom_field_2', 'presentation');
                        break;
                }

                $final = array();
                foreach ($arrResult as $key => $value) {
                    $final[] = array_combine($keys, $value);
                }

                if (sizeof($final) > 1001) {
                    $this->session->set_flashdata('error', lang("more_than_allowed"));
                    redirect("products/import");
                }

                $fila = 0;

                foreach ($final as $csv_pr) {

                    $fila = $fila + 1;

                    if ($this->products_model->getProductByCode($csv_pr['code'])) {
                        $this->session->set_flashdata('error', lang("check_product_code") . " (" . $csv_pr['code'] . "). " . lang("code_already_exist"));
                        redirect("products/import");
                    }
                    // if (!is_numeric($csv_pr['tax'])) {
                    //     $this->session->set_flashdata('error', lang("check_product_tax") . " (" . $csv_pr['tax'] . "). " . lang("tax_not_numeric"));
                    //     redirect("products/import");
                    // }
                    if(! ($category = $this->site->getCategoryByCode($csv_pr['category']))) {
                        $this->session->set_flashdata('error', lang("check_category") . " (" . $csv_pr['category'] . "). " . lang("category_x_exist"). " (Fila: " . $fila . ")");
                        redirect("products/import");
                    }
                    if (!is_numeric($csv_pr['price'])) {
                        $this->session->set_flashdata('error', lang("check_product_price") . " (" . $csv_pr['price'] . "). " . lang("price_not_numeric"));
                        redirect("products/import");
                    }

                    switch($this->session->userdata('negocio')){
                        case 0:

                            if(!empty($csv_pr['maker']))
                            {
                                if(! ($maker = $this->site->getMakerByName(utf8_encode($csv_pr['maker'])))) {
                                    $this->session->set_flashdata('error', $csv_pr['maker']. '. ' . lang("maker") . ' no encontrado'. " (Fila: " . $fila . ")");
                                    redirect("products/import");
                                    // $csv_pr['laboratory'] = '';
                                }
                            }

                            $data[] = array(
                                'type' => 'standard',
                                'code' => $csv_pr['code'],
                                'name' => utf8_encode($csv_pr['name']),
                                'cost' => !empty($csv_pr['cost']) ? $csv_pr['cost'] : NULL,//$cost,//$csv_pr['cost'],
                                // 'tax' => $csv_pr['tax'],
                                'tax_method' => '0',
                                'price' => $csv_pr['price'],
                                'category_id' => $category->id,
                                'maker_id' => !empty($csv_pr['maker']) ? $maker->id : NULL,//$laboratory,//$csv_pr['laboratory_id']
                                'presentation' => !empty($csv_pr['presentation']) ? utf8_encode($csv_pr['presentation']) : NULL,
                                'uCrea' => $this->session->userdata('user_id'),
                                'fCrea' => date("Y-m-d H:i:s"),
                                'estado' => 1
                            );
                            break;

                        case 1:

                            if(!empty($csv_pr['maker']))
                            {
                                if(! ($maker = $this->site->getMakerByName(utf8_encode($csv_pr['maker'])))) {
                                    $this->session->set_flashdata('error', $csv_pr['maker']. '. ' . lang("laboratory") . ' no encontrado'. " (Fila: " . $fila . ")");
                                    redirect("products/import");
                                    // $csv_pr['laboratory'] = '';
                                }
                            }

                            $data[] = array(
                                'type' => 'standard',
                                'code' => $csv_pr['code'],
                                'name' => utf8_encode($csv_pr['name']),
                                'cost' => !empty($csv_pr['cost']) ? $csv_pr['cost'] : NULL,//$cost,//$csv_pr['cost'],
                                // 'tax' => $csv_pr['tax'],
                                'tax_method' => '0',
                                'price' => $csv_pr['price'],
                                'category_id' => $category->id,
                                'maker_id' => !empty($csv_pr['maker']) ? $maker->id : NULL,//$laboratory,//$csv_pr['laboratory_id']
                                'custom_field_1' => !empty($csv_pr['custom_field_1']) ? utf8_encode($csv_pr['custom_field_1']) : NULL,
                                'custom_field_2' => !empty($csv_pr['custom_field_2']) ? utf8_encode($csv_pr['custom_field_2']) : NULL,
                                'presentation' => !empty($csv_pr['presentation']) ? utf8_encode($csv_pr['presentation']) : NULL,
                                'uCrea' => $this->session->userdata('user_id'),
                                'fCrea' => date("Y-m-d H:i:s"),
                                'estado' => 1
                            );
                            break;
                    }
                }
                //print_r($data); die();
            }
        }

        if ($this->form_validation->run() == true && $this->products_model->add_products($data)) {

            $this->session->set_flashdata('message', lang("products_added"));
            redirect('products');

        } else {

            $this->data['error'] = (validation_errors() ? validation_errors() : $this->session->flashdata('error'));
            $this->data['categories'] = $this->site->getAllCategories();
            $this->data['page_title'] = lang('import_products');
            $bc = array(array('link' => site_url('products'), 'page' => lang('products')), array('link' => '#', 'page' => lang('import_products')));
            $meta = array('page_title' => lang('import_products'), 'bc' => $bc);
            $this->page_construct('products/import', $this->data, $meta);

        }
    }

    function suggestions() {
         $term = $this->input->get('term', TRUE);

         $rows = $this->products_model->getProductNames($term);
         if ($rows) {
             foreach ($rows as $row) {
                 $row->qty = 1;
                 $pr[] = array('id' => str_replace(".", "", microtime(true)), 'item_id' => $row->id, 'label' => $row->name . " (" . $row->code . ")", 'row' => $row);
             }
             echo json_encode($pr);
         } else {
             echo json_encode(array(array('id' => 0, 'label' => lang('no_match_found'), 'value' => $term)));
         }
     }

    function movements() {
        $data['error'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('error');
        $this->data['page_title'] = lang('movements_search');
        $this->data['warehouses'] = $this->site->getAllWarehouses();
        $this->data['motivos'] = $this->site->getAllmotives();

        $bc = array(array('link' => '#', 'page' => lang('products')));
        $meta = array('page_title' => lang('products') . " - " . lang('movements_search'), 'bc' => $bc);
        $this->page_construct('products/movements', $this->data, $meta);
    }

    function get_movements(){//$idAlmacen, $producto, $idMotivo) {
        $this->load->library('datatables');
        $this->datatables->select(
            //$this->db->dbprefix('product_mov').".id as pid,
            $this->db->dbprefix('product_mov').".fCrea,
            ".$this->db->dbprefix('warehouses').".warehouse as warehouse_name,
            ".$this->db->dbprefix('products').".name as product_name,
            ".$this->db->dbprefix('product_mov').".cant as quantity,
            tipo,
            ".$this->db->dbprefix('mov_motive').".motive as motivo,
            ref,
            user1.username as user1");
        $this->datatables->from('tec_product_mov');
        $this->datatables->join('tec_products', 'tec_products.id=tec_product_mov.product_id' , 'left');
        $this->datatables->join('tec_warehouses', 'tec_warehouses.id=tec_product_mov.warehouse_id' , 'left');
        $this->datatables->join('tec_mov_motive', 'tec_mov_motive.id=tec_product_mov.idMotivo' , 'left');

        $this->datatables->join('tec_users as user1', 'user1.id=tec_product_mov.uCrea' , 'left');
        $this->datatables->join('tec_users as user2', 'user2.id=tec_product_mov.uActualiza' , 'left');

        $this->datatables->where('products.estado !=',0);

        $idAlmacen =  $this->input->post('idAlmacen');
        $producto =  $this->input->post('producto') ;
        $idMotivo =  $this->input->post('idMotivo') ;

        if($idAlmacen!=0) {
            $this->datatables->where('tec_product_mov.warehouse_id',$idAlmacen );
        }


        if( trim($producto) !="") {
            $this->datatables->where("tec_products.name like '%".$producto."%'");
        }


        if($idMotivo!=0) {
            $this->datatables->where('tec_product_mov.idMotivo',$idMotivo );
        }

        echo $this->datatables->generate();

    }
    function get_all(){
        $biz = array(
            "ruc_number"=> (string)($this->session->userdata('ruc'))
        );

        $context_data["business_information"] = $biz;
        $context = stream_context_create(array(
            'http' => array(
                'method' => 'GET',
                'header' => "Authorization: application/json\r\n" . "Content-Type: application/json\r\n",
                'content' => json_encode($context_data)
            )
        ));

        //Consultas api almacen
        $url = $this->config->item('api_almacen');

        $urlproducts="products/";
        $response = file_get_contents($url . $urlproducts, false, $context);
        $products = json_decode($response, true);
        if($products['result']=='ok'){
            $products=$products['data'];
        }else{
            $products=[];
        }
        echo json_encode($products);
    }

    function get_product($id = null){

        $biz = array(
            "ruc_number"=> (string)($this->session->userdata('ruc'))
        );

        $context_data["business_information"] = $biz;
        $context = stream_context_create(array(
            'http' => array(
                'method' => 'GET',
                'header' => "Authorization: application/json\r\n" . "Content-Type: application/json\r\n",
                'content' => json_encode($context_data)
            )
        ));

        //Consultas api almacen
        $url = $this->config->item('api_almacen');

        $urlproducts="products/".$id;
        $response = file_get_contents($url . $urlproducts, false, $context);
        $product = json_decode($response, true);
        if($product['result']=='ok'){
            $product=$product['data'];
        }else{
            $product=[];
        }
        echo json_encode($product);
        // $product = $this->site->getProductByID($id);
        // echo json_encode($product);
    }


    function get_models($brand_id = NULL) {
        $biz = array(
            "ruc_number"=> (string)($this->session->userdata('ruc'))
        );

        $context_data["business_information"] = $biz;

        $urlDoc = "models/brand/".$brand_id;

        $context = stream_context_create(array(
            'http' => array(
                'method' => 'GET',
                'header' => "Authorization: application/json\r\n" .
                "Content-Type: application/json\r\n",
                'content' => json_encode($context_data)
            )
        ));

        $url = $this->config->item('api_almacen');
        $response = file_get_contents($url . $urlDoc, false, $context);
        $res = json_decode($response, true);
        $models = $res['data'];

        echo json_encode($models);
    }
    function getProducPrice(){
        $customers_type_id = $this->input->get('customers_type_id')?$this->input->get('customers_type_id'):null;
        $product_id = $this->input->get('product_id');
        $biz = array(
            "ruc_number"=> (string)($this->session->userdata('ruc'))
        );
        $url = 'products/tipo-cliente/precios/'.$product_id."/";
        if($customers_type_id != null && $customers_type_id != 0 && $customers_type_id != ""){
            $url .= $customers_type_id;
        }
        $context_data["business_information"] = $biz;
        $curl = curl_init();
        curl_setopt_array($curl, array(
        CURLOPT_URL => $this->config->item('api_almacen').$url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'GET',
        CURLOPT_POSTFIELDS =>json_encode($context_data),
        CURLOPT_HTTPHEADER => array(
            'Content-Type: application/json'
        ),
        ));

        $response = curl_exec($curl);
        curl_close($curl);
        echo $response;
    }
}
