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

$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");
if (!$session) { echo "No hay sesión."; exit; }
$sessionId = (int)$session['id'];

$show = $_GET['show'] ?? 'diff'; // diff|all|selected
$search = trim($_GET['q'] ?? '');

$params = [$sessionId, $sessionId];
$where = "";
if ($search !== '') {
  $where .= " AND (c.code LIKE ? OR si.item_name LIKE ?)";
  $params[] = "%$search%";
  $params[] = "%$search%";
}
if ($show === 'selected') {
  $where .= " AND t.id IS NOT NULL AND t.status <> 'cancelado'";
} elseif ($show === 'all') {
  // no filter
} else { // diff
  $where .= " AND (IFNULL(c.qty_physical,0) - IFNULL(si.qty_system,0)) <> 0";
}

$sql = "
SELECT 
  c.code,
  si.item_name,
  si.variation,
  si.category,
  IFNULL(si.qty_system,0) AS qty_system,
  IFNULL(c.qty_physical,0) AS qty_physical,
  (IFNULL(c.qty_physical,0) - IFNULL(si.qty_system,0)) AS diff,
  c.vitrinas,
  t.id AS task_id,
  t.status AS task_status,
  a.assigned_to,
  d.delivered_at,
  r.second_count_qty,
  r.decision
FROM
  (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
LEFT JOIN
  (SELECT s.id as system_item_id, s.session_id, s.item_name, s.variation, s.category, s.qty_system, ic.code
   FROM system_items s
   JOIN item_codes ic ON ic.system_item_id = s.id
   WHERE s.session_id=?) si
  ON si.code = c.code
LEFT JOIN recount_tasks t ON t.session_id = ? AND t.code = c.code AND t.status <> 'cancelado'
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
WHERE 1=1 $where
ORDER BY (t.id IS NULL) DESC, ABS(diff) DESC, c.code
LIMIT 500
";

$// params
$params = [$sessionId, $sessionId, $sessionId];
if ($search !== '') { $params[] = "%$search%"; $params[] = "%$search%"; }
$rows = all($sql, $params);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  require_role(['admin','monitor']);
  $action = $_POST['action'] ?? '';
  $code = trim($_POST['code'] ?? '');
  if ($code==='') redirect('dashboard.php');

  if ($action === 'select_recount') {
    require_role(['admin']); // only admin can create tasks
    // avoid duplicates
    $existing = one("SELECT id,status FROM recount_tasks WHERE session_id=? AND code=? AND status<>'cancelado' ORDER BY id DESC LIMIT 1", [$sessionId,$code]);
    if ($existing) {
      flash_set('error', "Ya existe reconteo para $code (estado: ".$existing['status'].")");
      redirect('dashboard.php?show='.$show.'&q='.urlencode($search));
    }
    q("INSERT INTO recount_tasks(session_id, code, status, created_by, created_at, updated_at) VALUES(?, ?, 'seleccionado', ?, NOW(), NOW())",
      [$sessionId, $code, $user['id']]);
    flash_set('success', "Seleccionado para reconteo: $code");
  } elseif ($action === 'cancel_task') {
    require_role(['admin']);
    $taskId = (int)($_POST['task_id'] ?? 0);
    if ($taskId>0) {
      q("UPDATE recount_tasks SET status='cancelado', updated_at=NOW() WHERE id=? AND session_id=?", [$taskId,$sessionId]);
      q("UPDATE recount_assignments SET active=0 WHERE task_id=?", [$taskId]);
      flash_set('success', "Reconteo cancelado.");
    }
  }
  redirect('dashboard.php?show='.$show.'&q='.urlencode($search));
}

