<?php 
declare(strict_types=1);

require_once __DIR__ . '/../core/api.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendJsonResponse(['success' => false, 'message' => 'msg_invalid_method'], 405);
}

$userId = $_SESSION['user_id'] ?? null;
if (!$userId) {
    sendJsonResponse(['success' => false, 'message' => 'msg_session_expired'], 401);
}

// Validar Permiso
if (!is_module_active('dashboard') || !can('dashboard_view')) {
    sendJsonResponse(['success' => false, 'message' => 'msg_access_denied'], 403);
}

$data = readJsonInput();
$taskId = isset($data['id']) ? (int)$data['id'] : 0;

if (!$taskId) {
    sendJsonResponse(['success' => false, 'message' => 'msg_id_required'], 400);
}

try {
    global $pdo;

    // Ejecutar borrado seguro (solo si pertenece al usuario)
    $stmt = $pdo->prepare("DELETE FROM tasks WHERE id = ? AND user_id = ?");
    $stmt->execute([$taskId, $userId]);

    if ($stmt->rowCount() > 0) {
        sendJsonResponse(['success' => true, 'message' => 'msg_task_deleted']);
    } else {
        // No se encontró o no pertenece al usuario
        sendJsonResponse(['success' => false, 'message' => 'msg_record_not_found_or_access_denied'], 404);
    }

} catch (PDOException $e) {
    error_log("DB Error (tasks-delete): " . $e->getMessage());
    sendJsonResponse(['success' => false, 'message' => 'msg_error_db'], 500);
} catch (Exception $e) {
    error_log("Error (tasks-delete): " . $e->getMessage());
    sendJsonResponse(['success' => false, 'message' => 'msg_error_internal'], 500);
}
?>