<?php
/**
 * Debug: Obtener balance por account_number
 * Uso CLI: php debug_get_balance.php TR-USD-251029-772876
 * Uso HTTP: /api/debug_get_balance.php?account_number=TR-USD-...
 */

require_once __DIR__ . '/../../../database/connection.php';

function getParamAccountNumber(): ?string {
    if (php_sapi_name() === 'cli') {
        global $argv;
        return isset($argv[1]) ? trim($argv[1]) : null;
    }
    return isset($_GET['account_number']) ? trim($_GET['account_number']) : null;
}

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

try {
    if (!$pdo) { throw new Exception('Conexión no disponible'); }
    $accNum = getParamAccountNumber();
    if (!$accNum) { throw new Exception('Parámetro account_number requerido'); }

    $stmt = $pdo->prepare("SELECT id, account_number, balance, equity, margin, free_margin, currency, leverage, status FROM trading_accounts WHERE account_number = ? LIMIT 1");
    $stmt->execute([$accNum]);
    $acc = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$acc) {
        // Buscar otras tablas que tengan account_number y balance
        $dbName = $pdo->query('SELECT DATABASE()')->fetchColumn();
        $sql = "SELECT table_name FROM information_schema.columns WHERE table_schema = ? AND column_name IN ('account_number','balance') GROUP BY table_name HAVING COUNT(DISTINCT column_name)=2";
        $stmtT = $pdo->prepare($sql);
        $stmtT->execute([$dbName]);
        $tables = $stmtT->fetchAll(PDO::FETCH_COLUMN);
        foreach ($tables as $tbl) {
            if (strtolower($tbl) === 'trading_accounts') continue;
            try {
                $q = $pdo->prepare("SELECT * FROM `{$tbl}` WHERE account_number = ? LIMIT 1");
                $q->execute([$accNum]);
                $row = $q->fetch(PDO::FETCH_ASSOC);
                if ($row) {
                    $acc = [
                        'id' => $row['id'] ?? null,
                        'account_number' => $row['account_number'] ?? $accNum,
                        'balance' => isset($row['balance']) ? (float)$row['balance'] : 0.00,
                        'equity' => isset($row['equity']) ? (float)$row['equity'] : (isset($row['balance']) ? (float)$row['balance'] : 0.00),
                        'margin' => isset($row['margin']) ? (float)$row['margin'] : 0.00,
                        'free_margin' => isset($row['free_margin']) ? (float)$row['free_margin'] : (isset($row['balance']) ? (float)$row['balance'] : 0.00),
                        'currency' => $row['currency'] ?? 'USD',
                        'leverage' => $row['leverage'] ?? 100,
                        'status' => $row['status'] ?? 'active',
                        'source_table' => $tbl
                    ];
                    break;
                }
            } catch (Throwable $e) {}
        }
    }

    if (!$acc) {
        echo json_encode(['success' => false, 'message' => 'Cuenta no encontrada', 'account_number' => $accNum]);
        exit;
    }

    echo json_encode(['success' => true, 'account' => $acc]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>
