<?php
/**
 * API Endpoint: Account Information
 * Devuelve información de la cuenta del cliente autenticado
 */

session_start();
// Permitir modo invitado: devolver estructura mínima si no hay sesión activa
$isAuthorized = (isset($_SESSION['client_id']) && (($_SESSION['client_status'] ?? 'inactive') === 'active'));

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

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

try {
    $db = Database::getInstance();
    $pdo = $db->getConnection();
    header('Content-Type: application/json');

    $client_id = $isAuthorized ? $_SESSION['client_id'] : null;
    $accountNumber = isset($_GET['account_number']) ? trim($_GET['account_number']) : null;
    
    // Obtener información de la cuenta de trading
    if ($isAuthorized && $accountNumber) {
        $stmt = $pdo->prepare("SELECT ta.*, c.first_name, c.last_name, c.email
            FROM trading_accounts ta
            JOIN clients c ON ta.client_id = c.id
            WHERE ta.client_id = ? AND ta.account_number = ? AND ta.status = 'active'
            LIMIT 1");
        $stmt->execute([$client_id, $accountNumber]);
    } else if ($isAuthorized) {
        $stmt = $pdo->prepare("SELECT ta.*, c.first_name, c.last_name, c.email
            FROM trading_accounts ta
            JOIN clients c ON ta.client_id = c.id
            WHERE ta.client_id = ? AND ta.status = 'active'
            ORDER BY ta.created_at DESC
            LIMIT 1");
        $stmt->execute([$client_id]);
    }
    $account = isset($stmt) ? $stmt->fetch(PDO::FETCH_ASSOC) : null;

    if (!$account) {
        // Fallback: usar datos de client_accounts si existen, sin crear cuenta demo
        if ($isAuthorized && $accountNumber) {
            $stmt2 = $pdo->prepare("SELECT ca.*, c.first_name, c.last_name, c.email
                FROM client_accounts ca
                JOIN clients c ON ca.client_id = c.id
                WHERE ca.client_id = ? AND ca.account_number = ? AND ca.status = 'active'
                LIMIT 1");
            $stmt2->execute([$client_id, $accountNumber]);
        } else if ($isAuthorized) {
            $stmt2 = $pdo->prepare("SELECT ca.*, c.first_name, c.last_name, c.email
                FROM client_accounts ca
                JOIN clients c ON ca.client_id = c.id
                WHERE ca.client_id = ? AND ca.status = 'active'
                ORDER BY ca.created_at DESC
                LIMIT 1");
            $stmt2->execute([$client_id]);
        }
        $ca = isset($stmt2) ? $stmt2->fetch(PDO::FETCH_ASSOC) : null;

        if ($ca) {
            // Mapear a estructura esperada por el frontend
            $account = [
                'id' => $ca['id'],
                'account_number' => $ca['account_number'] ?? null,
                'account_type' => $ca['account_type'] ?? 'standard',
                'currency' => $ca['currency'] ?? 'USD',
                'leverage' => isset($ca['leverage']) ? (int)$ca['leverage'] : 100,
                'balance' => isset($ca['balance']) ? (float)$ca['balance'] : 0.00,
                // En ausencia de trading_accounts, usar balance como equity inicial y margen 0
                'equity' => isset($ca['balance']) ? (float)$ca['balance'] : 0.00,
                'margin' => 0.00,
                'free_margin' => isset($ca['balance']) ? (float)$ca['balance'] : 0.00,
                'margin_level' => 0.00,
                'first_name' => $ca['first_name'] ?? '',
                'last_name' => $ca['last_name'] ?? '',
                'email' => $ca['email'] ?? ''
            ];
        } else {
            // Fallback final: estructura vacía con ceros
            $account = [
                'account_type' => 'standard',
                'balance' => 0.00,
                'equity' => 0.00,
                'margin' => 0.00,
                'free_margin' => 0.00,
                'margin_level' => 0.00,
                'currency' => 'USD',
                'leverage' => 100,
                'first_name' => '',
                'last_name' => '',
                'email' => ''
            ];
        }
    }
    
    // Calcular métricas adicionales
    $account['profit_loss'] = $account['equity'] - $account['balance'];
    $account['profit_loss_percent'] = $account['balance'] > 0 ? 
        (($account['profit_loss'] / $account['balance']) * 100) : 0;
    
    // Formatear números para mostrar
    $account['balance_formatted'] = number_format($account['balance'], 2);
    $account['equity_formatted'] = number_format($account['equity'], 2);
    $account['margin_formatted'] = number_format($account['margin'], 2);
    $account['free_margin_formatted'] = number_format($account['free_margin'], 2);
    $account['margin_level_formatted'] = number_format($account['margin_level'], 2) . '%';
    $account['profit_loss_formatted'] = ($account['profit_loss'] >= 0 ? '+' : '') . number_format($account['profit_loss'], 2);
    
    // Información del cliente
    $account['client_name'] = $account['first_name'] . ' ' . $account['last_name'];
    
    // Agregar últimas transacciones para UI de modales
    try {
        if (!empty($account['id'])) {
            $stmtTx = $pdo->prepare("SELECT type, amount, currency, method, created_at FROM account_transactions WHERE account_id = ? ORDER BY created_at DESC LIMIT 5");
            $stmtTx->execute([$account['id']]);
            $transactions = $stmtTx->fetchAll(PDO::FETCH_ASSOC);
            $account['transactions'] = $transactions ?: [];
        } else {
            $account['transactions'] = [];
        }
    } catch (Throwable $e) { $account['transactions'] = []; }

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