<?php
/**
 * API Endpoint: Price Alerts
 * Devuelve las alertas de precio del usuario autenticado (o demo)
 */

session_start();
// Modo demo (permite acceder sin sesión)
$demo = (isset($_GET['demo']) && $_GET['demo'] === '1');

// Verificar autenticación del cliente/usuario
if (!$demo && (!isset($_SESSION['user_id']) && !isset($_SESSION['client_id']))) {
    http_response_code(401);
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'error' => 'No autorizado']);
    exit;
}

// Configuración de la base de datos (solo si no es demo)
if (!$demo) {
    require_once __DIR__ . '/../../../database/connection.php';
}

header('Content-Type: application/json');

try {
    if ($demo) {
        // Datos de ejemplo para UI
        $sample = [
            [
                'id' => 1,
                'symbol' => 'EURUSD',
                'condition_type' => 'above',
                'target_price' => 1.09000,
                'current_price' => 1.08478,
                'message' => 'Alertar si supera 1.0900',
                'is_active' => true,
                'triggered_at' => null,
                'created_at' => date('Y-m-d H:i:s')
            ],
            [
                'id' => 2,
                'symbol' => 'GBPUSD',
                'condition_type' => 'below',
                'target_price' => 1.26000,
                'current_price' => 1.26812,
                'message' => 'Avisar si cae por debajo de 1.2600',
                'is_active' => true,
                'triggered_at' => null,
                'created_at' => date('Y-m-d H:i:s', time() - 3600)
            ]
        ];
        echo json_encode(['success' => true, 'alerts' => $sample]);
        exit;
    }

    // Determinar user_id para price_alerts
    $user_id = $_SESSION['user_id'] ?? null;

    // Si no hay user_id en sesión, intentar mapear por email del cliente
    if (!$user_id && isset($_SESSION['client_email'])) {
        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ? LIMIT 1");
        $stmt->execute([$_SESSION['client_email']]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row) { $user_id = $row['id']; }
    }

    if (!$user_id) {
        echo json_encode(['success' => true, 'alerts' => [], 'message' => 'Sin usuario asociado para alertas']);
        exit;
    }

    // Obtener alertas activas del usuario
    $stmt = $pdo->prepare("SELECT id, symbol, condition_type, target_price, current_price, message, is_active, triggered_at, created_at
                           FROM price_alerts WHERE user_id = ? AND is_active = 1 ORDER BY created_at DESC");
    $stmt->execute([$user_id]);
    $alerts = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode(['success' => true, 'alerts' => $alerts]);

} catch (Exception $e) {
    error_log("Error en alerts.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Error interno del servidor'
    ]);
}
?>
