<?php
ob_start();
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'ERROR DESCONOCIDO'];

try {
    session_start();
    include_once 'db_connection.php';
    require_once '../files/guardiankey.php';

    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
    error_reporting(E_ALL);

    if (!isset($_SESSION['user_id'])) {
        throw new Exception('ACCESO NO AUTORIZADO');
    }

    $data = json_decode(file_get_contents('php://input'), true);

    if (!isset($data['id'])) {
        throw new Exception('ID PROYECTO REQUERIDO');
    }

    $projectId = filter_var($data['id'], FILTER_VALIDATE_INT);
    
    if ($projectId === false) {
        throw new Exception('ID INVALIDO');
    }

    $sql = "DELETE FROM projects WHERE id = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$projectId]);

    if ($stmt->rowCount() > 0) {
        $response = ['success' => true, 'message' => 'PROYECTO ELIMINADO'];
    } else {
        $response = ['success' => false, 'message' => 'NO ENCONTRADO'];
    }

} catch (PDOException $e) {
    error_log("Error PDO en projects-delete.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => 'ERROR DE BASE DE DATOS'];
} catch (Exception $e) {
    error_log("Error general en projects-delete.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => strtoupper($e->getMessage())];
}

if (ob_get_level() > 0) {
    ob_end_clean();
}
echo json_encode($response);
exit;
?>