<?php
// index.php — Nacionalizados
session_start();
if (!isset($_SESSION['ingreso']) || $_SESSION['ingreso'] !== 'YES') {
  header("Location: ../../views/index.php"); exit();
}
$usuario = $_SESSION['usuario'] ?? '';
$permiso = $_SESSION['permiso'] ?? '';
?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <title>SGO · Nacionalizados</title>

  <!-- Bootstrap 5 -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
  <!-- Font Awesome -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" rel="stylesheet"/>
  <!-- DataTables (DT + Buttons + Responsive) -->
  <link rel="stylesheet"
        href="https://cdn.datatables.net/v/bs5/jszip-3.10.1/dt-1.13.8/b-2.4.2/b-colvis-2.4.2/b-html5-2.4.2/b-print-2.4.2/r-2.5.0/datatables.min.css"/>

  <style>
    :root { --fz: 1.02rem; }
    body { font-size: var(--fz); }
    .table td, .table th { vertical-align: middle; }
    .btn-sm { padding: .25rem .5rem; }
    .modal-header { background:#f6f7fb; }
    table.dataTable tbody tr > * { padding-top:.35rem; padding-bottom:.35rem; }
    .dataTables_wrapper .dt-buttons { margin-bottom:.5rem; }
    /* Fila bloqueada (estado 8) */
    .row-disabled { opacity: .55; }
  </style>
</head>
<body>
<div class="container-fluid">
  <div class="row">
    <!-- Sidebar -->
    <?php include __DIR__ . '/partials/menu.php'; ?>

    <!-- Contenido principal -->
    <main class="col-md-9 ms-sm-auto col-lg-10 px-0">
      <!-- Topbar -->
      <?php include __DIR__ . '/partials/topbar.php'; ?>

      <div class="container-fluid py-2">
        <div class="card shadow-sm">
          <div class="card-header py-2">
            <i class="fa-solid fa-flag-checkered me-2"></i> Nacionalizados
          </div>
          <div class="card-body p-2">
            <div class="table-responsive">
              <table id="nacionalizados" class="table table-striped table-hover table-sm w-100">
                <thead class="table-info">
                  <tr>
                    <th>Nro.</th>
                    <th>Fecha</th>
                    <th>Cliente</th>
                    <th>Pedido</th>
                    <th>Embarque</th>
                    <th>SP</th>
                    <th>DAI</th>
                    <th>Acciones</th>
                  </tr>
                </thead>
                <tbody></tbody>
              </table>
            </div>
          </div>
        </div>
      </div>

      <!-- ================= Modal: Detalle de Factura ================= -->
      <div class="modal fade" id="mdlDetalle" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-scrollable">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title">
                <i class="fa-solid fa-file-invoice me-2"></i>
                Detalle de factura <span id="detNumero" class="text-primary"></span>
              </h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>

            <div class="modal-body p-2">
              <div id="detCabecera" class="small mb-2">
                <!-- Cabecera dinámica -->
              </div>

              <div class="table-responsive">
                <table class="table table-sm table-striped align-middle" id="tablaDetalle">
                  <thead class="table-light">
                    <tr>
                      <th class="text-center" style="width:36px">
                        <input type="checkbox" id="chkAllModal" class="form-check-input">
                      </th>
                      <th>#</th>
                      <th>Item</th>
                      <th>Marca</th>
                      <th>Chasis</th>
                      <th>Motor</th>
                      <th>Valor FOB</th>
                      <th>Flete</th>
                      <th>Seguro</th>
                      <th>Valor Aduana</th>
                    </tr>
                  </thead>
                  <tbody></tbody>
                </table>
              </div>

              <div id="detEmpty" class="alert alert-warning d-none mb-0">
                No hay ítems asociados a esta factura.
              </div>
            </div>

            <div class="modal-footer">
              <div class="me-auto small">
                Seleccionados: <span id="selCount" class="badge text-bg-primary">0</span>
              </div>
              <button class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">Cerrar</button>
              <button class="btn btn-success btn-sm" id="btnAbrirAprobar">
                <i class="fa-solid fa-floppy-disk"></i> Guardar
              </button>
            </div>
          </div>
        </div>
      </div>
      <!-- ============================================================= -->
    </main>
  </div>
</div>

<!-- ================= Modal: Nacionalización parcial (DAI 10) ================= -->
<div class="modal fade" id="mdlAprobar" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="fa-solid fa-file-shield me-2"></i> DAI 10 · Nacionalización parcial</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
      </div>

      <div class="modal-body">
        <input type="hidden" id="aprob_idfactura" />
        <div class="mb-3">
          <label for="aprob_dai10" class="form-label">Número de DAI 10 *</label>
          <input type="text" class="form-control" id="aprob_dai10" placeholder="Ej. 123-2025-0001234" />
        </div>

        <div class="mb-3">
          <label for="aprob_regimen" class="form-label">Régimen *</label>
          <select class="form-select" id="aprob_regimen">
            <option value="">Cargando...</option>
          </select>
        </div>

        <div class="small text-muted">
          Se aplicará a <span id="aprob_cnt" class="fw-bold">0</span> ítem(s) seleccionados.
        </div>
      </div>

      <div class="modal-footer">
        <button class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">Cancelar</button>
        <button class="btn btn-success btn-sm" id="btnConfirmarAprobar">
          <i class="fa-solid fa-check"></i> Confirmar
        </button>
      </div>
    </div>
  </div>
</div>

<!-- ===== JS ===== -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

<!-- DataTables (DT + Buttons + Responsive) -->
<script src="https://cdn.datatables.net/v/bs5/jszip-3.10.1/dt-1.13.8/b-2.4.2/b-colvis-2.4.2/b-html5-2.4.2/b-print-2.4.2/r-2.5.0/datatables.min.js"></script>
<!-- Dependencias para PDF -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>

<script>
  // ========= VARS =========
  $.fn.dataTable.ext.errMode = 'none';
  let currentDetalleFacturaId = 0;
  let detalleTieneSeleccionables = false; // viene de res.puede_guardar

  // ========= INIT =========
  $(document).ready(function () {
    cargarTablaNacionalizados();
  });

  // ========= TABLA PRINCIPAL =========
  function cargarTablaNacionalizados() {
    const $tbl = $('#nacionalizados');
    if ($.fn.DataTable.isDataTable($tbl)) {
      $tbl.DataTable().destroy();
    }

    $tbl.DataTable({
      processing: true,
      serverSide: true,
      autoWidth: false,
      ajax: {
        url: 'api/nacionalizados_list.php',
        type: 'POST',
        dataSrc: 'data',
        error: function (xhr) {
          console.error('Error AJAX:', xhr?.responseText || xhr.statusText);
        }
      },
      columns: [
        { data: 'numero',   defaultContent: '' },
        { data: 'fecha',    defaultContent: '' },
        { data: 'cliente',  defaultContent: '' },
        { data: 'pedido',   defaultContent: '' },
        { data: 'embarque', defaultContent: '' },
        { data: 'sp',       defaultContent: '' },
        { data: 'dai',      defaultContent: '' },
        {
          data: null,
          orderable: false,
          searchable: false,
          className: 'text-nowrap',
          render: function (data, type, row) {
            const id = row.id ?? 0;
            return `
              <button class="btn btn-info btn-sm me-1" title="Ver detalle" onclick="verDetalle(${id})">
                <i class="fa-solid fa-eye"></i>
              </button>`;
          }
        }
      ],
      order: [[0, 'desc']],
      responsive: true,
      pageLength: 10,
      language: { url: 'https://cdn.datatables.net/plug-ins/1.13.8/i18n/es-ES.json' },
      
    });
  }

  // ========= DETALLE (MODAL) =========
  function verDetalle(id) {
    if (!id) return;
    currentDetalleFacturaId = id;

    const modalEl = document.getElementById('mdlDetalle');
    const modal = new bootstrap.Modal(modalEl);

    // Reset visual
    $('#detNumero').text('');
    $('#detCabecera').html('<div class="text-muted"><i class="fa-solid fa-spinner fa-spin me-2"></i>Cargando...</div>');
    $('#tablaDetalle tbody').empty();
    $('#detEmpty').addClass('d-none');
    $('#selCount').text('0');
    $('#chkAllModal').prop('checked', false).prop('disabled', false);
    $('#btnAbrirAprobar').prop('disabled', true); // hasta cargar

    modal.show();

    $.ajax({
      url: 'api/nacionalizados_detalle.php',
      type: 'GET',
      dataType: 'json',
      data: { id: id },
      success: function(res) {
        if (!res || !res.success) {
          $('#detCabecera').html('<div class="text-danger">No se pudo cargar el detalle.</div>');
          return;
        }

        const h = res.cabecera || {};
        const r = res.resumen || {};
        $('#detNumero').text(h.numero || '');

        $('#detCabecera').html(`
          <div class="row g-1">
            <div class="col-md-3"><strong>Fecha:</strong> ${h.fecha ?? ''}</div>
            <div class="col-md-5"><strong>Cliente:</strong> ${h.cliente ?? ''}</div>
            <div class="col-md-4"><strong>Número:</strong> ${h.numero ?? ''}</div>
            <div class="col-md-3"><strong>Pedidos:</strong> ${r.pedido ?? ''}</div>
            <div class="col-md-3"><strong>Embarques:</strong> ${r.embarque ?? ''}</div>
            <div class="col-md-3"><strong>SP:</strong> ${r.sp ?? ''}</div>
            <div class="col-md-3"><strong>DAI:</strong> ${r.dai ?? ''}</div>
          </div>
        `);

        const items = Array.isArray(res.items) ? res.items : [];
        if (items.length === 0) {
          $('#detEmpty').removeClass('d-none');
          $('#btnAbrirAprobar').prop('disabled', true);
          $('#chkAllModal').prop('disabled', true);
          return;
        }

        function formatMoney(v){
          if (v === null || v === undefined || v === '') return '';
          const n = Number(v);
          if (Number.isNaN(n)) return v;
          return n.toLocaleString('es-EC', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        }

        const rows = items.map((it, i) => {
          const disabled  = it.bloqueado ? 'disabled' : '';
          const trClass   = it.bloqueado ? 'row-disabled' : '';
          const chk = `<input type="checkbox" class="form-check-input chkItemModal" value="${it.iddatadai}" ${disabled}>`;
          return `
            <tr class="${trClass}">
              <td class="text-center">${chk}</td>
              <td>${i + 1}</td>
              <td>${it.item ?? ''}</td>
              <td>${it.marca ?? ''}</td>
              <td>${it.chasis ?? ''}</td>
              <td>${it.motor ?? ''}</td>
              <td>${formatMoney(it.fobunitario)}</td>
              <td>${formatMoney(it.transporte)}</td>
              <td>${formatMoney(it.seguro)}</td>
              <td>${formatMoney(it.valoraduana)}</td>
            </tr>
          `;
        }).join('');

        $('#tablaDetalle tbody').html(rows);

        // Habilitar/Deshabilitar acciones según si hay seleccionables
        detalleTieneSeleccionables = !!res.puede_guardar;
        $('#btnAbrirAprobar').prop('disabled', !detalleTieneSeleccionables);

        const enabledTotal = $('.chkItemModal:not(:disabled)').length;
        if (enabledTotal === 0) {
          $('#chkAllModal').prop('disabled', true);
        }

        // Eventos de selección (delegados)
        $(document).off('change.chkItemModal').on('change.chkItemModal', '.chkItemModal', updateModalSelectedCount);
        $('#chkAllModal').off('change.chkAll').on('change.chkAll', function() {
          $('.chkItemModal:not(:disabled)').prop('checked', this.checked);
          updateModalSelectedCount();
        });

        // Inicializa contador
        updateModalSelectedCount();
      },
      error: function(xhr) {
        $('#detCabecera').html(`<div class="text-danger">Error: ${xhr.status} ${xhr.statusText}</div>`);
      }
    });
  }

  // Selección en modal detalle
  function updateModalSelectedCount() {
    const sel = $('.chkItemModal:not(:disabled):checked').length;
    const enabledTotal = $('.chkItemModal:not(:disabled)').length;

    $('#selCount').text(sel);
    $('#chkAllModal').prop('checked', sel > 0 && sel === enabledTotal);

    // Habilita Guardar solo si hay al menos un seleccionado
    $('#btnAbrirAprobar').prop('disabled', sel === 0);
  }

  function getModalSelectedIds() {
    return $('.chkItemModal:not(:disabled):checked').map((_, el) => $(el).val()).get();
  }

  // ========= MODAL APROBAR (DAI 10) =========
  // Abrir modal aprobar al clic en Guardar
  $(document).on('click', '#btnAbrirAprobar', function () {
    const ids = getModalSelectedIds();
    if (!ids || ids.length === 0) {
      alert('Selecciona al menos un ítem del detalle.');
      return;
    }

    // Reset campos
    $('#aprob_idfactura').val(currentDetalleFacturaId || 0);
    $('#aprob_dai10').val('');
    $('#aprob_cnt').text(ids.length);

    // Cargar opciones del select
    cargarRegimenes()
      .always(function () {
        new bootstrap.Modal(document.getElementById('mdlAprobar')).show();
      });
  });

  // Cargar Régimen (AJAX con fallback)
  function cargarRegimenes() {
    const $sel = $('#aprob_regimen').empty().append('<option value="">Cargando...</option>');
    return $.getJSON('api/regimenes_list.php', function (r) {
      $sel.empty().append('<option value="">Seleccione...</option>');
      if (r && r.success && Array.isArray(r.data)) {
        r.data.forEach(function (opt) {
          $sel.append(`<option value="${opt.id}">${opt.nombre}</option>`);
        });
      } else {
        $sel.html(`
          <option value="">Seleccione...</option>
          <option value="10">DAI 10</option>
          <option value="70">DAI 70</option>
          <option value="SIMPLE">SIMPLE</option>
        `);
      }
    }).fail(function () {
      $sel.html(`
        <option value="">Seleccione...</option>
        <option value="10">DAI 10</option>
        <option value="70">DAI 70</option>
        <option value="SIMPLE">SIMPLE</option>
      `);
    });
  }

  // Confirmar y enviar guardado parcial
  $(document).on('click', '#btnConfirmarAprobar', function () {
    const idfactura = parseInt($('#aprob_idfactura').val() || '0', 10);
    const dai10     = ($('#aprob_dai10').val() || '').trim();
    const regimen   = ($('#aprob_regimen').val() || '').trim();
    const ids       = getModalSelectedIds();

    if (!idfactura || ids.length === 0) { alert('Falta la factura o no hay ítems seleccionados.'); return; }
    if (!dai10) { alert('Ingrese el número de DAI 10.'); return; }
    if (!regimen) { alert('Seleccione un régimen.'); return; }

    $.post('api/nacionalizados_guardar_parcial.php', {
      idfactura: idfactura,
      dai10: dai10,
      regimen: regimen,
      'iddatadai[]': ids
    }, function (res) {
      if (res && res.success) {
        const m1 = bootstrap.Modal.getInstance(document.getElementById('mdlAprobar'));
        if (m1) m1.hide();
        $('#nacionalizados').DataTable().ajax.reload(null, false);
        alert('Guardado correctamente.');
      } else {
        alert(res?.message || 'No se pudo guardar.');
      }
    }, 'json').fail(function (xhr) {
      alert('Error: ' + (xhr?.responseText || xhr.statusText));
    });
  });
</script>
</body>
</html>
