<?php

class Producto extends CI_Controller
{

  public function __construct()
  {
    $this->folder = 'files/';
    parent::__construct();
    $this->load->model(modelo(), 'Controlador_model');
    $this->controlador = controlador();
    $this->titulo_controlador = humanize($this->controlador);
    $this->url = base_url() . $this->controlador;
    $this->vista = $this->controlador;
    $this->perfil = $this->session->userdata('perfil') ? $this->session->userdata('perfil') : FALSE;
    $this->empresa = $this->session->userdata('empresa') ? $this->session->userdata('empresa') : FALSE;
    $this->usuario = $this->session->userdata('usuario') ? $this->session->userdata('usuario') : FALSE;
  }

  public function index()
  {
    $data = array(
      'titulo' => $this->titulo_controlador,
      'contenido' => $this->vista,
      'categories' => ($this->perfil == 1 || $this->perfil == 2) 
                      ? $this->db->where('id !=', 14)->get('productocategoria')->result()
                      : $this->db->where('id !=', 14)->where('empresa', $this->empresa)->get('productocategoria')->result(),
      'empresas' => $this->Controlador_model->getAll('empresa'),
      'breads' => array(array('ruta' => 'javascript:;', 'titulo' => $this->titulo_controlador))
    );
    $this->load->view(THEME . TEMPLATE, $data);
  }

  public function ajax_list()
  {
    $draw = intval($this->input->get("draw"));
    $start = intval($this->input->get("start"));
    $length = intval($this->input->get("length"));
    if ($this->perfil == 1 || $this->perfil == 2) {
      $this->db->order_by('id', 'desc');
    } else {
      $this->db->where('empresa', $this->empresa)->order_by('id', 'desc');
    }

    $this->db->where('categoria !=', 14);

    if ($this->input->post('idcategoria')) {
      $this->db->where('categoria', $this->input->post('idcategoria'));
    }

    $query = $this->db->get($this->controlador)->result();
    $data = [];
    $estado['0'] = '<span class="badge badge-success">ACTIVADO</span>';
    $estado['1'] = '<span class="badge badge-danger">DESACTIVADO</span>';
    foreach ($query as $key => $value) {
      if ($value->tipo == 1) {
        $stockdisponible = "<span class='badge badge-warning'>SERVICIO</span>";
      } else {
        $stockdisponible =  "<span class='badge badge-secondary'>" . number_format($this->totalStock($value->id), 2) . "</span>";
      }

      $categoria = $this->Controlador_model->get($value->categoria, 'productocategoria');
      
      $boton = '';
      $boton .= '<a class="btn btn-sm btn-default" title="Detalle" onclick="detalle(' . $value->id . ')"><i class="fas fa-info-circle"></i></a> ';
      
      if ($value->variante == 1) {
        $boton .= '<a class="btn btn-sm btn-info" title="Variantes" onclick="variante(' . $value->id . ')"><i class="fas fa-th-list"></i></a> ';
      }

      if ($this->perfil == 1 || $this->perfil == 2) {
        $boton .= '<a class="btn btn-sm btn-primary" title="Modificar" onclick="edit(' . $value->id . ')"><i class="fas fa-edit"></i></a> ';
        
        if ($value->tipo == 2) {
          $boton .= '<a class="btn btn-sm btn-success" title="Combos" onclick="combo(' . $value->id . ')"><i class="fas fa-layer-group"></i></a> ';
        }
        
        if ($value->tipo == 0) {
          $boton .= '<a class="btn btn-sm btn-info" title="Control Stock" onclick="stock(' . $value->id . ')"><i class="fas fa-boxes"></i></a> ';
        }
        
        $boton .= '<a class="btn btn-sm btn-danger" title="Borrar" onclick="borrar(' . $value->id . ')"><i class="fas fa-trash"></i></a> ';
      }

      if ($value->estado == '0') {
        $sw_estado = '
        <div class="custom-control custom-switch" title="Activo - Clic para Desactivar">
          <input type="checkbox" class="custom-control-input" id="sw-prod-' . $value->id . '" checked onclick="desactivar(' . $value->id . ')">
          <label class="custom-control-label" for="sw-prod-' . $value->id . '"></label>
        </div>';
      } else {
        $sw_estado = '
        <div class="custom-control custom-switch" title="Inactivo - Clic para Activar">
          <input type="checkbox" class="custom-control-input" id="sw-prod-' . $value->id . '" onclick="activar(' . $value->id . ')">
          <label class="custom-control-label" for="sw-prod-' . $value->id . '"></label>
        </div>';
      }

        $data[] = array(
          $key + 1,
          '<span class="text-muted">' . $value->codigo . '</span>',
          '<strong>' . $value->nombre . '</strong>',
          $categoria ? '<span class="badge badge-light border">' . $categoria->nombre . '</span>' : '',
          '<div style="text-align:center">' . $stockdisponible . '</div>',
          '<div style="text-align:right"><strong>S/ ' . number_format($value->precioventa, 2) . '</strong></div>',
          $sw_estado,
          $boton
        );
    }
    $result = array(
      "draw" => $draw,
      "recordsTotal" => count($query),
      "recordsFiltered" => count($query),
      "data" => $data
    );
    //output to json format
    echo json_encode($result);
  }

  public function totalStock($idproducto)
  {
    //? contamos para cuantas selecciones de ese producto le resta
    $queryproducto = $this->Controlador_model->get($idproducto, "producto");
    $cantidadRestante = [];

    if ($queryproducto->tipo == '0') {
      //todo: El tipo de producto 0 es estandar//->where("em-presa", $this->em-presa)
      $existenciaStock = $this->db->where('producto',  $queryproducto->id)->get('stock')->row(); //todo: verificamos si el producto esta registra en stock
      if ($existenciaStock) {
        $stok_D = $this->db->where('producto', $queryproducto->id)->get('stock')->row();
        $cantidadRestante[] = $stok_D->cantidad;
      } else {
        $cantidadRestante[] = 0;
      }
    } else if ($queryproducto->tipo == '2') {

      //todo: El tipo de producto 2 es combo
      $combo = $this->db->where('producto',  $queryproducto->id)->get('combo')->result(); //todo: verificamos si el tiene registro en la tabal combo
      if ($combo) {

        foreach ($combo as $key => $value2) {

          $existenciaStockCombo = $this->db->where('producto',  $value2->item_id)->get('stock')->row(); //todo: verificamos si el producto esta registra en stock

          if ($existenciaStockCombo) {

            $verificarCantidad = $this->db->where('producto',  $value2->item_id)->where('cantidad >=', $value2->cantidad)->get('stock')->row();

            if ($verificarCantidad) {
              $cantidadTotalStock =  $verificarCantidad->cantidad;
              $cantidadCombo = $value2->cantidad;
              $totalSelecciones = ($cantidadTotalStock /  $cantidadCombo);
              $cantidadRestante[] = $totalSelecciones;
            } else {
              $cantidadRestante[] = 0;
              break;
            }
          } else {
            $cantidadRestante[] = 0;
          }
        }
      } else {
        $cantidadRestante[] = 0;
      }
    } else {
      $cantidadRestante[] = "Servicio";
    }

    return min($cantidadRestante);
  }


