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

$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);
  if ($taskId) {
    // ensure assigned to this user
    $ok = one("SELECT ra.task_id FROM recount_assignments ra WHERE ra.task_id=? AND ra.assigned_to_user_id=? AND ra.active=1", [$taskId, $user['id']]);
    if ($ok) {
      // insert delivery only once
      $exists = one("SELECT id FROM recount_deliveries WHERE task_id=?", [$taskId]);
      if (!$exists) {
        q("INSERT INTO recount_deliveries(task_id, delivered_by_user_id, delivered_at) VALUES(?, ?, NOW())", [$taskId, $user['id']]);
      }
      q("UPDATE recount_tasks SET status='entregado', updated_at=NOW() WHERE id=? AND session_id=? AND status IN ('asignado','seleccionado')", [$taskId,$sessionId]);
      flash_set('success','Marcado como entregado.');
    } else {
      flash_set('error','Tarea no asignada a ti.');
    }
  }
  redirect('my_tasks.php');
}

$tasks = all("
SELECT t.id, t.code, t.status, d.delivered_at,
       (SELECT GROUP_CONCAT(DISTINCT p.vitrina ORDER BY p.vitrina SEPARATOR ', ')
        FROM physical_items p WHERE p.session_id=t.session_id AND p.code=t.code) AS vitrinas
FROM recount_tasks t
JOIN recount_assignments ra ON ra.task_id=t.id AND ra.assigned_to_user_id=? AND ra.active=1
LEFT JOIN recount_deliveries d ON d.task_id=t.id
WHERE t.session_id=? AND t.status<>'cancelado'
ORDER BY FIELD(t.status,'asignado','entregado','en_revision','listo','seleccionado'), t.updated_at DESC
", [$user['id'], $sessionId]);

ob_start();
?>
<div class="card p-3">
  <h4>Mis tareas</h4>
  <p class="text-white-50">Solo marca <strong>Entregado</strong> cuando lleves el artículo al monitor.</p>

  <div class="list-group">
    <?php foreach($tasks as $t): ?>
      <div class="list-group-item d-flex justify-content-between align-items-center">
        <div>
          <div><strong><?= h($t['code']) ?></strong></div>
          <small class="text-muted">Vitrinas: <?= h($t['vitrinas'] ?: '-') ?></small><br>
          <span class="badge badge-info"><?= h($t['status']) ?></span>
          <?php if ($t['delivered_at']): ?><span class="badge badge-warning">entregado</span><?php endif; ?>
        </div>
        <div>
          <?php if (!$t['delivered_at'] && $t['status']!=='listo'): ?>
            <form method="post" class="m-0">
              <input type="hidden" name="task_id" value="<?= h($t['id']) ?>">
              <button class="btn btn-success">Entregado</button>
            </form>
          <?php else: ?>
            <span class="text-muted">—</span>
          <?php endif; ?>
        </div>
      </div>
    <?php endforeach; ?>
  </div>
</div>
<?php
$content = ob_get_clean();
$title="Mis tareas";
require __DIR__ . '/../app/views/layout.php';
