<?php

class Kardex 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,
      'datas' => $this->Controlador_model->getAll('empresa'),
      'breads' => array(array('ruta' => 'javascript:;', 'titulo' => $this->titulo_controlador))
    );
    $this->load->view(THEME . TEMPLATE, $data);
  }

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

  public function kardexFecha()
  {
    $producto = $this->input->post('producto');
    $fechainicio = $this->input->post('fechainicio');
    $fechafinal = $this->input->post('fechafinal');
    $movimientos = $this->Controlador_model->kardexFecha($producto, $fechainicio, $fechafinal);
    $saldoinicial = $this->Controlador_model->saldoinicialxFecha($producto, $fechainicio, $fechafinal);
    
    $ticket = '<div class="table-responsive">
    <table class="table table-hover table-bordered table-striped">
    <thead class="bg-navy text-white">
        <tr>
            <th width="50">#</th>
            <th>Tipo / Concepto</th>
            <th>Fecha</th>
            <th>Nº Doc.</th>
            <th>Referencia / Usuario</th>
            <th class="text-right">Precio</th>
            <th class="text-center">Entrada</th>
            <th class="text-center">Salida</th>
            <th class="text-center bg-light">Saldo</th>
        </tr>
    </thead>
    <tbody>
        <tr class="bg-light">
            <td colspan="5"></td>
            <td class="text-right font-weight-bold text-muted">SALDO INICIAL:</td>
            <td colspan="2"></td>
            <td class="text-center font-weight-bold text-primary">' . ($saldoinicial ? number_format($saldoinicial->stockanterior, 2) : '0.00') . '</td>
        </tr>';
    
    $saldofinal = $saldoinicial ? $saldoinicial->stockanterior : 0;
    $salida = 0;
    $ingreso = 0;
    $i = 1;
    
    foreach ($movimientos as $data) {
      $saldofinal = $saldofinal + ($data->tipo == 'ENTRADA' ? $data->cantidad : 0) - ($data->tipo == 'SALIDA' ? $data->cantidad : 0);
      $ingreso = $ingreso + ($data->tipo == 'ENTRADA' ? $data->cantidad : 0);
      $salida = $salida + ($data->tipo == 'SALIDA' ? $data->cantidad : 0);
      
      $venta = $this->Controlador_model->get($data->venta, 'venta');
      $notaingreso = $this->Controlador_model->get($data->notaingreso, 'notaingreso');
      $notasalida = $this->Controlador_model->get($data->notasalida, 'notasalida');
      
      $badge = '';
      $razon = '---';
      $fecha = $data->created;
      $numero = '---';
      $precio = 0;
      
      if ($venta) {
        $badge = '<span class="badge badge-success"><i class="fas fa-shopping-cart"></i> VENTA</span>';
        $numero = $venta->serie . '-' . $venta->numero;
        $cliente = $this->Controlador_model->get($venta->cliente, 'cliente');
        $razon = $cliente ? $cliente->nombre . ' ' . $cliente->apellido : 'CLIENTE VARIOS';
        $VD = $this->Controlador_model->getVDetalle($data->producto, $data->venta);
        $precio = $VD ? $VD->precio : 0;
      } else if ($notaingreso) {
        $badge = '<span class="badge badge-info"><i class="fas fa-plus-circle"></i> ' . ($notaingreso->tipoingreso ?: 'INGRESO') . '</span>';
        $numero = $notaingreso->codigo;
        $compra = $this->Controlador_model->get($notaingreso->compra, 'compra');
        if ($compra && $compra->proveedor) {
          $proveedor = $this->Controlador_model->get($compra->proveedor, 'proveedor');
          $razon = $proveedor ? $proveedor->nombre : 'PROVEEDOR';
        } else {
          $razon = 'AJUSTE / INVENTARIO';
        }
        $NID = $this->Controlador_model->getNIDetalle($data->producto, $data->notaingreso);
        $precio = $NID ? $NID->precio : 0;
      } else if ($notasalida) {
        $badge = '<span class="badge badge-danger"><i class="fas fa-minus-circle"></i> ' . ($notasalida->tiposalida ?: 'SALIDA') . '</span>';
        $numero = $notasalida->codigo;
        $usuario = $this->Controlador_model->get($notasalida->usuario, 'usuario');
        $razon = $usuario ? $usuario->nombre . ' ' . $usuario->apellido : 'SISTEMA';
        $NSD = $this->Controlador_model->getNSDetalle($data->producto, $data->notasalida);
        $precio = $NSD ? $NSD->precio : 0;
      }
      
      $ticket .= '<tr>
        <td>' . $i . '</td>
        <td>' . $badge . '</td>
        <td>' . date('d/m/Y', strtotime($fecha)) . '</td>
        <td><small class="font-weight-bold">' . $numero . '</small></td>
        <td><small>' . $razon . '</small></td>
        <td class="text-right text-muted">S/ ' . number_format($precio, 2) . '</td>
        <td class="text-center text-success font-weight-bold">' . ($data->tipo == 'ENTRADA' ? number_format($data->cantidad, 2) : '-') . '</td>
        <td class="text-center text-danger font-weight-bold">' . ($data->tipo == 'SALIDA' ? number_format($data->cantidad, 2) : '-') . '</td>
        <td class="text-center font-weight-bold bg-light">' . number_format($saldofinal, 2) . '</td>
      </tr>';
      $i++;
    }
    
    $ticket .= '<tr class="bg-light">
        <td colspan="5"></td>
        <td class="text-right font-weight-bold">TOTALES:</td>
        <td class="text-center text-success font-weight-bold">' . number_format($ingreso, 2) . '</td>
        <td class="text-center text-danger font-weight-bold">' . number_format($salida, 2) . '</td>
        <td class="text-center font-weight-bold text-navy" style="font-size: 1.1rem;">' . number_format($saldofinal, 2) . '</td>
    </tr></tbody></table></div>';
    echo $ticket;
  }


  public function imprimirnotaingresopdf($empresa, $fi, $ff)
  {
    $ticket = '<embed src="' . $this->url . '/notaingresodetallepdf/' . $empresa . '/' . $fi . '/' . $ff . '" type="application/pdf" width="100%" height="400"></embed>';
    echo $ticket;
  }

  public function notaingresodetallepdf($empresa, $fi, $ff)
  {
    $sucursal = $this->Controlador_model->get($this->empresa, 'empresa');
    //$notaingreso = $this->Controlador_model->get($id, $this->controlador);
    $notaingresodetalle = $this->Controlador_model->getDetalle($fi, $ff);
    $data = array(
      'sucursal' => $sucursal,
      //'data' => $notaingreso,
      'letras' => num_to_letras(500),
      'datas' => $notaingresodetalle,
    );
    $this->load->view('/notaingresodetallepdf', $data);
    $html = $this->output->get_output();
    $this->dompdf->loadHtml($html);
    $this->dompdf->setPaper('A4', 'portrait');
    $this->dompdf->render();
    $this->dompdf->stream("ordencompra.pdf", array("Attachment" => 0));
  }
}

/* End of file producto.php */
/* Location: ./system/application/controllers/producto.php */
