<?php
/**
 * GET /api/analytics/portfolio.php?account_type=prop_firm|personal
 *
 * Aggregates account-level analytics — via AnalyticsEngine::getAccountMetrics()
 * and, for prop_firm accounts, ::getChallengeMetrics() — across every
 * trading_accounts row of the given type that belongs to the authenticated
 * user. Backs the Prop Firms / Live Accounts toggle on the Reports page
 * when a portfolio-wide (rather than single-account) view is needed.
 *
 * Read-only. Never writes to the database.
 */

require_once __DIR__ . '/../../config/config.php';
$dsn = "mysql:host=" . DB_HOST . ";port=" . DB_PORT . ";dbname=" . DB_NAME . ";charset=utf8mb4";
$pdo = new PDO($dsn, DB_USER, DB_PASS, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
require_once __DIR__ . '/../../src/Auth.php';
require_once __DIR__ . '/../../src/ScopedDb.php';
if (session_status() === PHP_SESSION_NONE) {
    if (defined('SESSION_NAME')) session_name(SESSION_NAME);
    session_start();
}
$auth = new Auth($pdo);
$userId = $auth->requireAuth();
$db = new ScopedDb($pdo, $userId);

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

require_once __DIR__ . '/engine.php';

$accountType = $_GET['account_type'] ?? 'prop_firm';
if (!in_array($accountType, ['prop_firm', 'personal'], true)) {
    http_response_code(400);
    echo json_encode(['error' => "account_type must be 'prop_firm' or 'personal'"]);
    exit;
}

// Tolerant field lookup — adjust the key lists below if engine.php's actual
// array keys differ from what's assumed here.
function arrVal($arr, $keys, $default = null) {
    if (!is_array($arr)) return $default;
    foreach ((array)$keys as $k) {
        if (array_key_exists($k, $arr) && $arr[$k] !== null) return $arr[$k];
    }
    return $default;
}

try {
    $stmt = $pdo->prepare(
        "SELECT id, label, account_type, starting_balance, current_balance, lifecycle_state, peak_equity, created_at
         FROM trading_accounts
         WHERE user_id = :uid AND account_type = :atype AND deleted_at IS NULL
         ORDER BY created_at DESC"
    );
    $stmt->execute([':uid' => $userId, ':atype' => $accountType]);
    $accounts = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (\Throwable $e) {
    error_log('portfolio.php: account lookup failed: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Failed to load accounts']);
    exit;
}

$engine = new AnalyticsEngine($pdo);

$perAccount          = [];
$sumStartingBalance  = 0.0;
$sumCurrentBalance   = 0.0;
$sumNetPnl           = 0.0;
$sumTrades           = 0;
$winRates            = [];
$profitFactors       = [];

foreach ($accounts as $acct) {
    $metrics = null;
    try {
        $metrics = $engine->getAccountMetrics($acct['id']);
    } catch (\Throwable $e) {
        error_log('portfolio.php: getAccountMetrics failed for account ' . $acct['id'] . ': ' . $e->getMessage());
    }

    $challenge = null;
    if ($accountType === 'prop_firm') {
        try {
            $challenge = $engine->getChallengeMetrics($acct['id']);
        } catch (\Throwable $e) {
            error_log('portfolio.php: getChallengeMetrics failed for account ' . $acct['id'] . ': ' . $e->getMessage());
        }
    }

    $startingBalance = (float)$acct['starting_balance'];
    $currentBalance  = (float)arrVal($metrics, ['current_balance', 'balance'], $acct['current_balance']);
    $netPnl          = (float)arrVal($metrics, ['net_pnl', 'total_pnl'], $currentBalance - $startingBalance);
    $tradeCount      = (int)arrVal($metrics, ['total_trades', 'trades'], 0);
    $winRate         = arrVal($metrics, ['win_rate']);
    $profitFactor    = arrVal($metrics, ['profit_factor']);

    $sumStartingBalance += $startingBalance;
    $sumCurrentBalance  += $currentBalance;
    $sumNetPnl          += $netPnl;
    $sumTrades          += $tradeCount;
    if ($winRate !== null)      $winRates[]      = (float)$winRate;
    if ($profitFactor !== null) $profitFactors[] = (float)$profitFactor;

    $perAccount[] = [
        'account_id'      => $acct['id'],
        'label'           => $acct['label'],
        'lifecycle_state' => $acct['lifecycle_state'],
        'metrics'         => $metrics,
        'challenge'       => $challenge,
    ];
}

echo json_encode([
    'account_type'  => $accountType,
    'account_count' => count($accounts),
    'accounts'      => $perAccount,
    'aggregate'     => [
        'total_starting_balance' => round($sumStartingBalance, 2),
        'total_current_balance'  => round($sumCurrentBalance, 2),
        'total_net_pnl'          => round($sumNetPnl, 2),
        'total_trades'           => $sumTrades,
        'average_win_rate'       => count($winRates)      ? round(array_sum($winRates)      / count($winRates), 1)      : null,
        'average_profit_factor'  => count($profitFactors) ? round(array_sum($profitFactors) / count($profitFactors), 2) : null,
    ],
]);
