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

try {
    session_start();
    
    require_once __DIR__ . '/../core/api.php';

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

    $pdo->exec("SET NAMES 'utf8mb4'");

    $userId = $_SESSION['user_id'] ?? null;
    if (!$userId) throw new Exception('ACCESO NO AUTORIZADO');

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

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

    $projectId = filter_var($data['id'], FILTER_VALIDATE_INT);
    if (!$projectId) throw new Exception('ID INVÁLIDO');

    // --- PASO 1: VERIFICACIÓN DE PROPIEDAD ---
    $checkStmt = $pdo->prepare("
        SELECT p.id 
        FROM projects p
        JOIN clients c ON p.client_id = c.id
        WHERE p.id = ? AND c.user_id = ?
    ");
    $checkStmt->execute([$projectId, $userId]);

    if ($checkStmt->rowCount() === 0) {
        throw new Exception('NO TIENES PERMISO PARA ELIMINAR ESTE PROYECTO');
    }

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

    if ($stmt->rowCount() > 0) {
        $response = ['success' => true, 'message' => 'PROYECTO ELIMINADO'];
    } else {
        throw new Exception('NO SE PUDO ELIMINAR EL REGISTRO');
    }

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

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