<?php
header('Content-Type: application/json');
require_once 'db_connection.php';

$response = ['success' => false, 'message' => 'Solicitud no válida.'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        $response['message'] = 'Error al decodificar JSON: ' . json_last_error_msg();
        echo json_encode($response);
        exit;
    }

    if (empty($data['id'])) {
        $response['message'] = 'ID de tarea no proporcionado.';
        echo json_encode($response);
        exit;
    }

    $taskId = $data['id'];

    try {
        $stmt = $pdo->prepare("DELETE FROM tasks WHERE id = ?");
        $stmt->execute([$taskId]);

        if ($stmt->rowCount() > 0) {
            $response = ['success' => true, 'message' => 'Tarea eliminada con éxito.'];
        } else {
            $response = ['success' => false, 'message' => 'No se encontró la tarea para eliminar.'];
        }
    } catch (PDOException $e) {
        error_log("PDO Error en tasks-delete.php: " . $e->getMessage());
        $response = ['success' => false, 'message' => 'Error de Base de Datos: ' . $e->getMessage()];
    } catch (Exception $e) {
        error_log("General Error en tasks-delete.php: " . $e->getMessage());
        $response = ['success' => false, 'message' => $e->getMessage()];
    }
}

echo json_encode($response);
exit;
?>