/* ============================================================
   views/vouchers.js — Vouchers del distribuidor
   ============================================================ */

function renderVouchers(el) {
  el.dataset.viewTitle = 'Mis Vouchers';
  if (vipGuard(el)) return;

  apiGet('/voucher/list', function(data) {
    var todos    = data.vouchers || [];

    // Filtrar últimos 6 meses
    var corte = new Date();
    corte.setMonth(corte.getMonth() - 6);
    var vouchers = todos.filter(function(v) {
      if (!v.fecha_cre) return true;
      return new Date(v.fecha_cre) >= corte;
    });

    el.innerHTML =
      '<div class="page-header">' +
        '<div class="section-title" style="margin:0">Mis Vouchers</div>' +
      '</div>' +

      // Verificar voucher
      '<div class="card mb-16">' +
        '<div class="card-header"><span class="card-title">Verificar Voucher</span></div>' +
        '<div class="card-body">' +
          '<div style="display:flex;gap:8px;flex-wrap:wrap">' +
            '<input type="text" id="voucherInput" class="form-control" placeholder="Código de voucher..." style="flex:1;min-width:180px" autocapitalize="characters">' +
            '<button class="btn btn-primary" onclick="verifyVoucher()">Verificar</button>' +
          '</div>' +
          '<div id="voucherResult" style="margin-top:12px"></div>' +
        '</div>' +
      '</div>' +

      // Lista
      '<div class="section-title">Mis Vouchers — últimos 6 meses (' + vouchers.length + ')</div>' +
      (vouchers.length === 0
        ? '<div class="empty-state" style="background:var(--white);border-radius:var(--radius);border:1px solid var(--border);padding:40px">' +
            '<div class="empty-icon">🎫</div><h3>Sin vouchers</h3><p>No tienes vouchers registrados.</p>' +
          '</div>'
        : '<div id="vouchersList">' + vouchersList(vouchers) + '</div>'
      );

    // Wire clicks en cada voucher
    if (vouchers.length > 0) {
      var cards = document.querySelectorAll('[data-voucherid]');
      for (var i = 0; i < cards.length; i++) {
        (function(card) {
          card.addEventListener('click', function() {
            showVoucherDetalle(parseInt(card.dataset.voucherid));
          });
        })(cards[i]);
      }
    }

  }, function(err) {
    el.innerHTML = errorState('Error al cargar vouchers', err);
  });
}

function vouchersList(vouchers) {
  var html = '';
  for (var i = 0; i < vouchers.length; i++) {
    var v      = vouchers[i];
    var usado  = v.status === 1;
    var agotado= v.restante <= 0;
    var estado = agotado ? 'Agotado' : (usado ? 'Usado' : 'Disponible');
    var desc   = v.descripcion || v.referencia || 'Voucher #' + v.idv;

    html +=
      '<div class="voucher-card" data-voucherid="' + v.idv + '" style="cursor:pointer;' + (usado || agotado ? 'opacity:.7' : '') + '">' +
        '<div class="voucher-status">' + estado + '</div>' +
        '<div class="voucher-code">🎫 #' + v.idv + '</div>' +
        '<div style="font-size:13px;opacity:.85;margin-bottom:10px">' + escHtml(desc) + '</div>' +
        '<div style="display:flex;gap:24px;flex-wrap:wrap">' +
          '<div>' +
            '<div style="font-size:11px;opacity:.75;text-transform:uppercase;letter-spacing:.5px">Total</div>' +
            '<div class="voucher-amount" style="font-size:22px">' + formatMXN(v.total) + '</div>' +
          '</div>' +
          '<div>' +
            '<div style="font-size:11px;opacity:.75;text-transform:uppercase;letter-spacing:.5px">Disponible</div>' +
            '<div style="font-size:22px;font-weight:800">' + formatMXN(v.restante) + '</div>' +
          '</div>' +
        '</div>' +
        '<div class="voucher-info" style="margin-top:10px">' +
          (v.fecha_cre ? '📅 Creado: ' + formatDate(v.fecha_cre) : '') +
          ' · Toca para ver detalle →' +
        '</div>' +
      '</div>';
  }
  return html;
}

