<?php
require_once __DIR__ . '/../app/lib/auth.php';
require_once __DIR__ . '/../app/lib/util.php';
require_login();
require_role(['admin']);

$user = current_user();
$session = one("SELECT * FROM inventory_sessions ORDER BY id DESC LIMIT 1");
$sessionId = (int)$session['id'];

$counts = all("SELECT status, COUNT(*) c FROM recount_tasks WHERE session_id=? GROUP BY status", [$sessionId]);

$byEmp = all("
SELECT u.username, COUNT(*) total,
SUM(CASE WHEN t.status='entregado' THEN 1 ELSE 0 END) entregados,
SUM(CASE WHEN t.status='listo' THEN 1 ELSE 0 END) listos
FROM recount_assignments ra
JOIN users u ON u.id=ra.assigned_to_user_id
JOIN recount_tasks t ON t.id=ra.task_id
WHERE t.session_id=? AND ra.active=1
GROUP BY u.username
ORDER BY total DESC
", [$sessionId]);

ob_start();
?>
<div class="card p-3">
  <h4>Reportes</h4>

  <h5 class="mt-3">Estado de reconteos</h5>
  <ul class="text-white">
    <?php foreach($counts as $c): ?>
      <li><?= h($c['status']) ?>: <strong><?= h($c['c']) ?></strong></li>
    <?php endforeach; ?>
  </ul>

  <h5 class="mt-3">Rendimiento (asignaciones activas)</h5>
  <div class="table-responsive">
    <table class="table table-sm table-bordered">
      <thead><tr><th>Empleado</th><th>Total asignados</th><th>Entregados</th><th>Listos</th></tr></thead>
      <tbody>
      <?php foreach($byEmp as $r): ?>
        <tr>
          <td><?= h($r['username']) ?></td>
          <td><?= h($r['total']) ?></td>
          <td><?= h($r['entregados']) ?></td>
          <td><?= h($r['listos']) ?></td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <p class="text-white-50">Puedes pedirme que agregue más reportes (por vitrina, por diferencia, por categoría cuando importemos el inventario del sistema).</p>
</div>
<?php
$content = ob_get_clean();
$title="Reportes";
require __DIR__ . '/../app/views/layout.php';
