<?php
/**
 * GET /api/analytics/career.php
 *
 * Career-wide stats across ALL of the authenticated user's trading_accounts
 * and challenge_accounts, regardless of account_type: total challenges
 * attempted, pass rate, breach rate, average days to pass, and lifetime P&L
 * broken down by account type.
 *
 * 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');

try {
    // Every challenge this user has ever run, across every prop-firm account
    $stmt = $pdo->prepare(
        "SELECT c.account_id, c.challenge_type, c.lifecycle_state, c.passed_at, c.breached_at, c.created_at,
                ta.created_at AS account_created_at
         FROM challenge_accounts c
         JOIN trading_accounts ta ON ta.id = c.account_id
         WHERE ta.user_id = :uid AND ta.deleted_at IS NULL"
    );
    $stmt->execute([':uid' => $userId]);
    $challenges = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $stmt2 = $pdo->prepare(
        "SELECT account_type, COUNT(*) AS cnt, SUM(current_balance - starting_balance) AS net_pnl
         FROM trading_accounts
         WHERE user_id = :uid AND deleted_at IS NULL
         GROUP BY account_type"
    );
    $stmt2->execute([':uid' => $userId]);
    $accountTotals = $stmt2->fetchAll(PDO::FETCH_ASSOC);
} catch (\Throwable $e) {
    error_log('career.php: query failed: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Failed to load career stats']);
    exit;
}

$totalChallenges  = count($challenges);
$passed           = 0;
$breached         = 0;
$daysToPassSum    = 0;
$daysToPassCount  = 0;

foreach ($challenges as $c) {
    // Check if challenge is passed using lifecycle_state as the primary indicator
    $isPassed = !empty($c['passed_at']) || 
                strpos($c['lifecycle_state'], '_complete') !== false || 
                $c['lifecycle_state'] === 'funded_active';
    
    $isBreached = !empty($c['breached_at']);
    
    if ($isPassed) {
        $passed++;
        
        // Calculate days to pass using challenge created_at and passed_at
        if (!empty($c['passed_at']) && !empty($c['created_at'])) {
            try {
                $created = new DateTime($c['created_at']);
                $pass    = new DateTime($c['passed_at']);
                $days = $pass->diff($created)->days;
                
                // Only count positive differences (passed after created)
                if ($days > 0) {
                    $daysToPassSum += $days;
                    $daysToPassCount++;
                }
            } catch (\Throwable $e) {
                error_log('career.php: date calculation failed: ' . $e->getMessage());
                // skip malformed dates rather than failing the whole response
            }
        } elseif (!empty($c['created_at'])) {
            // If passed_at is empty but lifecycle indicates passed,
            // we can't calculate days, just count it as passed
            // Optionally log this for debugging
            error_log('career.php: challenge ' . $c['account_id'] . ' marked as passed but no passed_at date');
        }
    }
    
    if ($isBreached) {
        $breached++;
    }
}

$lifetimePnl          = 0.0;
$accountTypeBreakdown = [];
foreach ($accountTotals as $row) {
    $netPnl = (float)$row['net_pnl'];
    $lifetimePnl += $netPnl;
    $accountTypeBreakdown[$row['account_type']] = [
        'account_count' => (int)$row['cnt'],
        'net_pnl'       => round($netPnl, 2),
    ];
}

echo json_encode([
    'total_challenges'        => $totalChallenges,
    'passed_challenges'       => $passed,
    'breached_challenges'     => $breached,
    'in_progress_challenges'  => max(0, $totalChallenges - $passed - $breached),
    'pass_rate_pct'           => $totalChallenges > 0 ? round(($passed   / $totalChallenges) * 100, 1) : null,
    'breach_rate_pct'         => $totalChallenges > 0 ? round(($breached / $totalChallenges) * 100, 1) : null,
    'average_days_to_pass'    => $daysToPassCount > 0 ? round($daysToPassSum / $daysToPassCount, 1) : null,
    'lifetime_pnl'            => round($lifetimePnl, 2),
    'account_type_breakdown'  => $accountTypeBreakdown,
]);