function showVoucherDetalle(idv) {
  showModal('Detalle de Voucher',
    '<div class="loading-overlay" style="padding:24px"><div class="spinner-lg"></div></div>',
    ''
  );

  apiGet('/voucher/detalle-dist?idv=' + idv, function(data) {
    var v    = data.voucher || {};
    var usos = data.usos   || [];

    var usado  = v.status === 1;
    var agotado= v.restante <= 0;
    var estado = agotado ? 'Agotado' : (usado ? 'Usado' : 'Disponible');
    var desc   = v.descripcion || v.referencia || 'Voucher #' + v.idv;

    var body =
      // Resumen del voucher
      '<div style="background:var(--navy);border-radius:var(--radius);padding:20px;color:var(--white);margin-bottom:20px">' +
        '<div style="font-size:12px;opacity:.8;margin-bottom:4px">' + escHtml(desc) + ' · ' + escHtml(estado) + '</div>' +
        '<div style="display:flex;gap:24px;flex-wrap:wrap">' +
          '<div><div style="font-size:11px;opacity:.75">Total</div><div style="font-size:24px;font-weight:800">' + formatMXN(v.total) + '</div></div>' +
          '<div><div style="font-size:11px;opacity:.75">Disponible</div><div style="font-size:24px;font-weight:800">' + formatMXN(v.restante) + '</div></div>' +
          '<div><div style="font-size:11px;opacity:.75">Usado</div><div style="font-size:24px;font-weight:800">' + formatMXN(v.total - v.restante) + '</div></div>' +
        '</div>' +
        (v.fecha_cre ? '<div style="font-size:12px;opacity:.75;margin-top:10px">📅 Creado: ' + formatDate(v.fecha_cre) + '</div>' : '') +
      '</div>' +

      // Notas donde se usó
      '<div style="font-size:14px;font-weight:700;color:var(--navy);margin-bottom:10px">Notas en que se usó este voucher</div>' +
      (usos.length === 0
        ? '<div class="empty-state" style="padding:24px"><div class="empty-icon">📋</div><h3>Sin usos registrados</h3><p>Este voucher aún no ha sido aplicado en ninguna nota.</p></div>'
        : '<div class="table-wrap"><table>' +
            '<thead><tr><th>Transacción</th><th>Fecha</th><th>Distribuidor</th><th>Monto aplicado</th></tr></thead><tbody>' +
            usos.map(function(u) {
              return '<tr>' +
                '<td style="font-size:12px;color:var(--text-muted)">#' + u.idtransacciones + '</td>' +
                '<td>' + formatDate(u.fechat) + '</td>' +
                '<td style="font-size:13px">' + escHtml(u.nombre_completo) + '</td>' +
                '<td class="money green">' + formatMXN(u.monto) + '</td>' +
              '</tr>';
            }).join('') +
            '</tbody></table></div>'
      );

    document.getElementById('modalTitle').textContent = 'Voucher #' + v.idv;
    document.getElementById('modalBody').innerHTML = body;
    document.getElementById('modalFooter').innerHTML =
      '<button class="btn btn-outline" onclick="hideModal()">Cerrar</button>';

  }, function(err) {
    document.getElementById('modalBody').innerHTML =
      '<div class="empty-state"><div class="empty-icon">⚠️</div><h3>Error</h3><p>' + escHtml(err) + '</p></div>';
    document.getElementById('modalFooter').innerHTML =
      '<button class="btn btn-outline" onclick="hideModal()">Cerrar</button>';
  });
}

function verifyVoucher() {
  var code  = document.getElementById('voucherInput').value.trim().toUpperCase();
  var resEl = document.getElementById('voucherResult');
  if (!code) { toast('Ingresa un código de voucher.', 'warning'); return; }
  resEl.innerHTML = '<span class="text-muted text-sm">Verificando...</span>';

  apiGet('/voucher/verify?codigo=' + encodeURIComponent(code), function(data) {
    resEl.innerHTML =
      '<div style="background:#f0faf5;border:1px solid #a8ddc0;border-radius:var(--radius-sm);padding:12px 16px">' +
        '<div style="font-weight:700;color:var(--success)">✓ Voucher válido</div>' +
        '<div style="font-size:13px;margin-top:4px">' +
          'Monto: <strong>' + formatMXN(data.monto || data.total || 0) + '</strong>' +
          (data.descripcion ? ' · ' + escHtml(data.descripcion) : '') +
        '</div>' +
      '</div>';
  }, function(err) {
    resEl.innerHTML =
      '<div style="background:#fdf0ef;border:1px solid #f5c6c3;border-radius:var(--radius-sm);padding:12px 16px;color:var(--danger)">' +
        '✗ ' + escHtml(err) +
      '</div>';
  });
}
