<?php
// task_delete.php
declare(strict_types=1);
session_start();

require_once __DIR__ . '/db.php';

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

function get_pdo(): PDO {
  if (function_exists('db')) {
    $pdo = db();
    if ($pdo instanceof PDO) return $pdo;
  }
  if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) return $GLOBALS['pdo'];
  throw new RuntimeException('DB not ready: PDO not found. Ensure db.php defines db():PDO or $pdo');
}

$pdo = get_pdo();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

if ($_SERVER['REQUEST_METHOD'] !== 'POST') { header("Location: tasks.php"); exit; }

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

$role            = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));
$sessionBranchId = (int)($_SESSION['branch_id'] ?? 1);

/* اجلب فرع المهمة */
$st = $pdo->prepare("SELECT branch_id FROM tasks WHERE id=? LIMIT 1");
$st->execute([$id]);
$taskBranchId = (int)($st->fetchColumn() ?: 0);

if ($taskBranchId <= 0) {
  header("Location: tasks.php?del=0");
  exit;
}

/* صلاحيات الحذف:
   - OWNER/ADMIN: يحذف أي مهمة
   - STAFF: يحذف فقط مهام فرعه
*/
if (!in_array($role, ['OWNER','ADMIN'], true)) {
  if ($taskBranchId !== $sessionBranchId) {
    header("Location: tasks.php?del=forbidden");
    exit;
  }
}

/* حذف */
$del = $pdo->prepare("DELETE FROM tasks WHERE id=? LIMIT 1");
$del->execute([$id]);

$ok = ($del->rowCount() > 0);
header("Location: tasks.php?del=" . ($ok ? "1" : "0"));
exit;