<?php

class Empresa extends CI_Controller
{

  public function __construct()
  {
    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->usuario = $this->session->userdata('usuario') ? $this->session->userdata('usuario') : FALSE;
    $this->empresa = $this->session->userdata('empresa') ? $this->session->userdata('empresa') : FALSE;
  }

  public function index()
  {
    $data = array(
      'titulo' => $this->titulo_controlador,
      'contenido' => $this->vista,
      'iconos' => $this->Controlador_model->getAll('icono'),
      'breads' => array(array('ruta' => 'javascript:;', 'titulo' => $this->titulo_controlador)),
      'zonamesa' => $this->Controlador_model->zonasmesas(), //Controlador_model->getAll('zona')
    );
    $this->load->view(THEME . TEMPLATE, $data);
  }

  function ajax_datazona()
  {
    //$idempresa = $this->input->post("idempresa"); //->where("empresa", $idempresa)
    $datazona = $this->Controlador_model->zonasmesas();
    echo json_encode(["datazona" => $datazona]);
  }

  public function ajax_list()
  {
    $draw = intval($this->input->post("draw") ? $this->input->post("draw") : $this->input->get("draw"));
    $start = intval($this->input->post("start") ? $this->input->post("start") : $this->input->get("start"));
    $length = intval($this->input->post("length") ? $this->input->post("length") : $this->input->get("length"));
    $query = $this->db->order_by('id', 'desc')->get($this->controlador)->result();
    $data = [];
    $tipo['0'] = 'NATURAL';
    $tipo['1'] = 'JURIDICA';
    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="edit(' . $value->id . ')"><i class="fas fa-edit"></i></a> ';
      $boton .= '<a class="btn btn-sm btn-success" title="Zona" onclick="zona(' . $value->id . ')"><i class="fas fa-layer-group"></i></a> ';
      $boton .= '<a class="btn btn-sm btn-info" title="Mesa" onclick="mesa(' . $value->id . ')"><i class="fas fa-chair"></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') {
        $boton .= '<a class="btn btn-sm btn-warning" title="Desactivar" onclick="desactivar(' . $value->id . ')"><i class="fas fa-power-off"></i></a> ';
      } else {
        $boton .= '<a class="btn btn-sm btn-default" title="Activar" onclick="activar(' . $value->id . ')"><i class="fas fa-check"></i></a> ';
      }

