<?php
/**
 * API Endpoint: Trading Orders
 * Devuelve las órdenes pendientes del cliente
 */

session_start();
// Permitir modo invitado: devolver lista vacía sin error
$isAuthorized = (isset($_SESSION['client_id']) && (($_SESSION['client_status'] ?? 'inactive') === 'active'));
if (!$isAuthorized) {
    header('Content-Type: application/json');
    echo json_encode(['success' => true, 'orders' => [], 'total_count' => 0]);
    exit;
}

// Configuración de la base de datos
require_once __DIR__ . '/../../../database/connection.php';

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

try {
    

    $client_id = $_SESSION['client_id'];
    $accountNumber = isset($_GET['account_number']) ? trim($_GET['account_number']) : null;
    
    // Obtener cuenta de trading del cliente
    if ($accountNumber) {
        $stmt = $pdo->prepare("SELECT id FROM trading_accounts WHERE client_id = ? AND account_number = ? AND status = 'active' LIMIT 1");
        $stmt->execute([$client_id, $accountNumber]);
    } else {
        $stmt = $pdo->prepare("SELECT id FROM trading_accounts WHERE client_id = ? AND status = 'active' ORDER BY created_at DESC LIMIT 1");
        $stmt->execute([$client_id]);
    }
    $account = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$account) {
        echo json_encode([
            'success' => true,
            'orders' => [],
            'total_count' => 0,
            'message' => 'No se encontró cuenta de trading'
        ]);
        exit;
    }
    
    $account_id = $account['id'];
    
    // Obtener órdenes pendientes
    $stmt = $pdo->prepare("
        SELECT 
            ord.*,
            ti.name as instrument_name,
            ti.pip_size,
            ti.base_currency,
            ti.quote_currency
        FROM trading_orders AS ord
        LEFT JOIN trading_instruments ti ON ord.symbol = ti.symbol
        WHERE ord.account_id = ? AND ord.status = 'pending'
        ORDER BY ord.created_at DESC
    ");
    
    $stmt->execute([$account_id]);
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Obtener precios actuales desde Finage para mostrar distancia
    require_once __DIR__ . '/../finage_api.php';
    $finage = getFinageAPI();
    $symbols = array_values(array_unique(array_map(function($ord){ return $ord['symbol']; }, $orders)));
    $realPrices = [];
    try {
        if (count($symbols) > 0) {
            $realPrices = $finage->getMultiplePrices($symbols);
        }
    } catch (\Throwable $e) {
        error_log('Finage getMultiplePrices error (orders): ' . $e->getMessage());
        $realPrices = [];
    }
    
    // Procesar cada orden
    foreach ($orders as &$order) {
        $symbol = $order['symbol'];
        $type = $order['type'];
        $orderPrice = floatval($order['price']);
        $volume = floatval($order['volume']);
        
        // Obtener precio actual (sin simulación)
        if (isset($realPrices[$symbol])) {
            $rp = $realPrices[$symbol];
            $currentPrice = ($type === 'buy_limit' || $type === 'buy_stop') ? floatval($rp['ask']) : floatval($rp['bid']);
        } else {
            $currentPrice = null; // Sin dato en tiempo real
        }
        
        // Calcular distancia al precio actual
        $distance = $orderPrice - $currentPrice;
        $isJpyPair = (strpos($symbol, 'JPY') !== false);
        $pipValue = $isJpyPair ? 0.01 : 0.0001;
        $distancePips = $distance / $pipValue;
        
        $order['current_price'] = $currentPrice;
        $order['distance'] = $distance;
        $order['distance_pips'] = $distancePips;
        
        // Formatear valores
        $decimals = $isJpyPair ? 3 : 5;
        $order['price_formatted'] = number_format($orderPrice, $decimals);
        $order['current_price_formatted'] = is_numeric($currentPrice) ? number_format($currentPrice, $decimals) : '-';
        $order['volume_formatted'] = number_format($volume, 2);
        $order['distance_formatted'] = ($distance >= 0 ? '+' : '') . number_format($distance, $decimals);
        $order['distance_pips_formatted'] = ($distancePips >= 0 ? '+' : '') . number_format($distancePips, 1) . ' pips';
        
        // Determinar estado y clase CSS
        $order['type_class'] = str_replace('_', '-', strtolower($type));
        $order['status_class'] = 'pending';
        
        // Determinar si la orden está cerca de ejecutarse
        $threshold = $isJpyPair ? 0.05 : 0.0005; // 5 pips para JPY, 0.5 pips para otros
        $order['near_execution'] = is_numeric($distance) ? (abs($distance) <= $threshold) : false;
        
        // Información de tiempo
        $order['created_at_formatted'] = date('d/m/Y H:i:s', strtotime($order['created_at']));
        $order['age'] = calculateAge($order['created_at']);
        
        // Calcular valor nocional
        $order['notional_value'] = $volume * 100000 * (is_numeric($currentPrice) ? $currentPrice : $orderPrice);
        $order['notional_value_formatted'] = number_format($order['notional_value'], 2);
        
        // Información adicional según el tipo de orden
        switch ($type) {
            case 'buy_limit':
                $order['type_display'] = 'Buy Limit';
                $order['execution_condition'] = 'Se ejecutará cuando el precio Ask baje a ' . $order['price_formatted'];
                break;
            case 'sell_limit':
                $order['type_display'] = 'Sell Limit';
                $order['execution_condition'] = 'Se ejecutará cuando el precio Bid suba a ' . $order['price_formatted'];
                break;
            case 'buy_stop':
                $order['type_display'] = 'Buy Stop';
                $order['execution_condition'] = 'Se ejecutará cuando el precio Ask suba a ' . $order['price_formatted'];
                break;
            case 'sell_stop':
                $order['type_display'] = 'Sell Stop';
                $order['execution_condition'] = 'Se ejecutará cuando el precio Bid baje a ' . $order['price_formatted'];
                break;
            default:
                $order['type_display'] = ucfirst(str_replace('_', ' ', $type));
                $order['execution_condition'] = 'Orden pendiente';
        }
        
        // Agregar stops y límites si existen
        if (!empty($order['stop_loss'])) {
            $order['stop_loss_formatted'] = number_format(floatval($order['stop_loss']), $decimals);
        }
        if (!empty($order['take_profit'])) {
            $order['take_profit_formatted'] = number_format(floatval($order['take_profit']), $decimals);
        }
    }
    
    // Agrupar órdenes por tipo
    $groupedOrders = [];
    foreach ($orders as $order) {
        $type = $order['type'];
        if (!isset($groupedOrders[$type])) {
            $groupedOrders[$type] = [];
        }
        $groupedOrders[$type][] = $order;
    }
    
    // Estadísticas
    $buyOrders = array_filter($orders, function($order) { 
        return strpos($order['type'], 'buy') === 0; 
    });
    $sellOrders = array_filter($orders, function($order) { 
        return strpos($order['type'], 'sell') === 0; 
    });
    $nearExecution = array_filter($orders, function($order) { 
        return $order['near_execution']; 
    });
    
    echo json_encode([
        'success' => true,
        'orders' => $orders,
        'grouped' => $groupedOrders,
        'statistics' => [
            'total_count' => count($orders),
            'buy_orders' => count($buyOrders),
            'sell_orders' => count($sellOrders),
            'near_execution' => count($nearExecution)
        ],
        'last_updated' => date('Y-m-d H:i:s')
    ]);
    
} catch (Exception $e) {
    error_log("Error en orders.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Error interno del servidor'
    ]);
}

/**
 * Calcular edad de la orden
 */
function calculateAge($createdAt) {
    $created = new DateTime($createdAt);
    $now = new DateTime();
    $interval = $created->diff($now);
    
    if ($interval->days > 0) {
        return $interval->days . ' día' . ($interval->days > 1 ? 's' : '');
    } elseif ($interval->h > 0) {
        return $interval->h . ' hora' . ($interval->h > 1 ? 's' : '');
    } else {
        return $interval->i . ' minuto' . ($interval->i > 1 ? 's' : '');
    }
}
?>
