<?php
declare(strict_types=1);
session_start();
require_once __DIR__ . '/db.php';

if (empty($_SESSION['user_id'])) {
  header("Location: index.html?e=1");
  exit;
}


$branchId = (int)($_SESSION['branch_id'] ?? 1);

$id = (int)($_POST['id'] ?? 0);
if ($id <= 0) {
  header("Location: tasks.php?e=1");
  exit;
}

try {
  $st = $pdo->prepare("SELECT status FROM tasks WHERE id=? AND branch_id=? LIMIT 1");
  $st->execute([$id, $branchId]);
  $cur = (string)($st->fetchColumn() ?: '');

  if ($cur === '') {
    header("Location: tasks.php?e=1");
    exit;
  }

  $next = ($cur === 'DONE') ? 'OPEN' : 'DONE';
  $st = $pdo->prepare("UPDATE tasks SET status=? WHERE id=? AND branch_id=? LIMIT 1");
  $st->execute([$next, $id, $branchId]);

  header("Location: tasks.php?ok=1");
  exit;
} catch (Throwable $e) {
  header("Location: tasks.php?e=1");
  exit;
}