      $facturar = '<div class="pretty p-switch"><input type="checkbox" name="switch1" onclick="facturar(' . $value->id . ')" ' . ($value->facturar == '1' ? 'checked' : '') . '/><div class="state p-success"><label></label></div></div>';
      $caja = $this->db->where('empresa', $value->id)->where('estado', '0')->get('caja')->row();
      $data[] = array(
        $key + 1,
        $tipo[$value->tipo],
        $value->ruc,
        $value->razonsocial,
        substr($value->nombre, 0, 20),
        substr($value->direccion, 0, 30),
        $caja ? '<span class="badge badge-success">ABIERTO</span>' : '<span class="badge badge-danger">CERRADO</span>',
        $facturar,
        $boton
      );
    }
    $result = array(
      "draw" => $draw,
      "recordsTotal" => intval(count($query)),
      "recordsFiltered" => intval(count($query)),
      "data" => $data
    );
    //output to json format
    echo json_encode($result);
  }

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

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

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

    if ($check) {
      $data['inputerror'][] = 'ruc';
      $data['error_string'][] = 'Este campo ya esta registrado en BD.';
      $data['status'] = FALSE;
    }

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

  public function ajax_add()
  {
    $this->_validate();
    $config['upload_path'] = './files/Setting/';
    $config['file_name'] = 'logo' . $this->input->post('ruc');
    $config['overwrite'] = 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);
    if ($this->upload->do_upload('logo')) {
      $datas = array('upload_data' => $this->upload->data());
      $image = $datas['upload_data']['file_name'];
    } else {
      $image = '5dda8da7287e07792b4ce7094f1270c6.png';
    }
    $data['ruc'] = $this->input->post('ruc');
    $data['razonsocial'] = $this->input->post('razonsocial');
    $data['nombre'] = $this->input->post('nombre');
    $data['direccion'] = $this->input->post('direccion');
    $data['telefono'] = $this->input->post('telefono');
    $data['serie'] = $this->input->post('serie');
    $data['ubigeo'] = $this->input->post('ubigeo');
    $data['departamento'] = $this->input->post('departamento');
    $data['provincia'] = $this->input->post('provincia');
    $data['distrito'] = $this->input->post('distrito');
    $data['usuariosol'] = $this->input->post('usuariosol');
    $data['clavesol'] = $this->input->post('clavesol');
    $data['logo'] = $image;
    $data['tipoproceso'] = $this->input->post('tipoproceso');
    $data['tipo'] = $this->input->post('tipo');
    $data['tipoimpresora'] = $this->input->post('tipoimpresora');
    $data['nombreimpresora'] = $this->input->post('nombreimpresora');
    if ($this->Controlador_model->save($this->controlador, $data)) {
      echo json_encode(array("status" => TRUE));
    }
  }

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

  public function ajax_update()
  {
    $this->_validate();
    $config['upload_path'] = './files/Setting/';
    $config['file_name'] = 'logo' . $this->input->post('ruc');
    $config['overwrite'] = 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);
    $usuario = $this->Controlador_model->get_by_id($this->input->post('id'), $this->controlador);
    if ($this->upload->do_upload('logo')) {
      if ($usuario->logo <> '5dda8da7287e07792b4ce7094f1270c6.png') {
        @unlink('./files/Setting/' . $usuario->logo);
      }
      $datas = array('upload_data' => $this->upload->data());
      $image = $datas['upload_data']['file_name'];
    } else {
      $image = $usuario->logo;
    }
    $data['ruc'] = $this->input->post('ruc');
    $data['razonsocial'] = $this->input->post('razonsocial');
    $data['nombre'] = $this->input->post('nombre');
    $data['direccion'] = $this->input->post('direccion');
    $data['telefono'] = $this->input->post('telefono');
    $data['serie'] = $this->input->post('serie');
    $data['ubigeo'] = $this->input->post('ubigeo');
    $data['departamento'] = $this->input->post('departamento');
    $data['provincia'] = $this->input->post('provincia');
    $data['distrito'] = $this->input->post('distrito');
    $data['usuariosol'] = $this->input->post('usuariosol');
    $data['clavesol'] = $this->input->post('clavesol');
    $data['logo'] = $image;
    $data['tipoproceso'] = $this->input->post('tipoproceso');
    $data['tipo'] = $this->input->post('tipo');
    $data['tipoimpresora'] = $this->input->post('tipoimpresora');
    $data['nombreimpresora'] = $this->input->post('nombreimpresora');
    $this->Controlador_model->update(array('id' => $this->input->post('id')), $data, $this->controlador);
    echo json_encode(array("status" => TRUE));
  }

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

  public function cambiar($id)
  {
    if ($id) {
      $CI = &get_instance();
      $CI->session->set_userdata('empresa', $id);
      redirect('/');
    } else {
      show_404();
    }
  }

  public function ajax_listzona($id)
  {
    $draw = intval($this->input->get("draw"));
    $start = intval($this->input->get("start"));
    $length = intval($this->input->get("length"));
    //->where('empresa', $id)
    $query = $this->db->order_by('id', 'desc')->get('zona')->result();
    $data = [];
    foreach ($query as $key => $value) {
      $boton = '';
      $boton .= '<a class="btn btn-xs btn-primary" title="Modificar" onclick="editzona(' . $value->id . ')"><i class="fas fa-edit"></i></a> ';
      $boton .= '<a class="btn btn-xs btn-danger" title="Borrar" onclick="borrarzona(' . $value->id . ')"><i class="fas fa-trash"></i></a> ';
      
      $icon_display = '<i class="' . str_replace('fa ', 'fas ', $value->icono) . '"></i> ' . $value->icono;
      
      $estado = '<div class="pretty p-switch"><input type="checkbox" onclick="cambiarestadozona(' . $value->id . ')" ' . ($value->estado == '0' ? 'checked' : '') . '/><div class="state p-success"><label></label></div></div>';
      
      $data[] = array(
        $key + 1,
        $value->nombre,
        $icon_display,
        $value->posicion,
        $estado,
        $boton
      );
    }
    $result = array(
      "draw" => $draw,
      "recordsTotal" => intval(count($query)),
      "recordsFiltered" => intval(count($query)),
      "data" => $data
    );
    //output to json format
    echo json_encode($result);
  }

  private function _validatezona()
  {
    $data = array();
    $data['error_string'] = array();
    $data['inputerror'] = array();
    $data['status'] = TRUE;
    $id = $this->input->post('idzona');
    $empresa = $this->input->post('empresazona');
    $nombre = $this->input->post('nombrezona');
    $zonalist = $this->Controlador_model->duplicadozona($id, $empresa, $nombre);

    if ($nombre == '') {
      $data['inputerror'][] = 'nombrezona';
      $data['error_string'][] = 'Este campo es obligatorio.';
      $data['status'] = FALSE;
    }

    if ($zonalist) {
      $data['inputerror'][] = 'nombrezona';
      $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_addzona()
  {
    $this->_validatezona();
    $data['empresa'] = NULL; //$this->input->post('empresazona');
    $data['nombre'] = $this->input->post('nombrezona');
    $data['icono'] = $this->input->post('iconozona');
    $insert = $this->Controlador_model->save('zona', $data);
    echo json_encode(array("status" => TRUE));
  }

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

  public function ajax_updatezona()
  {
    $this->_validatezona();
    //$data['empresa'] = $this->input->post('empresazona');
    $data['nombre'] = $this->input->post('nombrezona');
    $data['icono'] = $this->input->post('iconozona');
    $this->Controlador_model->update(array('id' => $this->input->post('idzona')), $data, 'zona');
    echo json_encode(array("status" => TRUE));
  }

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

  public function ajax_listmesa($empresa, $zona)
  {
    $draw = intval($this->input->get("draw"));
    $start = intval($this->input->get("start"));
    $length = intval($this->input->get("length"));
    //->where('empresa', $id)
    //$query = $this->db->order_by('id', 'desc')->get('mesa')->result();

    if ($zona != 0) $this->db->where('z.id', $zona);
    $this->db->select('m.*,z.nombre znombre');
    $this->db->where('z.estado', '0')->where('z.is_dynamic', 0);
    $this->db->join('zona z', 'z.id=m.zona');
    $query = $this->db->order_by('m.id', 'desc')->get('mesa m')->result();

    $data = [];
    foreach ($query as $key => $value) {
      //add variables for action
      $boton = '';
      //add html for action
      $boton .= '<a class="btn btn-xs btn-primary" title="Modificar" onclick="editmesa(' . $value->id . ')"><i class="fas fa-edit"></i></a> ';
      $boton .= '<a class="btn btn-xs btn-danger" title="Borrar" onclick="borrarmesa(' . $value->id . ')"><i class="fas fa-trash"></i></a> ';
      
      $zona = $this->Controlador_model->get($value->zona, 'zona');
      $zona_nombre = $zona ? $zona->nombre : 'Sin Zona';
      
      $data[] = array(
        $key + 1,
        $value->nombre,
        $zona_nombre,
        $boton
      );
    }
    $result = array(
      "draw" => $draw,
      "recordsTotal" => intval(count($query)),
      "recordsFiltered" => intval(count($query)),
      "data" => $data
    );
    //output to json format
    echo json_encode($result);
  }

  private function _validatemesa()
  {
    $data = array();
    $data['error_string'] = array();
    $data['inputerror'] = array();
    $data['status'] = TRUE;
    $empresa = $this->input->post('empresamesa');
    $nombre = $this->input->post('nombremesa');
    $zona = $this->input->post('zonamesa');
    $zonalist = $this->Controlador_model->duplicadomesa($empresa, $zona, $nombre);

    if ($nombre == '') {
      $data['inputerror'][] = 'nombrezona';
      $data['error_string'][] = 'Este campo es obligatorio.';
      $data['status'] = FALSE;
    }

    if ($zonalist) {
      $data['inputerror'][] = 'nombrezona';
      $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_addmesa()
  {
    $this->_validatemesa();
    $data['empresa'] = NULL; //$this->input->post('empresamesa');
    $data['nombre'] = $this->input->post('nombremesa');
    $data['zona'] = $this->input->post('zonamesa');
    $insert = $this->Controlador_model->save('mesa', $data);
    echo json_encode(array("status" => TRUE));
  }

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

  public function ajax_updatemesa()
  {
    $this->_validatemesa();
    $data['empresa'] = NULL; //$this->input->post('empresamesa');
    $data['nombre'] = $this->input->post('nombremesa');
    $data['zona'] = $this->input->post('zonamesa');
    $this->Controlador_model->update(array('id' => $this->input->post('idmesa')), $data, 'mesa');
    echo json_encode(array("status" => TRUE));
  }

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

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

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

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

  public function ajax_desactivarzona($id)
  {
    if ($this->Controlador_model->desactivar_by_id($id, 'zona')) {
      echo json_encode(array("status" => TRUE));
    }
  }

  public function ajax_activarzona($id)
  {
    if ($this->Controlador_model->activar_by_id($id, 'zona')) {
      echo json_encode(array("status" => TRUE));
    }
  }

  public function ajax_bajarzona($zona, $pos)
  {
    $pos--;

    if ($pos < 1)
      $pos = 1;
    $this->Controlador_model->update(['id' => $zona], ['posicion' => $pos], 'zona');
    echo json_encode(array("status" => TRUE));
  }
  public function ajax_subirzona($zona, $pos)
  {
    $pos++;
    $conteo = $this->db->select('count(id) conteo')->get('zona')->row()->conteo;
    $total = $conteo ? $conteo : 100;
    if ($pos >= $total)
      $pos = $total;
    $this->Controlador_model->update(['id' => $zona], ['posicion' => $pos], 'zona');
    echo json_encode(array("status" => TRUE));
  }

  public function toggle_estadozona($id)
  {
    $zona = $this->Controlador_model->get_by_id($id, 'zona');
    if ($zona->estado == '0') {
      $this->Controlador_model->desactivar_by_id($id, 'zona');
    } else {
      $this->Controlador_model->activar_by_id($id, 'zona');
    }
    echo json_encode(array("status" => TRUE));
  }
}