  private function _validate()
  {
    $data = array();
    $data['error_string'] = array();
    $data['inputerror'] = array();
    $data['status'] = TRUE;
    $producto = $this->Controlador_model->check($this->input->post('id'), $this->input->post('nombre'));

    if ($producto) {
      if ($this->input->post('id') == '') {
        $data['inputerror'][] = 'nombre';
        $data['error_string'][] = 'Este nombre ya se encuentra registrado.';
        $data['status'] = FALSE;
      }
    }

    if ($this->input->post('nombre') == '') {
      $data['inputerror'][] = 'nombre';
      $data['error_string'][] = 'Este campo es obligatorio.';
      $data['status'] = FALSE;
    }

    if ($this->input->post('precioventa') == '') {
      $data['inputerror'][] = 'precioventa';
      $data['error_string'][] = 'Este campo es obligatorio.';
      $data['status'] = FALSE;
    }

    if ($this->input->post('tipo') == '0') {
      if ($this->input->post('categoria') == '') {
        $data['inputerror'][] = 'categoria';
        $data['error_string'][] = 'Este campo es obligatorio.';
        $data['status'] = FALSE;
      }

      if ($this->input->post('preciocompra') == '') {
        $data['inputerror'][] = 'preciocompra';
        $data['error_string'][] = 'Este campo es obligatorio.';
        $data['status'] = FALSE;
      }

      if ($this->input->post('unidad') == '') {
        $data['inputerror'][] = 'unidad';
        $data['error_string'][] = 'Este campo es obligatorio.';
        $data['status'] = FALSE;
      }

      if ($this->input->post('alertqt') == '') {
        $data['inputerror'][] = 'alertqt';
        $data['error_string'][] = 'Este campo es obligatorio.';
        $data['status'] = FALSE;
      }
    }

    if ($data['status'] === FALSE) {
      echo json_encode($data);
      exit();
    }
  }

  public function ajax_add()
  {
    $variante = 0;
    if (!is_null($this->input->post('chkVariante'))) {
      $variante = $this->input->post('chkVariante');
    }
    $this->_validate();
    $config['upload_path'] = './files/products/';
    $config['encrypt_name'] = TRUE;
    $config['allowed_types'] = 'gif|jpg|jpeg|png';
    $config['max_width'] = '10000';
    $config['max_height'] = '10000';
    $this->load->library('upload', $config);
    $this->upload->initialize($config);
    $this->load->library('image_lib');
    if ($this->upload->do_upload('foto')) {
      $datas = array('upload_data' => $this->upload->data());
      $config2['image_library'] = 'gd2';
      $config2['source_image'] = $datas['upload_data']['full_path'];
      $config2['create_thumb'] = TRUE;
      $config2['maintain_ratio'] = TRUE;
      $config2['width'] = 120;
      $config2['height'] = 120;
      $this->image_lib->clear();
      $this->image_lib->initialize($config2);
      $this->image_lib->resize();
      $image = $datas['upload_data']['file_name'];
      $image_thumb = $datas['upload_data']['raw_name'] . '_thumb' . $datas['upload_data']['file_ext'];
      $data['photo'] = $image;
      $data['photothumb'] = $image_thumb;
    }
    $data['empresa'] = $this->empresa; //$this->perfil == 1 || $this->perfil == 2 ? $this->input->post('empresa') : $this->empresa;
    $data['tipo'] = $this->input->post('tipo');
    $data['codigo'] = $this->input->post('codigo');
    $data['codigoBarra'] = $this->input->post('codigoBarra');
    $data['numero'] = $this->input->post('numero');
    $data['nombre'] = $this->input->post('nombre');
    $data['variante'] = $variante;
    $data['categoria'] = $this->input->post('categoria');
    $data['descripcion'] = $this->input->post('descripcion');
    $data['options'] = $this->input->post('options');
    $data['preciocompra'] = $this->input->post('preciocompra');
    $data['precioventa'] = $this->input->post('precioventa');
    $data['color'] = $this->input->post('color');
    $data['alertqt'] = $this->input->post('alertqt');
    $data['unidad'] = $this->input->post('unidad');
    if ($this->Controlador_model->save($this->controlador, $data)) {
      echo json_encode(array("status" => TRUE));
    }
  }

  public function ajax_edit($id)
  {
    $data = $this->Controlador_model->get($id, $this->controlador);
    echo json_encode($data);
  }

  public function ajax_detalle($id)
  {
    $datas = $this->Controlador_model->get($id, $this->controlador);
    $categorias = $this->Controlador_model->get($datas->categoria, 'productocategoria');
    
    // Obtener opciones de la categoria
    $cat_options = $this->db->where('categoria', $datas->categoria)->get('productocategoriaopcion')->result();
    $options_arr = [];
    foreach($cat_options as $opt) {
        $options_arr[] = $opt->nombre;
    }
    $options_str = implode(', ', $options_arr);

    $mostrar = ($datas->tipo == 1) ? 'SERVICIO' : number_format($this->totalStock($id), 2);
    $tipo['0'] = 'ESTANDAR';
    $tipo['1'] = 'SERVICIO';
    $tipo['2'] = 'COMBINACION';
    $data = array(
      'tipo' => $tipo[$datas->tipo],
      'codigo' => $datas->codigo,
      'nombre' => $datas->nombre,
      'alertqt' => $datas->alertqt,
      'costo' => $datas->preciocompra,
      'precio' => $datas->precioventa,
      'descripcion' => $datas->descripcion,
      'unidad' => $datas->unidad,
      'photo' => $datas->photo,
      'categoria' => $categorias ? $categorias->nombre : '',
      'options' => $options_str,
      'stock' => $mostrar
    );
    echo json_encode($data);
  }

  public function ajax_update()
  {
    $variante = 0;
    if (!is_null($this->input->post('chkVariante'))) {
      $variante = $this->input->post('chkVariante');
    }
    $this->_validate();
    $config['upload_path'] = './files/products/';
    $config['encrypt_name'] = TRUE;
    $config['allowed_types'] = 'gif|jpg|jpeg|png';
    $config['max_width'] = '10000';
    $config['max_height'] = '10000';
    $this->load->library('upload', $config);
    $this->upload->initialize($config);
    $this->load->library('image_lib');
    if ($this->upload->do_upload('foto')) {
      $datas = array('upload_data' => $this->upload->data());
      $config2['image_library'] = 'gd2';
      $config2['source_image'] = $datas['upload_data']['full_path'];
      $config2['create_thumb'] = TRUE;
      $config2['maintain_ratio'] = TRUE;
      $config2['width'] = 120;
      $config2['height'] = 120;
      $this->image_lib->clear();
      $this->image_lib->initialize($config2);
      $this->image_lib->resize();
      $image = $datas['upload_data']['file_name'];
      $image_thumb = $datas['upload_data']['raw_name'] . '_thumb' . $datas['upload_data']['file_ext'];
      $data['photo'] = $image;
      $data['photothumb'] = $image_thumb;
    }
    $data['empresa'] = $this->empresa; //$this->perfil == 1 || $this->perfil == 2 ? $this->empresa : $this->input->post('empresa');
    $data['tipo'] = $this->input->post('tipo');
    $data['codigo'] = $this->input->post('codigo');
    $data['codigoBarra'] = $this->input->post('codigoBarra');
    $data['numero'] = $this->input->post('numero');
    $data['nombre'] = $this->input->post('nombre');
    $data['variante'] = $variante;
    $data['categoria'] = $this->input->post('categoria');
    $data['descripcion'] = $this->input->post('descripcion');
    $data['options'] = $this->input->post('options');
    $data['preciocompra'] = $this->input->post('preciocompra');
    $data['precioventa'] = $this->input->post('precioventa');
    $data['preciodistribuidor'] = $this->input->post('preciodistribuidor');
    $data['preciomayorista'] = $this->input->post('preciomayorista');
    $data['precioespecial'] = $this->input->post('precioespecial');
    $data['color'] = $this->input->post('color');
    $data['alertqt'] = $this->input->post('alertqt');
    $data['unidad'] = $this->input->post('unidad');
    $this->Controlador_model->update(array('id' => $this->input->post('id')), $data, $this->controlador);
    echo json_encode(array("status" => TRUE));
  }

