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

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


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

$id      = (int)($_POST['id'] ?? 0);
$title   = trim((string)($_POST['title'] ?? ''));
$details = trim((string)($_POST['details'] ?? ''));
$status  = strtoupper(trim((string)($_POST['status'] ?? 'OPEN')));
$dueDate = trim((string)($_POST['due_date'] ?? ''));

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

if (!in_array($status, ['OPEN','DONE'], true)) $status = 'OPEN';
$due = ($dueDate !== '') ? $dueDate : null;

try {
  if ($id > 0) {
    // تعديل (ضمن نفس الفرع فقط)
    $st = $pdo->prepare("
      UPDATE tasks
      SET title=?, details=?, status=?, due_date=?
      WHERE id=? AND branch_id=?
      LIMIT 1
    ");
    $st->execute([$title, $details ?: null, $status, $due, $id, $branchId]);
  } else {
    // إضافة
    $st = $pdo->prepare("
      INSERT INTO tasks (branch_id, title, details, status, due_date, created_by)
      VALUES (?, ?, ?, ?, ?, ?)
    ");
    $st->execute([$branchId, $title, $details ?: null, $status, $due, $userId ?: null]);
  }

  header("Location: tasks.php?ok=1");
  exit;

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