ob_start();
?>
<div class="card p-3">
  <div class="d-flex flex-wrap align-items-center">
    <h4 class="mb-0 mr-3">Inventarios <?= h($session['name']) ?></h4>
    <div class="ml-auto">
      <a class="btn btn-light btn-sm" href="dashboard.php?show=diff">Solo diferencias</a>
      <a class="btn btn-light btn-sm" href="dashboard.php?show=all">Todos</a>
      <a class="btn btn-light btn-sm" href="dashboard.php?show=selected">Seleccionados</a>
    </div>
  </div>

  <form class="form-inline mt-2" method="get">
    <input type="hidden" name="show" value="<?= h($show) ?>">
    <input class="form-control mr-2" name="q" placeholder="Buscar UPC o nombre" value="<?= h($search) ?>" style="min-width:260px;">
    <button class="btn btn-warning btn-sm">Buscar</button>
    <a class="btn btn-outline-light btn-sm ml-2" href="dashboard.php?show=<?= h($show) ?>">Limpiar</a>
  </form>

  <div class="table-responsive mt-3" style="max-height:70vh;">
    <table class="table table-sm table-bordered">
      <thead>
        <tr>
          <th>UPC</th>
          <th>Artículo</th>
          <th>Sistema</th>
          <th>Contado</th>
          <th>Diferencia</th>
          <th>Vitrinas</th>
          <th>Estado reconteo</th>
          <th>Acción</th>
        </tr>
      </thead>
      <tbody>
      <?php foreach ($rows as $r):
        $diff = (int)$r['diff'];
        $cls = '';
        if ($diff===0) $cls='row-green';
        else $cls='row-orange';
      ?>
        <tr class="<?= $cls ?>">
          <td><?= h($r['code']) ?></td>
          <td><?= h($r['item_name'] ?: '(sin nombre en sistema)') ?><?= $r['variation'] ? ' - '.h($r['variation']) : '' ?></td>
          <td><?= h($r['qty_system']) ?></td>
          <td><?= h($r['qty_physical']) ?></td>
          <td><strong><?= h($diff) ?></strong></td>
          <td style="max-width:260px;"><?= h($r['vitrinas']) ?></td>
          <td>
            <?php if ($r['task_id']): ?>
              <span class="badge badge-info badge-status"><?= h($r['task_status']) ?></span>
              <?php if ($r['assigned_to']): ?><span class="badge badge-light"><?= h($r['assigned_to']) ?></span><?php endif; ?>
              <?php if ($r['delivered_at']): ?><span class="badge badge-warning">entregado</span><?php endif; ?>
              <?php if ($r['decision']): ?><span class="badge badge-success"><?= h($r['decision']) ?></span><?php endif; ?>
            <?php else: ?>
              <span class="badge badge-secondary badge-status">no seleccionado</span>
            <?php endif; ?>
          </td>
          <td>
            <?php if (!$r['task_id']): ?>
              <?php if ($user['role']==='admin'): ?>
                <form method="post" class="m-0">
                  <input type="hidden" name="action" value="select_recount">
                  <input type="hidden" name="code" value="<?= h($r['code']) ?>">
                  <button class="btn btn-sm btn-success">Seleccionar</button>
                </form>
              <?php else: ?>
                <span class="text-muted">Solo admin</span>
              <?php endif; ?>
            <?php else: ?>
              <?php if ($user['role']==='admin'): ?>
                <form method="post" class="m-0" onsubmit="return confirm('¿Cancelar este reconteo?');">
                  <input type="hidden" name="action" value="cancel_task">
                  <input type="hidden" name="task_id" value="<?= h($r['task_id']) ?>">
                  <button class="btn btn-sm btn-danger">Cancelar</button>
                </form>
              <?php else: ?>
                <a class="btn btn-sm btn-outline-light" href="assign.php">Ver</a>
              <?php endif; ?>
            <?php endif; ?>
          </td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <small class="text-white-50">Mostrando hasta 500 filas. Ajusta con búsqueda y filtros.</small>
</div>
<?php
$content = ob_get_clean();
$title = "Inventario";
require __DIR__ . '/../app/views/layout.php';