  public function ajax_delete($id)
  {
    if ($this->Controlador_model->delete_by_id($id, $this->controlador)) {
      echo json_encode(array("status" => TRUE));
    }
  }

  public function codigo()
  {
    if ($this->input->is_ajax_request()) {
      $tipo = $this->input->post('tipo');
      $categoria = $this->input->post('categoria');
      $numero = $this->Controlador_model->codigos($tipo, $categoria);
      $numeros = $numero ? $numero->numero + 1 : 1;
      $cadena = "";
      for ($i = 0; $i < 3 - strlen($numeros); $i++) {
        $cadena = $cadena . '0';
      }
      $categorias = $this->Controlador_model->get($categoria, 'productocategoria');
      $codigo1 = $categorias ? $categorias->id : '00';
      $codigo = substr($categorias->nombre, 0, 1) . $tipo . $codigo1 . $cadena . $numeros;
      $output = array("codigo" => $codigo, "numero" => $numeros);
      $this->output->set_content_type('application/json')->set_output(json_encode($output));
    } else {
      show_404();
    }
  }

  public function ajax_list_combo($id)
  {
    $draw = intval($this->input->get("draw"));
    $start = intval($this->input->get("start"));
    $length = intval($this->input->get("length"));
    $query = $this->db->order_by('id', 'desc')->where('producto', $id)->get('combo');
    $data = [];
    $no = 0;
    foreach ($query->result() as $value) {
      $producto = $this->Controlador_model->get($value->item_id, 'producto');
      $categoria = $this->Controlador_model->get($producto->categoria, 'productocategoria');
      $no++;
      //add variables for action
      $boton1 = '';
      //add html for action
      $boton1 = '<a class="btn btn-sm btn-danger" title="Borrar" onclick="borrarcombo(' . $value->id . ')"><i class="fas fa-trash-alt"></i></a>';
      $data[] = array(
        $no,
        $producto->codigo,
        $producto->nombre,
        $categoria ? $categoria->nombre : '',
        $value->cantidad,
        $boton1
      );
    }
    $result = array(
      "draw" => $draw,
      "recordsTotal" => $query->num_rows(),
      "recordsFiltered" => $query->num_rows(),
      "data" => $data
    );
    //output to json format
    echo json_encode($result);
  }

  public function autocompletar()
  {
    if (isset($_GET['term'])) {
      $q = strtoupper($_GET['term']);
      $this->Controlador_model->autocompletar($q);
    }
  }

  private function _validatecombo()
  {
    $data = array();
    $data['error_string'] = array();
    $data['inputerror'] = array();
    $data['status'] = TRUE;
    $combolist = $this->Controlador_model->getDup($this->input->post('combo'), $this->input->post('producto'));

    if ($this->input->post('producto') == '') {
      $data['inputerror'][] = 'producto';
      $data['error_string'][] = 'Este campo es obligatorio.';
      $data['status'] = FALSE;
    }

    if ($this->input->post('cantidad') == '') {
      $data['inputerror'][] = 'cantidad';
      $data['error_string'][] = 'Este campo es obligatorio.';
      $data['status'] = FALSE;
    }

    if ($combolist) {
      $data['inputerror'][] = 'producto';
      $data['error_string'][] = 'Este campo ya existe en la base de datos.';
      $data['status'] = FALSE;
    }

    if ($data['status'] === FALSE) {
      echo json_encode($data);
      exit();
    }
  }

  public function ajax_addcombo()
  {
    $this->_validatecombo();
    $data = array(
      'producto' => $this->input->post('combo'),
      'item_id' => $this->input->post('producto'),
      'cantidad' => $this->input->post('cantidad'),
    );
    $insert = $this->Controlador_model->save('combo', $data);
    echo json_encode(array("status" => TRUE));
  }

  public function ajax_deletecombo($id)
  {
    if ($this->Controlador_model->delete_by_id($id, 'combo')) {
      echo json_encode(array("status" => TRUE));
    }
  }

  public function ajax_desactivar($id)
  {
    $this->Controlador_model->desactivar_by_id($id, $this->controlador);
    echo json_encode(array("status" => TRUE));
  }

  public function ajax_activar($id)
  {
    $this->Controlador_model->activar_by_id($id, $this->controlador);
    echo json_encode(array("status" => TRUE));
  }

  public function delete($id)
  {
    $product = $this->Controlador_model->get($id, 'producto');
    if ($product->photo !== '') {
      unlink('./files/products/' . $product->photo);
      unlink('./files/products/' . $product->photothumb);
    }
    $this->Controlador_model->delete($id, $this->controlador);
    redirect($this->url);
  }

  public function downloads($name)
  {
    $data = file_get_contents($this->folder . $name);
    force_download($name, $data);
  }

  function insertar()
  {
    $tipoproducto['ESTANDAR'] = '0';
    $tipoproducto['SERVICIO'] = '1';
    $tipoproducto['COMBINACION'] = '2';
    $tipo = $this->input->post('tipo');
    $categoria = $this->input->post('categoria');
    $categorias = $this->db->where('nombre', $categoria)->get('productocategoria')->row();
    if ($categorias) {
      $codigocategoria = $categorias->codigo;
      $nombrecategoria = $categorias->nombre;
    } else {
      $numero = $this->Controlador_model->codigocategoria();
      $numeros = $numero ? $numero->numero + 1 : 1;
      $cadena = "";
      for ($i = 0; $i < 2 - strlen($numeros); $i++) {
        $cadena = $cadena . '0';
      }
      $codigocategoria = $cadena . $numeros;
      $nombrecategoria = $categoria;
      $datacategoria['empresa'] = $this->empresa;
      $datacategoria['nombre'] = $categoria;
      $datacategoria['codigo'] = $cadena . $numeros;
      $datacategoria['numero'] = $numeros;
      $insert = $this->Controlador_model->save('productocategoria', $datacategoria);
    }
    $numeronew = $this->Controlador_model->codigos($tipoproducto[$tipo], $categoria);
    $numerosnew = $numeronew ? $numeronew->numero + 1 : 1;
    $cadenanew = "";
    for ($i = 0; $i < 3 - strlen($numerosnew); $i++) {
      $cadenanew = $cadenanew . '0';
    }
    $data['empresa'] = $this->empresa;
    $data['categoria'] = $categorias ? $categorias->id : $insert;
    $data['tipo'] = $tipoproducto[$tipo];
    $data['codigo'] = substr($nombrecategoria, 0, 1) . $tipoproducto[$tipo] . $codigocategoria . $cadenanew . $numerosnew;
    $data['numero'] = $numerosnew;
    $data['nombre'] = $this->input->post('nombre');
    $data['preciocompra'] = $this->input->post('costo');
    $data['precioventa'] = $this->input->post('precio');
    $data['unidad'] = $this->input->post('unidad');
    $data['color'] = 'color01';
    $this->Controlador_model->save('producto', $data);
  }

