<?php
if (count(get_included_files()) === 1) { http_response_code(403); exit('Forbidden'); }
$page_title = 'Vale Admin — Ventas & Finanzas';

ob_start();
?>
<div class="dashboard-container">
  <?php $adminNav = 'sales'; require __DIR__ . '/sidebar.php'; ?>

  <main class="main-content">
    <header class="header-bar">
      <h2>Ventas &amp; Finanzas</h2>
      <div style="font-size:.82rem;color:var(--color-text-muted)"><?= date('d M Y') ?></div>
    </header>

    <div style="flex:1;overflow-y:auto;padding:1.5rem 2rem">

      <!-- KPIs globales -->
      <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:.75rem;margin-bottom:2rem">
        <?php
        $kpis = [
          ['MRR Total',           '$'.number_format($kpi['mrr_total'] ?? 0, 0),   '#1E7A4D'],
          ['Activos',             (int)($kpi['activos']    ?? 0),                  '#A8331A'],
          ['Trial',               (int)($kpi['trial']      ?? 0),                  '#B07B1A'],
          ['Vencidos (past_due)', (int)($kpi['past_due']   ?? 0),                  '#C0392B'],
          ['Comisiones pendientes','$'.number_format($kpi['comm_pend'] ?? 0, 2),   '#0078C8'],
          ['Comisiones pagadas',  '$'.number_format($kpi['comm_paid']  ?? 0, 2),   '#665D55'],
        ];
        foreach ($kpis as [$lbl, $val, $color]): ?>
          <div style="background:#fff;border:1px solid var(--color-border);border-radius:12px;padding:.9rem 1.2rem;box-shadow:0 1px 4px rgba(0,0,0,.04)">
            <div style="font-family:var(--font-headings);font-size:1.65rem;font-weight:600;color:<?= $color ?>;line-height:1"><?= $val ?></div>
            <div style="font-size:.72rem;color:var(--color-text-muted);text-transform:uppercase;letter-spacing:.05em;margin-top:5px"><?= $lbl ?></div>
          </div>
        <?php endforeach; ?>
      </div>

      <!-- MRR por plan -->
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;margin-bottom:2rem">
        <div style="background:#fff;border:1px solid var(--color-border);border-radius:12px;padding:1.25rem">
          <h4 style="font-family:var(--font-headings);margin:0 0 1rem;font-size:1rem">MRR por plan</h4>
          <table style="width:100%;font-size:.84rem;border-collapse:collapse">
            <thead><tr style="color:var(--color-text-muted);text-align:left">
              <th style="padding:.4rem .5rem">Plan</th>
              <th style="padding:.4rem .5rem">Negocios</th>
              <th style="padding:.4rem .5rem">MRR</th>
            </tr></thead>
            <tbody>
              <?php foreach ($mrrByPlan as $row): ?>
              <tr style="border-top:1px solid var(--color-border)">
                <td style="padding:.45rem .5rem;font-weight:700;text-transform:uppercase;font-size:.78rem"><?= htmlspecialchars($row['plan']) ?></td>
                <td style="padding:.45rem .5rem"><?= (int)$row['cnt'] ?></td>
                <td style="padding:.45rem .5rem;font-weight:700;color:var(--color-verde)">$<?= number_format($row['total_mrr'], 0) ?></td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>

        <div style="background:#fff;border:1px solid var(--color-border);border-radius:12px;padding:1.25rem">
          <h4 style="font-family:var(--font-headings);margin:0 0 1rem;font-size:1rem">MRR por método de cobro</h4>
          <table style="width:100%;font-size:.84rem;border-collapse:collapse">
            <thead><tr style="color:var(--color-text-muted);text-align:left">
              <th style="padding:.4rem .5rem">Método</th>
              <th style="padding:.4rem .5rem">Negocios</th>
              <th style="padding:.4rem .5rem">MRR</th>
            </tr></thead>
            <tbody>
              <?php foreach ($mrrByMethod as $row): ?>
              <tr style="border-top:1px solid var(--color-border)">
                <td style="padding:.45rem .5rem;font-weight:700;text-transform:uppercase;font-size:.78rem"><?= htmlspecialchars($row['billing_method'] ?? 'sin cobro') ?></td>
                <td style="padding:.45rem .5rem"><?= (int)$row['cnt'] ?></td>
                <td style="padding:.45rem .5rem;font-weight:700;color:var(--color-verde)">$<?= number_format($row['total_mrr'], 0) ?></td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>

      <!-- Rendimiento por vendedor -->
      <h3 style="font-family:var(--font-headings);margin:0 0 .9rem;font-size:1.05rem">Rendimiento por vendedor</h3>
      <table style="width:100%;border-collapse:collapse;background:#fff;border-radius:12px;overflow:hidden;font-size:.84rem;box-shadow:0 1px 4px rgba(0,0,0,.05);margin-bottom:2rem">
        <thead>
          <tr style="background:var(--color-tierra);color:#FBF6EE;text-align:left">
            <th style="padding:.65rem 1rem">Vendedor</th>
            <th style="padding:.65rem 1rem">Negocios</th>
            <th style="padding:.65rem 1rem">Activos</th>
            <th style="padding:.65rem 1rem">MRR generado</th>
            <th style="padding:.65rem 1rem">Comisión pendiente</th>
            <th style="padding:.65rem 1rem">Comisión pagada</th>
            <th style="padding:.65rem 1rem">Acciones</th>
          </tr>
        </thead>
        <tbody>
          <?php if (empty($sellers)): ?>
            <tr><td colspan="7" style="padding:1.5rem;text-align:center;color:var(--color-text-muted)">Sin vendedores todavía.</td></tr>
          <?php else: foreach ($sellers as $s): ?>
          <tr style="border-top:1px solid var(--color-border)">
            <td style="padding:.65rem 1rem">
              <div style="font-weight:700"><?= htmlspecialchars($s['nombre']) ?></div>
              <div style="font-size:.75rem;color:var(--color-text-muted)"><?= htmlspecialchars($s['email']) ?></div>
            </td>
            <td style="padding:.65rem 1rem"><?= (int)$s['total_tenants'] ?></td>
            <td style="padding:.65rem 1rem"><?= (int)$s['activos'] ?></td>
            <td style="padding:.65rem 1rem;font-weight:700;color:var(--color-verde)">$<?= number_format($s['mrr'], 0) ?></td>
            <td style="padding:.65rem 1rem;font-weight:700;color:#B07B1A">$<?= number_format($s['comm_pend'], 2) ?></td>
            <td style="padding:.65rem 1rem;color:var(--color-text-muted)">$<?= number_format($s['comm_paid'], 2) ?></td>
            <td style="padding:.65rem 1rem">
              <a href="/admin/seller?id=<?= (int)$s['id'] ?>" style="font-size:.78rem;color:var(--color-barro);font-weight:600;text-decoration:none">Ver pipeline →</a>
            </td>
          </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>

      <!-- Movimientos recientes (todas las comisiones) -->
      <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:.9rem">
        <h3 style="font-family:var(--font-headings);margin:0;font-size:1.05rem">Movimientos recientes</h3>
        <form method="GET" style="display:flex;gap:.5rem;align-items:center">
          <select name="filter_pagada" onchange="this.form.submit()" style="font-size:.8rem;padding:.35rem .7rem;border:1px solid var(--color-border);border-radius:7px;font-family:var(--font-body)">
            <option value="" <?= empty($_GET['filter_pagada'])?'selected':'' ?>>Todos</option>
            <option value="0" <?= ($_GET['filter_pagada']??'') === '0' ?'selected':'' ?>>Pendientes</option>
            <option value="1" <?= ($_GET['filter_pagada']??'') === '1' ?'selected':'' ?>>Pagadas</option>
          </select>
          <select name="filter_tipo" onchange="this.form.submit()" style="font-size:.8rem;padding:.35rem .7rem;border:1px solid var(--color-border);border-radius:7px;font-family:var(--font-body)">
            <option value="" <?= empty($_GET['filter_tipo'])?'selected':'' ?>>Todos los tipos</option>
            <option value="setup" <?= ($_GET['filter_tipo']??'')==='setup'?'selected':'' ?>>Setup</option>
            <option value="mrr"   <?= ($_GET['filter_tipo']??'')==='mrr'?'selected':'' ?>>MRR</option>
          </select>
        </form>
      </div>

      <table style="width:100%;border-collapse:collapse;background:#fff;border-radius:12px;overflow:hidden;font-size:.84rem;box-shadow:0 1px 4px rgba(0,0,0,.05);margin-bottom:1.5rem">
        <thead>
          <tr style="background:var(--color-tierra);color:#FBF6EE;text-align:left">
            <th style="padding:.65rem 1rem">Vendedor</th>
            <th style="padding:.65rem 1rem">Negocio</th>
            <th style="padding:.65rem 1rem">Tipo</th>
            <th style="padding:.65rem 1rem">Período</th>
            <th style="padding:.65rem 1rem">Monto</th>
            <th style="padding:.65rem 1rem">Estado</th>
            <th style="padding:.65rem 1rem">Fecha</th>
            <th style="padding:.65rem 1rem">Acción</th>
          </tr>
        </thead>
        <tbody>
          <?php if (empty($commissions)): ?>
            <tr><td colspan="8" style="padding:1.5rem;text-align:center;color:var(--color-text-muted)">Sin movimientos.</td></tr>
          <?php else: foreach ($commissions as $c): ?>
          <tr style="border-top:1px solid var(--color-border)">
            <td style="padding:.65rem 1rem;font-weight:600"><?= htmlspecialchars($c['seller_nombre'] ?? '—') ?></td>
            <td style="padding:.65rem 1rem"><?= htmlspecialchars($c['tenant_name'] ?? '#'.$c['tenant_id']) ?></td>
            <td style="padding:.65rem 1rem">
              <span style="background:<?= $c['tipo']==='setup'?'rgba(168,51,26,.1)':'rgba(0,120,200,.1)' ?>;color:<?= $c['tipo']==='setup'?'var(--color-barro)':'#0078C8' ?>;font-size:.7rem;font-weight:700;border-radius:99px;padding:2px 9px">
                <?= strtoupper($c['tipo']) ?>
              </span>
            </td>
            <td style="padding:.65rem 1rem;font-size:.8rem"><?= $c['periodo'] ?: '—' ?></td>
            <td style="padding:.65rem 1rem;font-weight:700;color:var(--color-verde)">$<?= number_format($c['monto'], 2) ?></td>
            <td style="padding:.65rem 1rem">
              <span style="background:<?= $c['pagada']?'rgba(30,122,77,.1)':'rgba(224,163,62,.1)' ?>;color:<?= $c['pagada']?'#1E7A4D':'#B07B1A' ?>;font-size:.7rem;font-weight:700;border-radius:99px;padding:2px 9px">
                <?= $c['pagada'] ? 'Pagada' : 'Pendiente' ?>
              </span>
            </td>
            <td style="padding:.65rem 1rem;font-size:.78rem;color:var(--color-text-muted)"><?= date('d/m/Y', strtotime($c['created_at'])) ?></td>
            <td style="padding:.65rem 1rem">
              <?php if (!$c['pagada']): ?>
              <form method="POST" action="/admin/commissions/pay" style="display:inline">
                <input type="hidden" name="id" value="<?= (int)$c['id'] ?>">
                <button type="submit" style="font-size:.75rem;background:var(--color-verde);color:#fff;border:none;border-radius:6px;padding:.3rem .7rem;cursor:pointer;font-family:var(--font-body)">
                  Marcar pagada
                </button>
              </form>
              <?php else: ?>
                <span style="font-size:.75rem;color:var(--color-text-muted)">✓</span>
              <?php endif; ?>
            </td>
          </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>

    </div><!-- /body -->
  </main>
</div>

<?php
$content = ob_get_clean();
require dirname(__DIR__) . '/layout.php';
