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

$user = current_user();
$flash_success = flash_get('success');
$flash_error = flash_get('error');

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

if ($_SERVER['REQUEST_METHOD']==='POST') {
  $taskId = (int)($_POST['task_id'] ?? 0);
  $second = trim($_POST['second_count_qty'] ?? '');
  $decision = $_POST['decision'] ?? 'pendiente';
  $comment = trim($_POST['comment'] ?? '');
  if ($taskId) {
    $qty = ($second==='') ? null : (int)$second;
    // upsert result
    $exists = one("SELECT id FROM recount_results WHERE task_id=?", [$taskId]);
    if ($exists) {
      q("UPDATE recount_results SET second_count_qty=?, decision=?, comment=?, monitor_user_id=?, created_at=NOW() WHERE task_id=?",
        [$qty, $decision, $comment, $user['id'], $taskId]);
    } else {
      q("INSERT INTO recount_results(task_id, second_count_qty, decision, comment, monitor_user_id, created_at) VALUES(?, ?, ?, ?, ?, NOW())",
        [$taskId, $qty, $decision, $comment, $user['id']]);
    }
    $newStatus = ($decision==='ok' || $decision==='diferencia_confirmada') ? 'listo' : 'en_revision';
    q("UPDATE recount_tasks SET status=?, updated_at=NOW() WHERE id=? AND session_id=? AND status<>'cancelado'",
      [$newStatus, $taskId, $sessionId]);
    flash_set('success','Guardado.');
  }
  redirect('monitor.php');
}

$tasks = all("
SELECT t.id, t.code, t.status, a.assigned_to, d.delivered_at,
       r.second_count_qty, r.decision, r.comment,
       IFNULL(c.qty_physical,0) AS qty_physical, IFNULL(si.qty_system,0) AS qty_system,
       (IFNULL(c.qty_physical,0) - IFNULL(si.qty_system,0)) AS diff,
       c.vitrinas
FROM recount_tasks t
LEFT JOIN (
  SELECT ra.task_id, u.username AS assigned_to
  FROM recount_assignments ra JOIN users u ON u.id=ra.assigned_to_user_id
  WHERE ra.active=1
) a ON a.task_id=t.id
LEFT JOIN recount_deliveries d ON d.task_id=t.id
LEFT JOIN recount_results r ON r.task_id=t.id
LEFT JOIN (
  SELECT p.code, COUNT(*) qty_physical, GROUP_CONCAT(DISTINCT p.vitrina ORDER BY p.vitrina SEPARATOR ', ') AS vitrinas
  FROM physical_items p WHERE p.session_id=? GROUP BY p.code
) c ON c.code=t.code
LEFT JOIN (
  SELECT ic.code, s.qty_system
  FROM system_items s JOIN item_codes ic ON ic.system_item_id=s.id
  WHERE s.session_id=?
) si ON si.code=t.code
WHERE t.session_id=? AND t.status IN ('entregado','en_revision','listo')
ORDER BY FIELD(t.status,'entregado','en_revision','listo'), t.updated_at DESC
LIMIT 500
", [$sessionId,$sessionId,$sessionId]);

ob_start();
?>
<div class="card p-3">
  <h4>Mesa Monitor</h4>
  <p class="text-white-50">Aquí llegan los artículos entregados. El monitor captura el 2º conteo y marca listo.</p>

  <div class="table-responsive" style="max-height:75vh;">
    <table class="table table-sm table-bordered">
      <thead>
        <tr>
          <th>ID</th><th>UPC</th><th>Asignado</th><th>Estado</th>
          <th>Sistema</th><th>Contado</th><th>Dif</th><th>Vitrinas</th>
          <th>2º conteo</th><th>Decisión</th><th>Comentario</th><th>Guardar</th>
        </tr>
      </thead>
      <tbody>
      <?php foreach($tasks as $t): ?>
        <tr>
          <td><?= h($t['id']) ?></td>
          <td><?= h($t['code']) ?></td>
          <td><?= h($t['assigned_to'] ?: '-') ?></td>
          <td><span class="badge badge-info"><?= h($t['status']) ?></span></td>
          <td><?= h($t['qty_system']) ?></td>
          <td><?= h($t['qty_physical']) ?></td>
          <td><strong><?= h((int)$t['diff']) ?></strong></td>
          <td style="max-width:220px;"><?= h($t['vitrinas'] ?: '-') ?></td>
          <td>
            <form method="post" class="form-inline m-0">
              <input type="hidden" name="task_id" value="<?= h($t['id']) ?>">
              <input class="form-control form-control-sm" style="width:90px;" name="second_count_qty" value="<?= h($t['second_count_qty']) ?>">
          </td>
          <td>
              <select class="form-control form-control-sm" name="decision" style="width:170px;">
                <option value="pendiente" <?= $t['decision']==='pendiente'?'selected':'' ?>>pendiente</option>
                <option value="ok" <?= $t['decision']==='ok'?'selected':'' ?>>ok</option>
                <option value="diferencia_confirmada" <?= $t['decision']==='diferencia_confirmada'?'selected':'' ?>>diferencia_confirmada</option>
              </select>
          </td>
          <td>
              <input class="form-control form-control-sm" name="comment" style="width:220px;" value="<?= h($t['comment']) ?>">
          </td>
          <td>
              <button class="btn btn-sm btn-success">Guardar</button>
            </form>
          </td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>
<?php
$content = ob_get_clean();
$title="Mesa Monitor";
require __DIR__ . '/../app/views/layout.php';