  public function reporte()
  {
    $date = date("Y-m-d");
    $year = date("Y");
    $mes = date("m");
    // $VentaDiario = 0;
    // $TodaySales = $this->Controlador_model->getAll('venta');
    // foreach ($TodaySales as $TodaySale) {
    //   if ($TodaySale->created == $date) {
    //     $VentaDiario += $TodaySale->montototal;
    //   }   
    // }
    $TodaySales = $this->db->query("select sum(montototal) AS sum FROM venta where created = '$date'")->row();
    $Top5product = $this->Controlador_model->productoTop($mes);
    $monthlySales = $this->db->query("SELECT SUM(IF(MONTH = 1, numRecords, 0)) AS 'january', SUM(IF(MONTH = 2, numRecords, 0)) AS 'feburary',SUM(IF(MONTH = 3, numRecords, 0)) AS 'march',SUM(IF(MONTH = 4, numRecords, 0)) AS 'april',SUM(IF(MONTH = 5, numRecords, 0)) AS 'may',SUM(IF(MONTH = 6, numRecords, 0)) AS 'june',SUM(IF(MONTH = 7, numRecords, 0)) AS 'july',SUM(IF(MONTH = 8, numRecords, 0)) AS 'august',SUM(IF(MONTH = 9, numRecords, 0)) AS 'september',SUM(IF(MONTH = 10, numRecords, 0)) AS 'october',SUM(IF(MONTH = 11, numRecords, 0)) AS 'november',SUM(IF(MONTH = 12, numRecords, 0)) AS 'december',SUM(numRecords) AS montototal FROM ( SELECT id, MONTH(created) AS MONTH, ROUND(sum(montototal)) AS numRecords FROM venta WHERE DATE_FORMAT(created, '%Y') = $year GROUP BY id, MONTH ) AS SubTable1")->row();
    $monthlyExp = $this->db->query("SELECT SUM(IF(MONTH = 1, numRecords, 0)) AS 'january', SUM(IF(MONTH = 2, numRecords, 0)) AS 'feburary', SUM(IF(MONTH = 3, numRecords, 0)) AS 'march', SUM(IF(MONTH = 4, numRecords, 0)) AS 'april', SUM(IF(MONTH = 5, numRecords, 0)) AS 'may', SUM(IF(MONTH = 6, numRecords, 0)) AS 'june', SUM(IF(MONTH = 7, numRecords, 0)) AS 'july', SUM(IF(MONTH = 8, numRecords, 0)) AS 'august', SUM(IF(MONTH = 9, numRecords, 0)) AS 'september', SUM(IF(MONTH = 10, numRecords, 0)) AS 'october', SUM(IF(MONTH = 11, numRecords, 0)) AS 'november', SUM(IF(MONTH = 12, numRecords, 0)) AS 'december', SUM(numRecords) AS montototal FROM ( SELECT id, MONTH(created) AS MONTH, ROUND(sum(montototal)) AS numRecords FROM egreso WHERE DATE_FORMAT(created, '%Y') = $year GROUP BY id, MONTH ) AS SubTable1")->row();
    $data = array(
      'titulo' => $this->titulo_controlador,
      'contenido' => '/reporte' . $this->controlador,
      'monthly' => $monthlySales,
      'monthlyExp' => $monthlyExp,
      'year' => $year,
      'Top5product' => $Top5product,
      'empresas' => $this->Controlador_model->getAll('empresa'),
      'CustomerNumber' => $this->Controlador_model->contador('cliente'),
      'CategoriesNumber' => $this->Controlador_model->contador('productocategoria'),
      'ProductNumber' => $this->Controlador_model->contador('producto'),
      'TodaySales' => $TodaySales->sum
    );
    $this->load->view(THEME . TEMPLATE, $data);
  }

  public function consolidar()
  {
    $finicio = $this->input->post('finicio');
    $factual = $this->input->post('factual');
    $empresa = $this->input->post('empresa');
    $datas = $this->Controlador_model->consolidar($finicio, $factual, $empresa);
    $mostrar = '';
    $mostrar .= '<table id="example1" class="table table-bordered table-striped"><thead><tr><th>Orden</th><th>Codigo</th>
    <th>Descripcion</th><th>S. Inicial</th><th>Entrada</th><th>Salida</th><th>Stock</th></tr></thead><tbody>';
    $i = 0;

    foreach ($datas as $data) {
      $i++;
      $producto = $this->Controlador_model->get($data->producto, 'producto');
      if (!$producto) continue;
      $marca = $this->Controlador_model->get($producto->categoria, 'productocategoria');
      $primero = $this->Controlador_model->primerMov($data->producto, $finicio, $factual, $empresa); //? trae el primer movimiento de su producto
      $entrada = $this->Controlador_model->SumMovi($data->producto, $finicio, $factual, $empresa);
      $stock = $this->Controlador_model->getStock($data->producto, $empresa);
      if ($producto->tipo == "1") {
        //? si el tipo de producto es "Servicio es por que no funciona con STOCK"
        $dataSTock = "SERVICIO";
        $dataPrimero = "SERVICIO";
        $dataEntrada = "SERVICIO";
      } else {
        $dataPrimero = ($primero ? $primero->stockanterior : 0);
        $dataEntrada = ($entrada ? $entrada->cantidad : 0);
        $dataSTock = ($stock ? $stock->cantidad : 0);
      }



      $mostrar .= '
      <tr>
      <td>' . $i . '</td>
      <td>' . $producto->codigo . '</td>

      <td>' . $producto->nombre . ' ' . ($marca ? $marca->nombre : '') . '</td>

      <td>' . $dataPrimero . '</td>
      
      <td>' . $dataEntrada . '</td>

      <td>' . $data->numero . '</td>
      <td>' . $dataSTock . '</td></tr>';
    }

    $mostrar .= '</tbody></table>';
    echo $mostrar;
  }

