<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>KHE BESTIA Manager v1</title>
<style>
  * { box-sizing: border-box; font-family: Arial, sans-serif; }
  body { margin: 0; background: #f4f4f4; color: #333; }
  .contenedor { max-width: 600px; margin: auto; padding: 20px; }
  h1 { text-align: center; color: #d35400; font-size: 32px; margin-bottom: 5px; }
  h2 { text-align: center; color: #555; font-size: 20px; margin-top: 0; }
  .tarjeta { background: white; border-radius: 15px; padding: 20px; margin-top: 20px; box-shadow: 0px 4px 12px rgba(0,0,0,0.10); }
  h3 { margin-top: 0; color: #333; }
  textarea { width: 100%; height: 150px; padding: 15px; border-radius: 12px; border: 1px solid #ccc; font-size: 16px; resize: none; }
  button { width: 100%; margin-top: 15px; padding: 15px; border: none; border-radius: 12px; background: #d35400; color: white; font-size: 18px; font-weight: bold; cursor: pointer; }
  button:hover { background: #a04000; }

  .tabs { display: flex; gap: 8px; margin-top: 20px; flex-wrap: wrap; justify-content: center; }
  .tab-btn { padding: 10px 16px; border: none; border-radius: 10px; background: #ddd; color: #333; cursor: pointer; font-weight: bold; font-size: 14px; }
  .tab-btn:hover { background: #ccc; }
  .tab-btn.active { background: #d35400; color: white; }
  .tab-panel { display: none; }
  .tab-panel.active { display: block; }

  .dash-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
  .dash-card { background: #fff8f0; border-radius: 12px; padding: 16px; text-align: center; border: 2px solid #d35400; }
  .dash-card .icon { font-size: 1.6rem; margin-bottom: 4px; }
  .dash-card .value { font-size: 1.5rem; font-weight: bold; color: #d35400; }
  .dash-card .label { color: #777; font-size: 0.8rem; margin-top: 2px; }

  .preview-item { background: #fff8f0; border-radius: 10px; padding: 10px 14px; margin-bottom: 8px; display: flex; justify-content: space-between; align-items: center; border-left: 4px solid #d35400; }
  .preview-item .name { font-weight: bold; }
  .preview-item .det { color: #777; font-size: 0.85rem; }
  .preview-item .tot { font-weight: bold; color: #d35400; }

  .cliente-card { background: white; border-radius: 15px; padding: 16px; margin-top: 14px; box-shadow: 0px 4px 12px rgba(0,0,0,0.08); cursor: pointer; }
  .cliente-card:hover { border: 1px solid #d35400; }
  .cliente-header { display: flex; justify-content: space-between; align-items: center; }
  .cliente-header .nombre { font-size: 1.1rem; font-weight: bold; }
  .cliente-header .deuda { font-size: 1.3rem; font-weight: bold; color: #c0392b; }
  .cliente-header .pagado { color: #27ae60; }
  .cliente-sub { color: #777; font-size: 0.8rem; margin-top: 2px; }
  .cliente-detalles { display: none; margin-top: 12px; border-top: 1px solid #eee; padding-top: 12px; }
  .cliente-detalles.open { display: block; }
  table { width: 100%; border-collapse: collapse; font-size: 0.9rem; }
  th, td { padding: 8px 6px; text-align: left; }
  th { color: #777; font-weight: bold; border-bottom: 1px solid #ddd; }
  td { border-bottom: 1px solid #eee; }
  .btn-pago { padding: 8px 16px; background: #27ae60; color: white; border: none; border-radius: 8px; font-weight: bold; cursor: pointer; font-size: 0.85rem; width: auto; margin-top: 0; }
  .btn-pago:hover { background: #1e8449; }
  .badge { padding: 2px 8px; border-radius: 6px; font-size: 0.75rem; font-weight: bold; }
  .badge-pendiente { background: #fdecea; color: #c0392b; }
  .badge-pagado { background: #eafaf1; color: #27ae60; }

  .filtros { display: flex; gap: 10px; margin-bottom: 14px; flex-wrap: wrap; }
  .filtros input { padding: 10px 12px; border-radius: 10px; border: 1px solid #ccc; font-size: 14px; }
  .hist-row { background: white; border-radius: 10px; padding: 12px 14px; margin-bottom: 8px; display: flex; justify-content: space-between; align-items: center; border-left: 4px solid #2980b9; box-shadow: 0px 2px 6px rgba(0,0,0,0.05); }

  .export-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
  .export-card { background: white; border-radius: 15px; padding: 18px; text-align: center; box-shadow: 0px 4px 12px rgba(0,0,0,0.08); cursor: pointer; border: 2px solid transparent; }
  .export-card:hover { border-color: #27ae60; transform: translateY(-2px); }
  .export-card .icon { font-size: 2rem; margin-bottom: 8px; }
  .export-card .tit { font-weight: bold; }
  .export-card .sub { color: #777; font-size: 0.8rem; margin-top: 4px; }

  .toast { position: fixed; bottom: 20px; right: 20px; background: #27ae60; color: white; padding: 12px 20px; border-radius: 10px; font-weight: bold; z-index: 100; transform: translateY(100px); transition: transform 0.3s; }
  .toast.show { transform: translateY(0); }
  .empty-state { text-align: center; padding: 30px; color: #777; }
  .empty-state .emoji { font-size: 2.5rem; margin-bottom: 8px; }
  .top-row { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #eee; }
</style>
</head>
<body>
<div class="contenedor">
  <h1>🐗 KHE BESTIA Manager</h1>
  <h2>Tu cuaderno digital, con base de datos real</h2>

  <nav class="tabs">
    <button class="tab-btn active" data-tab="dashboard">📊 Dashboard</button>
    <button class="tab-btn" data-tab="pedidos">📝 Pedidos</button>
    <button class="tab-btn" data-tab="clientes">👥 Clientes</button>
    <button class="tab-btn" data-tab="historial">📁 Historial</button>
    <button class="tab-btn" data-tab="exportar">📤 Exportar</button>
  </nav>

  <section id="dashboard" class="tab-panel active">
    <div class="tarjeta">
      <div class="dash-grid">
        <div class="dash-card">
          <div class="icon">💰</div>
          <div class="value" id="dashPendiente">$0.00</div>
          <div class="label">Pendiente por Cobrar</div>
        </div>
        <div class="dash-card">
          <div class="icon">🧾</div>
          <div class="value" id="dashCobrado">$0.00</div>
          <div class="label">Cobrado Este Mes</div>
        </div>
        <div class="dash-card">
          <div class="icon">👤</div>
          <div class="value" id="dashClientesDeuda">0</div>
          <div class="label">Clientes con Deuda</div>
        </div>
        <div class="dash-card">
          <div class="icon">📦</div>
          <div class="value" id="dashTotalPedidos">0</div>
          <div class="label">Pedidos Registrados</div>
        </div>
      </div>
    </div>
    <div class="tarjeta">
      <h3>🏆 Top 5 Clientes con Mayor Consumo</h3>
      <div id="topClientes"></div>
    </div>
  </section>

  <section id="pedidos" class="tab-panel">
    <div class="tarjeta">
      <h3>📝 Ingresar Pedidos</h3>
      <p style="color:#777;font-size:0.85rem;margin-bottom:10px;">Escribe o dicta los pedidos (uno por línea):</p>
      <textarea id="pedidosInput" placeholder="Juan Pérez dos sándwiches y un agua aromática total 7.50
María Gómez una fritada total 6
Carlos Ruiz dos almuerzos total 8"></textarea>
      <button onclick="procesarPedidos()">⚡ Procesar Pedidos</button>
      <div class="preview-area" id="previewArea"></div>
    </div>
  </section>

  <section id="clientes" class="tab-panel">
    <div id="clientesLista"></div>
  </section>

  <section id="historial" class="tab-panel">
    <div class="tarjeta">
      <div class="filtros">
        <input type="text" id="histFiltroCliente" placeholder="🔍 Filtrar por cliente..." oninput="renderHistorial()">
        <input type="date" id="histDesde" onchange="renderHistorial()">
        <input type="date" id="histHasta" onchange="renderHistorial()">
      </div>
    </div>
    <div id="historialLista"></div>
  </section>

  <section id="exportar" class="tab-panel">
    <div class="tarjeta">
      <div class="export-grid">
        <div class="export-card" onclick="exportarExcel('todos')">
          <div class="icon">📊</div>
          <div class="tit">Exportar Todo</div>
          <div class="sub">Clientes, pedidos y pagos</div>
        </div>
        <div class="export-card" onclick="exportarExcel('pendientes')">
          <div class="icon">🔴</div>
          <div class="tit">Solo Pendientes</div>
          <div class="sub">Pedidos sin pagar</div>
        </div>
        <div class="export-card" onclick="exportarExcel('pagados')">
          <div class="icon">🟢</div>
          <div class="tit">Solo Pagados</div>
          <div class="sub">Historial de pagos</div>
        </div>
        <div class="export-card" onclick="exportarExcel('clientes')">
          <div class="icon">👥</div>
          <div class="tit">Resumen por Cliente</div>
          <div class="sub">Totales acumulados</div>
        </div>
      </div>
    </div>
  </section>

  <div class="toast" id="toast"></div>
</div>

<script>
  const API = '';

  document.querySelectorAll('.tab-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
      document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
      btn.classList.add('active');
      document.getElementById(btn.dataset.tab).classList.add('active');
      if (btn.dataset.tab === 'dashboard') renderDashboard();
      if (btn.dataset.tab === 'clientes') renderClientes();
      if (btn.dataset.tab === 'historial') renderHistorial();
    });
  });

  async function procesarPedidos() {
    const texto = document.getElementById('pedidosInput').value.trim();
    if (!texto) return;
    const lineas = texto.split('\n').filter(l => l.trim());
    const hoy = new Date().toLocaleDateString('es-ES');
    const procesados = [];

    for (const linea of lineas) {
      const match = linea.match(/(.+?)\s+total\s+(\d+(?:\.\d+)?)/i);
      if (!match) continue;
      let nombre = match[1].trim().replace(/\s+/g, ' ');
      const total = parseFloat(match[2]);
      const pedidoTexto = linea.replace(/\s+total\s+\d+(?:\.\d+)?/i, '').replace(nombre, '').trim();

      let res = await fetch(`${API}/api/clientes`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ nombre })
      });
      const cliente = await res.json();

      await fetch(`${API}/api/pedidos`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ cliente_id: cliente.id, fecha: hoy, pedido: pedidoTexto || linea.replace(/\s+total\s+\d+(?:\.\d+)?/i, '').trim(), total })
      });
      procesados.push({ nombre, pedido: pedidoTexto, total });
    }

    document.getElementById('pedidosInput').value = '';
    const preview = document.getElementById('previewArea');
    if (procesados.length === 0) {
      preview.innerHTML = '<div style="color:#c0392b;margin-top:10px;">⚠️ No se detectaron pedidos. Formato: Nombre pedido total X.XX</div>';
      return;
    }
    preview.innerHTML = '<h3 style="margin-top:10px;">✅ Pedidos procesados:</h3>' +
      procesados.map(p => `
        <div class="preview-item">
          <div><div class="name">${p.nombre}</div><div class="det">${p.pedido}</div></div>
          <div class="tot">$${p.total.toFixed(2)}</div>
        </div>
      `).join('');
    toast(`${procesados.length} pedido(s) registrado(s)`);
    renderDashboard();
  }

  async function renderClientes() {
    const cont = document.getElementById('clientesLista');
    const res = await fetch(`${API}/api/clientes`);
    const clientes = await res.json();

    if (clientes.length === 0) {
      cont.innerHTML = `<div class="empty-state"><div class="emoji">📒</div><div>Aún no hay clientes. Ve a "Pedidos" para empezar.</div></div>`;
      return;
    }

    cont.innerHTML = clientes.map(c => {
      const totalPendiente = parseFloat(c.total_pendiente || 0);
      const totalPagado = parseFloat(c.total_pagado || 0);
      return `
        <div class="cliente-card" onclick="toggleCliente(${c.id})">
          <div class="cliente-header">
            <div>
              <div class="nombre">${c.nombre}</div>
              <div class="cliente-sub">$${totalPagado.toFixed(2)} cobrado en total</div>
            </div>
            <div class="deuda ${totalPendiente === 0 ? 'pagado' : ''}">$${totalPendiente.toFixed(2)}</div>
          </div>
          <div class="cliente-detalles" id="det-${c.id}">
            <div id="pedidos-${c.id}"></div>
            ${totalPendiente > 0 ? `<div style="margin-top:12px;text-align:right;"><button class="btn-pago" onclick="event.stopPropagation();registrarPago(${c.id})">💰 Registrar Pago ($${totalPendiente.toFixed(2)})</button></div>` : ''}
          </div>
        </div>
      `;
    }).join('');
  }

  async function toggleCliente(id) {
    const el = document.getElementById('det-' + id);
    const pedidosEl = document.getElementById('pedidos-' + id);
    if (el.classList.contains('open')) {
      el.classList.remove('open');
      return;
    }
    const res = await fetch(`${API}/api/clientes/${id}/pedidos`);
    const pedidos = await res.json();
    pedidosEl.innerHTML = `
      <table>
        <thead><tr><th>Fecha</th><th>Pedido</th><th>Total</th><th>Estado</th></tr></thead>
        <tbody>
          ${pedidos.map(p => `
            <tr>
              <td>${p.fecha}</td>
              <td>${p.pedido}</td>
              <td>$${parseFloat(p.total).toFixed(2)}</td>
              <td><span class="badge ${p.estado === 'pendiente' ? 'badge-pendiente' : 'badge-pagado'}">${p.estado === 'pendiente' ? 'Pendiente' : 'Pagado'}</span></td>
            </tr>
          `).join('')}
        </tbody>
      </table>
    `;
    el.classList.add('open');
  }

  async function registrarPago(id) {
    const hoy = new Date().toLocaleDateString('es-ES');
    const res = await fetch(`${API}/api/pedidos/pagar`, {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ cliente_id: id, fecha_pago: hoy })
    });
    const data = await res.json();
    toast(`Pago registrado: ${data.pagados} pedido(s) pagado(s)`);
    renderClientes();
    renderDashboard();
  }

  async function renderDashboard() {
    const res = await fetch(`${API}/api/dashboard`);
    const d = await res.json();
    document.getElementById('dashPendiente').textContent = '$' + parseFloat(d.total_pendiente).toFixed(2);
    document.getElementById('dashCobrado').textContent = '$' + parseFloat(d.total_cobrado).toFixed(2);
    document.getElementById('dashClientesDeuda').textContent = d.clientes_deuda;
    document.getElementById('dashTotalPedidos').textContent = d.total_pedidos;

    document.getElementById('topClientes').innerHTML = (d.top_clientes || []).length === 0
      ? '<div class="empty-state"><div class="emoji">📊</div><div>Aún no hay datos</div></div>'
      : d.top_clientes.map((c, i) => `
        <div class="top-row">
          <span><b>#${i+1}</b> ${c.nombre}</span>
          <span style="color:#d35400;font-weight:bold;">$${parseFloat(c.total).toFixed(2)}</span>
        </div>
      `).join('');
  }

  async function renderHistorial() {
    const filtroCliente = document.getElementById('histFiltroCliente').value;
    const desde = document.getElementById('histDesde').value;
    const hasta = document.getElementById('histHasta').value;
    const cont = document.getElementById('historialLista');

    let url = `${API}/api/historial?`;
    if (filtroCliente) url += `cliente=${encodeURIComponent(filtroCliente)}&`;
    if (desde) url += `desde=${desde}&`;
    if (hasta) url += `hasta=${hasta}&`;

    const res = await fetch(url);
    const items = await res.json();

    if (items.length === 0) {
      cont.innerHTML = `<div class="empty-state"><div class="emoji">📂</div><div>No hay registros con esos filtros</div></div>`;
      return;
    }

    cont.innerHTML = items.map(h => `
      <div class="hist-row">
        <div>
          <div style="font-weight:bold;">${h.cliente}</div>
          <div style="color:#777;font-size:0.85rem;">${h.fecha} · ${h.pedido}</div>
        </div>
        <div style="text-align:right;">
          <div style="font-weight:bold;">$${parseFloat(h.total).toFixed(2)}</div>
          <span class="badge ${h.estado === 'pendiente' ? 'badge-pendiente' : 'badge-pagado'}">${h.estado === 'pendiente' ? 'Pendiente' : 'Pagado'}</span>
        </div>
      </div>
    `).join('');
  }

  function exportarExcel(tipo) {
    window.open(`${API}/api/exportar/${tipo}`);
    toast('📤 Descargando archivo...');
  }

  function toast(msg) {
    const t = document.getElementById('toast');
    t.textContent = msg;
    t.classList.add('show');
    setTimeout(() => t.classList.remove('show'), 2500);
  }

  renderDashboard();
</script>
</body>
</html>