{% extends 'layoutManifiesto.html.twig' %}

{% block stylesheets %}
  {{ parent() }}
  <style>
    .table th, .table td { vertical-align: middle; }
    .form-check-input { cursor: pointer; }
    .form-check { display: flex; justify-content: center; align-items: center; }
    .table tr.table-danger > td { background-color: #f8d7da !important; }
    .text-dup { color: #842029 !important; font-weight: 600; }
  </style>
{% endblock %}

{% set m       = (manifiesto is defined and manifiesto) ? manifiesto : null %}
{% set maniId  = m ? m.id : 0 %}

{% block body %}
  {{ parent() }}

  <div class="container-fluid py-4">

    <!-- Breadcrumb y Título -->
    <nav aria-label="breadcrumb">
      <ol class="breadcrumb bg-white shadow-sm px-3 py-2">
        <li class="breadcrumb-item"><a href="{{ path('manifiesto_index') }}">Manifiestos</a></li>
        {% if maniId %}
          <li class="breadcrumb-item"><a href="{{ path('manifiesto_show', {'id': maniId}) }}">#{{ maniId }}</a></li>
        {% endif %}
        <li class="breadcrumb-item active">Agregar Facturas</li>
      </ol>
    </nav>

    <h5 class="text-primary fw-bold mb-3">
      <i class="ri-file-list-3-line"></i>
      {% if maniId %}Manifiesto #{{ maniId }} – {% endif %} Selección de Facturas
    </h5>

    <!-- Filtros -->
    <div class="card shadow-sm mb-4 border">
      <div class="card-body">
        <form id="formFiltrarFact" class="row g-3 mb-0">
          <div class="col-md-3">
            <label class="form-label small">Fecha inicial</label>
            <input type="date" name="fIni" class="form-control form-control-sm">
          </div>
          <div class="col-md-3">
            <label class="form-label small">Fecha final</label>
            <input type="date" name="fFin" class="form-control form-control-sm">
          </div>
          <div class="col-md-3">
            <label class="form-label small">Ruta (código o nombre)</label>
            <input type="text" name="ruta" class="form-control form-control-sm" placeholder="Ej: 12 o Central">
          </div>
          <div class="col-md-3 d-flex align-items-end gap-2">
            <button class="btn btn-primary btn-sm">
              <i class="ri-search-line"></i> Buscar
            </button>
            <button type="button" id="btnReset" class="btn btn-outline-secondary btn-sm">
              <i class="ri-refresh-line"></i>
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- Tabla de Facturas -->
    <div class="card shadow-sm">
      <div class="card-body p-0">
        <div class="table-responsive">
          <table id="tablaFacturas" class="table table-hover table-striped mb-0 tabla-fix">
            <thead class="table-light text-center">
              <tr>
                <th style="width: 40px">
                  <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="chkAll">
                  </div>
                </th>
                <th>Factura</th>
                <th>Pago</th>
                <th>Dirección</th>
                <th>Fecha</th>
                <th>Tienda</th>
                <th>Cliente</th>
                <th>Ruta</th>
                <th>Total</th>
              </tr>
            </thead>
            <tbody></tbody>
            <tfoot>
              <tr>
                <th colspan="7" class="text-end">TOTAL Q <span id="sumaTotal">0.00</span></th>
              </tr>
            </tfoot>
          </table>
        </div>
      </div>

      {% set backUrl = maniId
        ? path('manifiesto_show', {'id': maniId})
        : path('manifiesto_index') %}

      <div class="card-footer text-end no-print">
        <button id="btnGuardarFacturas" class="btn btn-success" disabled>
          <i class="ri-save-line"></i> Agregar al manifiesto
        </button>
        <a href="{{ backUrl }}" class="btn btn-outline-secondary">
          <i class="ri-arrow-left-line"></i> Regresar
        </a>
      </div>
    </div>

  </div>
{% endblock %}

{% block javascripts %}
  {{ parent() }}
  <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap4.min.js"></script>
  <script src="{{ asset('public/js/moment.js') }}"></script>

  <script>
    const maniId = {{ maniId }};
    var arrDetalle = [];
    const selected = {{ selFacturas|raw }};
    arrDetalle.push.apply(arrDetalle, selected);

    if (maniId > 0) {
      let tbl;

      function mostrarLoader(si) {
        $('#btnGuardarFacturas').prop('disabled', si);
        $('#btnGuardarFacturas').html(
          si ? '<span class="spinner-border spinner-border-sm"></span> Procesando…'
             : '<i class="ri-save-line"></i> Guardar cambios'
        );
      }

      function cargarFacturas(queryStr) {
        tbl.clear().draw();
        $('#chkAll').prop('checked', false);
        $('#btnGuardarFacturas').prop('disabled', true);
        actualizarTotal();

        $.get('{{ path("manifiesto_facturas_search", {"id": maniId}) }}', queryStr, function (r) {
          tbl.rows.add(r.data).draw();
          actualizarTotal();
        }, 'json').fail(function () {
          alert('Error al obtener facturas');
        });
      }

       function actualizarTotal() {
        var s = 0;
        if (!tbl) return;
        tbl.rows().every(function () {
          if ($(this.node()).find('.chkRow').is(':checked')) {
            s += parseFloat(this.data().total);
          }
        });
        $('#sumaTotal').text(s.toFixed(2));
      }

      $(function () {
        tbl = $('#tablaFacturas').DataTable({
          paging: true,
          info: false,
          order: [[3, 'desc']],
          language: { url: '//cdn.datatables.net/plug-ins/1.13.6/i18n/es-ES.json' },
          columns: [
            {
              data: null,
              orderable: false,
              className: 'text-center',
              render: function (d, t, row) {
                var checked = row.existing ? ' checked data-existing="1"' : '';
                var disabled = '';
                if (!row.existing && row.assigned_count && parseInt(row.assigned_count) > 0) {
                  disabled = ' disabled title="Factura ya está asociada a otro manifiesto"';
                }
                return '<div class="form-check">'
                     + '<input class="form-check-input chkRow" type="checkbox"'+ checked + disabled + '>'
                     + '</div>';
              }
            },
            { 
              data: 'factura',
              render: function(d, t, row) {
                if (row.assigned_count && parseInt(row.assigned_count) > 0) {
                  return '<span class="text-dup">'+ d +'</span> <span class="badge bg-danger" title="Ya en otro manifiesto">dup</span>';
                }
                return d;
              }
            },
            {
              data: 'payment_type',
              render: function (d) {
                return d === 'R' ? 'Crédito' : 'Contado';
              }
            },
            { data: 'cliente_direccion' },
            {
              data: 'fecha_factura',
              render: function (d) { return moment(d).format('DD/MM/YYYY'); }
            },
            { data: 'tienda' },
            { data: 'cliente_nombre' },
            { data: 'ruta_nombre' },
            {
              data: 'total',
              className: 'text-end',
              render: function (d) { return parseFloat(d).toFixed(2); }
            }
          ]
        });

        if (arrDetalle.length) {
          tbl.rows.add(arrDetalle).draw();
        }
        // Resaltar filas duplicadas
        tbl.on('draw', function(){
          tbl.rows().every(function(){
            var data = this.data() || {};
            if (data.assigned_count && parseInt(data.assigned_count) > 0) {
              $(this.node()).addClass('table-danger');
            }
          });
        });

        function toggleBtnGuardar() {
          var anyChecked = $('.chkRow:enabled:checked').length > 0;
          var anyUncheckedExisting = $('.chkRow[data-existing="1"]').not(':checked').length > 0;
          $('#btnGuardarFacturas').prop('disabled', !(anyChecked || anyUncheckedExisting));
        }

        $('#chkAll').on('change', function () {
          $('.chkRow:enabled').prop('checked', this.checked);
          toggleBtnGuardar();
          actualizarTotal();
        });

        $('#tablaFacturas tbody').on('change', '.chkRow', function () {
          toggleBtnGuardar();
          actualizarTotal();
        });

        $('#formFiltrarFact').submit(function (e) {
          e.preventDefault();
          cargarFacturas($(this).serialize());
        });

        $('#btnReset').click(function () {
          this.form.reset();
          tbl.clear().draw();
          $('#btnGuardarFacturas').prop('disabled', true);
          actualizarTotal();
        });

        $('#btnGuardarFacturas').click(function () {
          const toAdd = [];
          const toRemove = [];
          tbl.rows().every(function () {
            var data = this.data();
            var checked = $(this.node()).find('.chkRow').is(':checked');
            if (data.existing) {
              if (!checked) {
                toRemove.push(data);
              }
            } else if (checked) {
              toAdd.push(data);
            }
          });
          if (!toAdd.length && !toRemove.length) return;

          mostrarLoader(true);
          $.ajax({
            url: '{{ path("manifiesto_detalle_save", {"id": maniId}) }}',
            type: 'POST',
            data: {
              add: JSON.stringify(toAdd),
              remove: JSON.stringify(toRemove)
            },
            success: function (r) {
              if (r.success) {
                window.location.href = '{{ path("manifiesto_show", {"id": maniId}) }}';
              } else {
                if (r.requiresAuth) {
                  var motivo = '';
                  try { motivo = prompt(r.message + "\nIngrese motivo:", ''); } catch(e) { motivo = ''; }
                  if (!motivo) { alert('Motivo es obligatorio para solicitar autorizacion.'); return; }
                  $.post(r.requestUrl, { items: JSON.stringify(r.requiresAuth), motivo: motivo }, function(res) {
                    if (res && res.ok) {
                      alert('Solicitud de autorizacion enviada. Quedara pendiente de aprobacion.');
                    } else {
                      alert((res && res.error) ? res.error : 'No se pudo registrar la solicitud.');
                    }
                  }).fail(function(){ alert('Error al solicitar autorizacion'); });
                } else {
                  alert(r.error || 'Error');
                }
              }
            },
            error: function () { alert('Error de servidor'); },
            complete: function () { mostrarLoader(false); }
          });
        });
      });
    }
  </script>
{% endblock %}