  public function vendido()
  {
    $finicio = $this->input->post('finicio');
    $factual = $this->input->post('factual');
    $empresa = $this->input->post('empresa');
    $datas = $this->Controlador_model->vendido($finicio, $factual, $empresa);
    $mostrar = '';
    $mostrar .= '<table id="example1" class="table table-bordered table-striped"><thead><tr><th>Orden</th><th>Codigo</th>
    <th>Descripcion</th><th>Modelo</th><th>Categoria</th><th>Cantidad</th><th>Margen(%)</th></tr></thead><tbody>';
    $suma = $this->Controlador_model->vendidototal($finicio, $factual, $empresa);
    $i = 0;
    foreach ($datas as $data) {
      $i++;
      $producto = $this->Controlador_model->get($data->producto, 'producto');
      if (!$producto) continue;
      $marca = $this->Controlador_model->get($producto->categoria, 'productocategoria');
      //? $data->suma = cuanto se a vendido segun la fehca

      $margen = number_format(($data->suma / $suma->numero) * 100, 2);
      if ($producto->tipo == 0) {
        $categoria = 'ESTANDAR';
      }
      if ($producto->tipo == 1) {
        $categoria = 'COMBINACION';
      }
      if ($producto->tipo == 2) {
        $categoria = 'SERVICIO';
      }
      $mostrar .= '<tr>
      <td>' . $i . '</td>
      <td>' . $producto->codigo . '</td>
      <td>' . $producto->nombre . '</td>
      <td>' . ($marca ? $marca->nombre : '') . '</td>
      <td>' . $categoria . '</td>
      <td>' . $data->suma . '</td>
      <td>' . $margen . ' %</td>
      </tr>';
    }
    $mostrar .= '</tbody></table>';
    echo $mostrar;
  }

  public function valorizado()
  {
    $empresa = $this->input->post('empresa');
    $datas = $this->Controlador_model->valorizado($empresa);
    $mostrar = '';
    $mostrar .= '<table id="example1" class="table table-bordered table-striped"><thead><tr><th>Orden</th><th>Codigo</th>
    <th>Producto</th><th>Costo</th><th>Stock</th><th>SubTotal</th></tr></thead><tbody>';
    $total = 0;
    $i = 0;
    foreach ($datas as $data) {
      $i++;
      $producto = $this->Controlador_model->get($data->producto, 'producto');
      $marca = $this->Controlador_model->get($producto->categoria, 'productocategoria');
      $total += $data->costopromedio * $data->cantidad;
      $mostrar .= '<tr>
      <td>' . $i . '</td>
      <td>' . $producto->codigo . '</td>
      <td>' . $producto->nombre . ' ' . ($marca ? $marca->nombre : '') . '</td>
      <td>' . number_format($data->costopromedio, 2) . '</td><td>' . $data->cantidad . '</td>
      <td class="text-right">' . number_format($data->costopromedio * $data->cantidad, 2) . '</td>
      </tr>';
    }
    $mostrar .= '</tbody><tfoot><tr><td colspan="4"></td><td>Total:</td><td class="text-right">' . number_format($total, 2) . '</td>
    </tr></tfoot></table>';
    echo $mostrar;
  }

