<?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'];

$employees = all("SELECT id, username FROM users WHERE role='empleado' AND active=1 ORDER BY username");

if ($_SERVER['REQUEST_METHOD']==='POST') {
  $taskId = (int)($_POST['task_id'] ?? 0);
  $empId = (int)($_POST['emp_id'] ?? 0);
  if ($taskId && $empId) {
    // deactivate previous
    q("UPDATE recount_assignments SET active=0 WHERE task_id=?", [$taskId]);
    q("INSERT INTO recount_assignments(task_id, assigned_to_user_id, assigned_by_user_id, assigned_at, active) VALUES(?, ?, ?, NOW(), 1)",
      [$taskId, $empId, $user['id']]);
    q("UPDATE recount_tasks SET status='asignado', updated_at=NOW() WHERE id=? AND session_id=? AND status<>'cancelado'", [$taskId,$sessionId]);
    flash_set('success', 'Asignado correctamente.');
  } else {
    flash_set('error', 'Selecciona empleado.');
  }
  redirect('assign.php');
}

$tasks = all("
SELECT t.id, t.code, t.status, t.created_at, u.username AS creado_por,
       a.assigned_to, d.delivered_at
FROM recount_tasks t
JOIN users u ON u.id = t.created_by
LEFT JOIN (
  SELECT ra.task_id, uu.username AS assigned_to
  FROM recount_assignments ra
  JOIN users uu ON uu.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
WHERE t.session_id=? AND t.status<>'cancelado'
ORDER BY FIELD(t.status,'seleccionado','asignado','entregado','en_revision','listo'), t.updated_at DESC
LIMIT 1000
", [$sessionId]);

ob_start();
?>
<div class="card p-3">
  <h4>Asignaciones</h4>
  <p class="text-white-50 mb-2">Admin y monitor pueden asignar. Solo admin selecciona artículos para reconteo.</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>Estado</th><th>Creado por</th><th>Asignado</th><th>Entregado</th><th>Asignar/Reasignar</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach($tasks as $t): ?>
        <tr>
          <td><?= h($t['id']) ?></td>
          <td><?= h($t['code']) ?></td>
          <td><span class="badge badge-info"><?= h($t['status']) ?></span></td>
          <td><?= h($t['creado_por']) ?></td>
          <td><?= h($t['assigned_to'] ?: '-') ?></td>
          <td><?= h($t['delivered_at'] ?: '-') ?></td>
          <td style="min-width:260px;">
            <?php if (in_array($t['status'], ['seleccionado','asignado'], true)): ?>
              <form method="post" class="form-inline m-0">
                <input type="hidden" name="task_id" value="<?= h($t['id']) ?>">
                <select class="form-control form-control-sm mr-2" name="emp_id" required>
                  <option value="">Empleado...</option>
                  <?php foreach($employees as $e): ?>
                    <option value="<?= h($e['id']) ?>"><?= h($e['username']) ?></option>
                  <?php endforeach; ?>
                </select>
                <button class="btn btn-sm btn-warning">Asignar</button>
              </form>
            <?php else: ?>
              <span class="text-muted">No editable</span>
            <?php endif; ?>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>
<?php
$content = ob_get_clean();
$title="Asignaciones";
require __DIR__ . '/../app/views/layout.php';
