<?php

declare(strict_types=1);

require_once __DIR__ . '/../../includes/bootstrap.php';

auth_start_session();
auth_require_role(['admin']);

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo 'Method Not Allowed';
    exit;
}

$id = (int)($_POST['id'] ?? 0);
$returnView = trim((string)($_POST['return_view'] ?? 'list'));
$returnMonth = trim((string)($_POST['return_month'] ?? date('Y-m')));
$returnDetailStaff = trim((string)($_POST['return_detail_staff'] ?? ''));
$returnDetailCustomer = trim((string)($_POST['return_detail_customer'] ?? ''));
$allowedViews = ['list', 'calendar', 'completed', 'todo'];
if (!in_array($returnView, $allowedViews, true)) {
    $returnView = 'list';
}
if (!preg_match('/^\d{4}-\d{2}$/', $returnMonth)) {
    $returnMonth = date('Y-m');
}
if ($id <= 0) {
    http_response_code(400);
    echo 'Invalid ID';
    exit;
}

try {
    $pdo = Database::pdo();
    $pdo->beginTransaction();

    $stmt = $pdo->prepare('SELECT assigned_staff_id, status FROM tasks WHERE task_id = :id LIMIT 1');
    $stmt->execute(['id' => $id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $staffId = (int)($row['assigned_staff_id'] ?? 0);

    $stmt2 = $pdo->prepare("UPDATE tasks SET status = 'deleted', updated_at = CURRENT_TIMESTAMP WHERE task_id = :id");
    $stmt2->execute(['id' => $id]);

    if ($staffId > 0) {
        $pdo->prepare('UPDATE staff_details SET is_available = 1 WHERE user_id = :uid')->execute(['uid' => $staffId]);
    }

    $pdo->commit();
} catch (Throwable $e) {
    if (isset($pdo) && $pdo instanceof PDO && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    http_response_code(500);
    echo $e->getMessage();
    exit;
}

if ($returnView === 'todo') {
    $redirect = '/pest/public/admin/todo_tasks.php?month=' . urlencode($returnMonth);
    if ($returnDetailCustomer !== '') {
        $redirect .= '&detail_customer=' . urlencode($returnDetailCustomer) . '#customer-details';
    }
} else {
    $redirect = '/pest/public/admin/task_assignment.php?view=' . urlencode($returnView) . '&month=' . urlencode($returnMonth);
    if ($returnDetailStaff !== '' && $returnDetailCustomer !== '') {
        $redirect .= '&detail_staff=' . urlencode($returnDetailStaff) . '&detail_customer=' . urlencode($returnDetailCustomer);
    }
}
header('Location: ' . $redirect);
exit;