  public function consolidarexcel()
  {
    $finicio = $this->uri->segment(3);
    $factual = $this->uri->segment(4);
    $empresa = $this->uri->segment(5);
    $pedidos = $this->Controlador_model->consolidar($finicio, $factual, $empresa);
    // Propiedades del archivo excel
    $this->phpexcel->getProperties()->setTitle("Lista de Productos")->setDescription("Lista de Productos en Ventas");
    // Setiar la solapa que queda actia al abrir el excel
    $this->phpexcel->setActiveSheetIndex(0);
    // Solapa excel para trabajar con PHP
    $sheet = $this->phpexcel->getActiveSheet();
    $sheet->setTitle("Lista de Productos - Ventas");
    $sheet->getColumnDimension('A')->setAutoSize(true);
    $sheet->getColumnDimension('B')->setAutoSize(true);
    $sheet->getColumnDimension('C')->setAutoSize(true);
    $sheet->getColumnDimension('D')->setAutoSize(true);
    $sheet->getColumnDimension('E')->setAutoSize(true);
    $sheet->getColumnDimension('F')->setAutoSize(true);
    $sheet->getColumnDimension('G')->setAutoSize(true);
    $style_header = array('borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN)), 'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => 'E1E0F7')));
    $style = array('alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER));
    $sheet->getStyle('A1:G1')->applyFromArray($style_header);
    $sheet->getStyle("A1:G1")->applyFromArray($style);
    $sheet->setCellValue('A1', 'ORDEN');
    $sheet->setCellValue('B1', 'CODIGO');
    $sheet->setCellValue('C1', 'DESCRIPCION');
    $sheet->setCellValue('D1', 'S. INICIAL');
    $sheet->setCellValue('E1', 'ENTRADA');
    $sheet->setCellValue('F1', 'SALIDA');
    $sheet->setCellValue('G1', 'STOCK');
    $i = 1;
    foreach ($pedidos as $value) {
      $i++;
      $producto = $this->Controlador_model->get($value->producto, 'producto');
      if (!$producto) continue;
      //$marca = $this->Controlador_model->get($producto->categoria, 'productocategoria');
      $primero = $this->Controlador_model->primerMov($value->producto, $finicio, $factual, $empresa);


      $entrada = $this->Controlador_model->SumMovi($value->producto, $finicio, $factual, $empresa);


      $stock = $this->Controlador_model->getStock($value->producto, $empresa);



      if ($producto->tipo == "1") {
        //? si el tipo de producto es "Servicio es por que no funciona con STOCK"
        $dataSTock = "SERVICIO";
        $dataPrimero = "SERVICIO";
        $dataEntrada = "SERVICIO";
      } else {
        $dataPrimero = ($primero ? $primero->stockanterior : 0);
        $dataEntrada = ($entrada ? $entrada->cantidad : 0);
        $dataSTock = ($stock ? $stock->cantidad : 0);
      }


      $sheet->setCellValue('A' . $i, $i - 1);
      $sheet->setCellValue('B' . $i, $producto->codigo);
      $sheet->setCellValue('C' . $i, ($producto->nombre));
      $sheet->setCellValue('D' . $i,  $dataPrimero);
      $sheet->setCellValue('E' . $i, $dataEntrada);
      $sheet->setCellValue('F' . $i, $value->numero);
      $sheet->setCellValue('G' . $i, $dataSTock);
    }
    // Salida
    header("Content-Type: application/vnd.ms-excel");
    $nombreArchivo = 'consolidado_' . date('YmdHis');
    header("Content-Disposition: attachment; filename=\"$nombreArchivo.xls\"");
    header("Cache-Control: max-age=0");
    // Genera Excel
    $writer = PHPExcel_IOFactory::createWriter($this->phpexcel, "Excel5");
    // Escribir
    $writer->save('php://output');
    exit;
  }

  public function vendidoexcel()
  {
    $finicio = $this->uri->segment(3);
    $factual = $this->uri->segment(4);
    $empresa = $this->uri->segment(5);
    $pedidos = $this->Controlador_model->vendido($finicio, $factual, $empresa);
    // Propiedades del archivo excel
    $this->phpexcel->getProperties()->setTitle("Lista de Productos")->setDescription("Lista de Productos mas Vendido");
    // Setiar la solapa que queda actia al abrir el excel
    $this->phpexcel->setActiveSheetIndex(0);
    // Solapa excel para trabajar con PHP
    $sheet = $this->phpexcel->getActiveSheet();
    $sheet->setTitle("Lista de Productos - Ventas");
    $sheet->getColumnDimension('A')->setAutoSize(true);
    $sheet->getColumnDimension('B')->setAutoSize(true);
    $sheet->getColumnDimension('C')->setAutoSize(true);
    $sheet->getColumnDimension('D')->setAutoSize(true);
    $sheet->getColumnDimension('E')->setAutoSize(true);
    $sheet->getColumnDimension('F')->setAutoSize(true);
    $sheet->getColumnDimension('G')->setAutoSize(true);
    $style_header = array('borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN)), 'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => 'E1E0F7')));
    $style = array('alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER));
    $sheet->getStyle('A1:G1')->applyFromArray($style_header);
    $sheet->getStyle("A1:G1")->applyFromArray($style);
    $sheet->setCellValue('A1', 'ORDEN');
    $sheet->setCellValue('B1', 'CODIGO');
    $sheet->setCellValue('C1', 'DESCRIPCION');
    $sheet->setCellValue('D1', 'MARCA');
    $sheet->setCellValue('E1', 'CATEGORIA');
    $sheet->setCellValue('F1', 'CANTIDAD');
    $sheet->setCellValue('G1', 'MARGEN (%)');
    $i = 1;
    $suma = $this->Controlador_model->vendidototal($finicio, $factual, $empresa);
    foreach ($pedidos as $value) {
      $i++;
      $producto = $this->Controlador_model->get($value->producto, 'producto');
      if (!$producto) continue;
      //$marca = $this->Controlador_model->get($producto->categoria, 'productocategoria');
      $margen = number_format(($value->suma / $suma->numero) * 100, 2);
      $sheet->setCellValue('A' . $i, $i - 1);
      $sheet->setCellValue('B' . $i, $producto->codigo);
      $sheet->setCellValue('C' . $i, $producto->nombre);
      $sheet->setCellValue('D' . $i, "");
      $categoria = "";
      if ($producto->categoria == 0) {
        $categoria = 'ESTANDAR';
      }
      if ($producto->categoria == 1) {
        $categoria = 'COMBINACION';
      }
      if ($producto->categoria == 2) {
        $categoria = 'SERVICIO';
      }
      $sheet->setCellValue('E' . $i, $categoria);
      $sheet->setCellValue('F' . $i, $value->suma);
      $sheet->setCellValue('G' . $i, $margen . ' %');
    }
    // Salida
    header("Content-Type: application/vnd.ms-excel");
    $nombreArchivo = 'vendido_' . date('YmdHis');
    header("Content-Disposition: attachment; filename=\"$nombreArchivo.xls\"");
    header("Cache-Control: max-age=0");
    // Genera Excel
    $writer = PHPExcel_IOFactory::createWriter($this->phpexcel, "Excel5");
    // Escribir
    $writer->save('php://output');
    exit;
  }

  public function valorizadoexcel()
  {
    $empresa = $this->uri->segment(3);
    $pedidos = $this->Controlador_model->valorizado($empresa);
    // Propiedades del archivo excel
    $this->phpexcel->getProperties()->setTitle("Lista de Productos")->setDescription("Lista de productos en Stock");
    // Setiar la solapa que queda actia al abrir el excel
    $this->phpexcel->setActiveSheetIndex(0);
    // Solapa excel para trabajar con PHP
    $sheet = $this->phpexcel->getActiveSheet();
    $sheet->setTitle("Lista de Productos - Stock");
    $sheet->getColumnDimension('A')->setAutoSize(true);
    $sheet->getColumnDimension('B')->setAutoSize(true);
    $sheet->getColumnDimension('C')->setAutoSize(true);
    $sheet->getColumnDimension('D')->setAutoSize(true);
    $sheet->getColumnDimension('E')->setAutoSize(true);
    $sheet->getColumnDimension('F')->setAutoSize(true);
    $sheet->getColumnDimension('G')->setAutoSize(true);
    $sheet->getColumnDimension('H')->setAutoSize(true);
    $sheet->getColumnDimension('I')->setAutoSize(true);
    $sheet->getStyle('F')->getNumberFormat()->setFormatCode('#,##0.00');
    $sheet->getStyle('G')->getNumberFormat()->setFormatCode('#,##0.00');
    $sheet->getStyle('I')->getNumberFormat()->setFormatCode('#,##0.00');
    $style_header = array('borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN)), 'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => 'E1E0F7')));
    $style = array('alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER));
    $sheet->getStyle('A1:I1')->applyFromArray($style_header);
    $sheet->getStyle("A1:I1")->applyFromArray($style);
    $sheet->setCellValue('A1', 'ORDEN');
    $sheet->setCellValue('B1', 'CODIGO');
    $sheet->setCellValue('C1', 'DESCRIPCION');
    $sheet->setCellValue('D1', 'MARCA');
    $sheet->setCellValue('E1', 'CATEGORIA');
    $sheet->setCellValue('F1', 'COSTO');
    $sheet->setCellValue('G1', 'VENTA');
    $sheet->setCellValue('H1', 'STOCK');
    $sheet->setCellValue('I1', 'SUBTOTAL');
    $i = 1;
    foreach ($pedidos as $value) {
      $i++;
      $producto = $this->Controlador_model->get($value->producto, 'producto');
      if (!$producto) continue;
      $categoria = "";
      //$marca = $this->Controlador_model->get($producto->categoria, 'productocategoria');
      $sheet->setCellValue('A' . $i, $i - 1);
      $sheet->setCellValue('B' . $i, $producto->codigo);
      $sheet->setCellValue('C' . $i, $producto->nombre);
      $sheet->setCellValue('D' . $i, "");
      if ($producto->categoria == 0) {
        $categoria = 'ESTANDAR';
      }
      if ($producto->categoria == 1) {
        $categoria = 'COMBINACION';
      }
      if ($producto->categoria == 2) {
        $categoria = 'SERVICIO';
      }
      $sheet->setCellValue('E' . $i, $categoria);
      $sheet->setCellValue('F' . $i, number_format($value->costopromedio, 2));
      $sheet->setCellValue('G' . $i, number_format($producto->precioventa, 2));
      $sheet->setCellValue('H' . $i, $value->cantidad);
      $sheet->setCellValue('I' . $i, number_format($value->costopromedio * $value->cantidad, 2));
    }
    // Salida
    header("Content-Type: application/vnd.ms-excel");
    $nombreArchivo = 'valorizado_' . date('YmdHis');
    header("Content-Disposition: attachment; filename=\"$nombreArchivo.xls\"");
    header("Cache-Control: max-age=0");
    // Genera Excel
    $writer = PHPExcel_IOFactory::createWriter($this->phpexcel, "Excel5");
    // Escribir
    $writer->save('php://output');
    exit;
  }

  public function inventarioexcel()
  {
    $empresas = $this->uri->segment(3);
    $familias = $this->Controlador_model->getAll('productocategoria');
    $empresa = $this->Controlador_model->get($empresas, 'empresa');
    // Propiedades del archivo excel
    $this->phpexcel->getProperties()->setTitle("INVENTARIO DE ARTICULOS")->setDescription("INVENTARIO");
    // Setiar la solapa que queda actia al abrir el excel
    $this->phpexcel->setActiveSheetIndex(0);
    // Solapa excel para trabajar con PHP
    $sheet = $this->phpexcel->getActiveSheet();
    $sheet->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_PORTRAIT);
    $sheet->getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4);
    $sheet->getPageSetup()->setFitToWidth(1);
    $sheet->getPageSetup()->setFitToHeight(0);
    $sheet->getHeaderFooter()->setOddHeader('&B&IINVENTARIO DE ARTICULOS &R' . date('m/d/Y'));
    $sheet->getHeaderFooter()->setOddFooter('&L&B' . $this->phpexcel->getProperties()->getTitle() . '&RPagina &P de &N');
    $this->phpexcel->getDefaultStyle()->getFont()->setSize(10);
    $sheet->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 3);
    $sheet->setTitle("REPUESTOS Y LUBRICANTES");
    $sheet->getColumnDimension('A')->setAutoSize(true);
    $sheet->getColumnDimension('B')->setAutoSize(true);
    $sheet->getColumnDimension('C')->setAutoSize(true);
    $sheet->getColumnDimension('D')->setAutoSize(true);
    $sheet->getColumnDimension('E')->setAutoSize(true);
    $sheet->getColumnDimension('F')->setAutoSize(true);
    $style_header = array('borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN)), 'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => 'E1E0F7')));
    $center = array('alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER));
    $left = array('alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_LEFT));
    $right = array('alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_RIGHT));
    $borde = array('borders' => array('outline' => array('style' => PHPExcel_Style_Border::BORDER_THIN)));
    $sheet->mergeCells('A1:D1');
    $sheet->setCellValue('A1', $empresa->serie . ' ' . $empresa->razonsocial);
    $sheet->getStyle("E1:F1")->applyFromArray($right);
    $sheet->mergeCells('E1:F1');
    $sheet->setCellValue('E1', date('g:i:s A', time()));
    $sheet->mergeCells('A2:D2');
    $sheet->getStyle('A3:F3')->applyFromArray($style_header);
    $sheet->getStyle('A3:F3')->applyFromArray($center);
    $sheet->setCellValue('A3', 'ORDEN');
    $sheet->setCellValue('B3', 'CODIGO');
    $sheet->setCellValue('C3', 'DESCRIPCION');
    $sheet->setCellValue('D3', 'MARCA');
    $sheet->setCellValue('E3', 'CANTIDAD');
    $sheet->setCellValue('F3', 'STOCK');
    $i = 3;
    $j = 0;
    $k = 0;
    foreach ($familias as $data) {
      $i++;
      $sheet->getStyle('A' . $i . ':F' . $i)->applyFromArray($borde);
      $sheet->mergeCells('A' . $i . ':F' . $i);
      $sheet->setCellValue('A' . $i, $data->nombre);
      $productos = $this->Controlador_model->getFamilia($data->id);
      foreach ($productos as $value) {
        $stock = $this->Controlador_model->getStock($value->id, $empresas);
        if ($stock) {
          $producto = $this->Controlador_model->get($value->id, 'producto');
          $j++;
          $i++;
          $sheet->getStyle('A' . $i)->applyFromArray($borde);
          $sheet->getStyle('B' . $i)->applyFromArray($borde);
          $sheet->getStyle('C' . $i)->applyFromArray($borde);
          $sheet->getStyle('D' . $i)->applyFromArray($borde);
          $sheet->getStyle('E' . $i)->applyFromArray($borde);
          $sheet->getStyle('F' . $i)->applyFromArray($borde);
          $sheet->setCellValue('A' . $i, $j);
          $sheet->setCellValue('B' . $i, $value->codigo);
          $sheet->setCellValue('C' . $i, $value->nombre);
          $sheet->setCellValue('D' . $i, "");
          $sheet->setCellValue('E' . $i, ($stock ? $stock->cantidad : 0));
          $sheet->setCellValue('F' . $i, '');
        }
      }
    }
    // Salida
    header("Content-Type: application/vnd.ms-excel");
    $nombreArchivo = 'inventario_' . date('Y-m-d_His');
    header("Content-Disposition: attachment; filename=\"$nombreArchivo.xls\"");
    header("Cache-Control: max-age=0");
    // Genera Excel
    $writer = PHPExcel_IOFactory::createWriter($this->phpexcel, "Excel5");
    // Escribir
    $writer->save('php://output');
    exit;
  }

  public function cargar()
  {
    $config["upload_path"] = realpath(APPPATH . "../files");
    $config["allowed_types"] = 'xls';
    $config["max_size"] = '0';
    $this->upload->initialize($config);
    if (!$this->upload->do_upload('file')) {
      print_r($this->upload->display_errors());
    } else {
      $data = array('upload_data' => $this->upload->data());
      $this->load->library('PHPExcel');
      $objPHPExcel = PHPExcel_IOFactory::load(APPPATH . '../files/' . $data['upload_data']['file_name']);
    }
    unlink($config["upload_path"] . '/' . $data['upload_data']['file_name']);
    $cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection(); //estamos trayendo la coleccion de filas
    $header = array();
    $arr_data = array();
    foreach ($cell_collection as $cell) {
      # code...
      //aui estamos obteniendo las columnas a,b,c
      $column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
      $row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
      $data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
      if ($row == 1) {
        $header[$row][$column] = $data_value;
      } else {
        $arr_data[$row][$column] = $data_value;
      }
    }
    $data = array(
      'titulo' => $this->titulo_controlador,
      'contenido' => $this->vista . 'ver',
      'datas' => $arr_data,
      'breads' => array(
        array('ruta' => $this->url, 'titulo' => $this->titulo_controlador),
        array('ruta' => 'javascript:;', 'titulo' => 'Cargar')
      )
    );
    $this->load->view(THEME . TEMPLATE, $data);
  }

  public function ajax_listvariante($id)
  {
    $draw = intval($this->input->get("draw"));
    $start = intval($this->input->get("start"));
    $length = intval($this->input->get("length"));
    $query = $this->db->order_by('id', 'desc')->where('producto', $id)->get('productovariante')->result();
    $data = [];
    foreach ($query as $key => $value) {
      //add variables for action
      $boton = '';
      //add html for action
      $boton .= '<a class="btn btn-sm btn-primary" title="Modificar" onclick="editvariante(' . $value->id . ')"><i class="fa fa-pencil"></i></a> ';
      $boton .= '<a class="btn btn-sm btn-danger" title="Borrar" onclick="borrarvariante(' . $value->id . ')"><i class="fa fa-trash"></i></a>';
      $data[] = array(
        $key + 1,
        $value->nombre,
        $value->precio,
        $boton
      );
    }
    $result = array(
      "draw" => $draw,
      "recordsTotal" => $start,
      "recordsFiltered" => $length,
      "data" => $data
    );
    //output to json format
    echo json_encode($result);
  }

  public function ajax_addvariante()
  {
    $data['producto'] = $this->input->post('varianteproducto');
    $data['nombre'] = $this->input->post('nombrevariante');
    $data['precio'] = $this->input->post('preciovariante');
    $insert = $this->Controlador_model->save('productovariante', $data);
    echo json_encode(array("status" => TRUE));
  }

  public function ajax_editvariante($id)
  {
    $data = $this->Controlador_model->get_by_id($id, 'productovariante');
    echo json_encode($data);
  }

  public function ajax_updatevariante()
  {
    $data['producto'] = $this->input->post('varianteproducto');
    $data['nombre'] = $this->input->post('nombrevariante');
    $data['precio'] = $this->input->post('preciovariante');
    $this->Controlador_model->update(array('id' => $this->input->post('idvariante')), $data, 'productovariante');
    echo json_encode(array("status" => TRUE));
  }

  public function ajax_deletevariante($id)
  {
    if ($this->Controlador_model->delete_by_id($id, 'productovariante')) {
      echo json_encode(array("status" => TRUE));
    }
  }

  public function ajax_stockproducto($producto) //producto no es por empresa
  {
    $produ = $this->Controlador_model->get($producto, $this->controlador);
    if ($produ->tipo == 0) {
      $stock = $this->db->where('producto', $producto)->get('stock')->row();
      if ($stock) {
        $data = $stock;
        $data->status = TRUE;
        $data->nombre = $produ->nombre;
      } else {
        $idstock = $this->Controlador_model->save('stock', ['empresa' => '1', 'producto' => $producto, 'cantidad' => '0', 'costopromedio' => '0']);
        $data = ['status' => TRUE, 'nombre' => $produ->nombre, 'id' => $idstock, 'empresa' => '1', 'producto' => $producto, 'cantidad' => '0', 'costopromedio' => '0'];
      }
      echo json_encode($data);
    } else
      echo json_encode(['status' => FALSE]);
  }

  private function _validatestock()
  {
    $data = array();
    $data['error_string'] = array();
    $data['inputerror'] = array();
    $data['status'] = TRUE;


    if ($this->input->post('cantidadstock') == '' || $this->input->post('cantidadstock') == '0') {
      $data['inputerror'][] = 'cantidadstock';
      $data['error_string'][] = 'Este campo es obligatorio.';
      $data['status'] = FALSE;
    }

    if ($data['status'] === FALSE) {
      echo json_encode($data);
      exit();
    }
  }

  public function ajax_addstock()
  {
    $this->_validatestock();
    $stock = $this->Controlador_model->get($this->input->post('idstock'), 'stock');
    $data['cantidad'] = $stock->cantidad + $this->input->post('cantidadstock');
    $this->Controlador_model->update(['id' => $this->input->post('idstock')], $data, 'stock');

    $producto = $this->Controlador_model->get($stock->producto, 'producto');

    if ($this->input->post('cantidadstock') > 0) {
      $ni = $this->crear_nota_ingreso();
      /*  */
      $datanid['producto'] = $producto->id;
      $datanid['notaingreso'] = $ni;
      $datanid['nombre'] = $producto->nombre;
      $datanid['precio'] = $producto->preciocompra;
      $datanid['cantidad'] = $this->input->post('cantidadstock');
      $datanid['subtotal'] = $producto->preciocompra * $this->input->post('cantidadstock');
      $this->Controlador_model->save('notaingresodetalle', $datanid);
      /*  */
      $movimiento['empresa'] = $this->empresa;
      $movimiento['usuario'] = $this->usuario;
      $movimiento['notaingreso'] = $ni;
      $movimiento['tipo'] = 'ENTRADA';
      $movimiento['producto'] = $stock->producto;
      $movimiento['cantidad'] = $this->input->post('cantidadstock');
      $movimiento['stockanterior'] = $stock ? $stock->cantidad : 0;
      $movimiento['stockactual'] = ($stock ? $stock->cantidad : 0) + $this->input->post('cantidadstock');
      $movimiento['costopromedio'] = 0.0; //$stock ? $stock->costopromedio : $producto->preciocompra;
      $movimiento['created'] = date('Y-m-d');
      $this->Controlador_model->save('movimiento', $movimiento);
    } elseif ($this->input->post('cantidadstock') < 0) {
      $ns = $this->crear_nota_salida();
      /*  */
      $datansd['producto'] = $producto->id;
      $datansd['notasalida'] = $ns;
      $datansd['nombre'] = $producto->nombre;
      $datansd['precio'] = $producto->preciocompra;
      $datansd['cantidad'] = -1 * $this->input->post('cantidadstock');
      $datansd['subtotal'] = -1 * $producto->preciocompra * $this->input->post('cantidadstock');
      $this->Controlador_model->save('notasalidadetalle', $datansd);
      /*  */
      $movimiento['empresa'] = $this->empresa;
      $movimiento['usuario'] = $this->usuario;
      $movimiento['notasalida'] = $ns;
      $movimiento['tipo'] = 'SALIDA';
      $movimiento['producto'] = $stock->producto;
      $movimiento['cantidad'] = -1 * $this->input->post('cantidadstock');
      $movimiento['stockanterior'] = $stock ? $stock->cantidad : 0;
      $movimiento['stockactual'] = ($stock ? $stock->cantidad : 0) + $this->input->post('cantidadstock');
      $movimiento['costopromedio'] = 0; //$stock ? $stock->costopromedio : $stock->costo;
      $movimiento['created'] = date('Y-m-d');
      $this->Controlador_model->save('movimiento', $movimiento);
    }

    echo json_encode(["status" => TRUE]);
  }

  public function crear_nota_ingreso()
  {
    $numero = $this->Controlador_model->codigo_nota('notaingreso', $this->empresa);
    $numeros = $numero ? $numero->correlativo + 1 : 1;
    $cadena = "";
    for ($i = 0; $i < 4 - strlen($numeros); $i++) {
      $cadena = $cadena . '0';
    }
    $data['codigo'] = "NI" . $cadena . $numeros;
    $data['correlativo'] = $numeros;
    $data['tipoingreso'] = 'AJUSTE STOCK';
    $data['usuario'] = $this->usuario;
    $data['empresa'] = $this->empresa;
    $data['estado'] = '1';
    $data['created'] = date('Y-m-d');
    $insert = $this->Controlador_model->save('notaingreso', $data);
    return $insert;
  }

  public function crear_nota_salida()
  {
    $numero = $this->Controlador_model->codigo_nota('notasalida', $this->empresa);
    $numeros = $numero ? $numero->correlativo + 1 : 1;
    $cadena = "";
    for ($i = 0; $i < 4 - strlen($numeros); $i++) {
      $cadena = $cadena . '0';
    }
    $data['codigo'] = "NS" . $cadena . $numeros;
    $data['correlativo'] = $numeros;
    $data['empresa'] = $this->empresa;
    $data['usuario'] = $this->usuario;
    $data['tiposalida'] = 'AJUSTE STOCK';
    $data['estado'] = '1';
    $data['created'] = date('Y-m-d');
    $insert = $this->Controlador_model->save('notasalida', $data);
    return $insert;
  }

  public function ajustestock()
  {
    $stocks = $this->db->get('stock')->result();
    foreach ($stocks as $key => $value) {
      $ss = $this->db->where('id', $value->id)->get('stock_xxx')->row();
      if ($ss) {
        echo $key . ' - ' . $value->cantidad . ' - ';
        $value->cantidad = $ss->cantidad;
        echo $ss->cantidad . '<br>';
        ///$this->Controlador_model->update(['id' => $value->id], ['cantidad' => $ss->cantidad], 'stock');
      }
    }
  }
}
