<?php
// =============================================================
// ANALYTICS — просадки, кривая капитала, разбивка по инструментам
// =============================================================
// Фильтры: трейдер + период (7д/30д/90д/всё). Графики — inline-SVG
// (assets/app.js), без CDN-зависимостей.

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/auth.php';
require_auth();

if (isset($_GET['logout'])) {
    logout();
    header('Location: login.php');
    exit;
}

require_once __DIR__ . '/../storage.php';
require_once __DIR__ . '/data.php';
require_once __DIR__ . '/lib/render.php';
require_once __DIR__ . '/lib/layout.php';

// --- Фильтры ---------------------------------------------------
$walletsConfig = load_wallets_config();
$allWallets    = $walletsConfig['wallets'] ?? [];
$walletAddressById = array_column($allWallets, 'address', 'id');

$filterWalletId = $_GET['wallet'] ?? 'all';
if ($filterWalletId !== 'all' && !isset($walletAddressById[$filterWalletId])) {
    $filterWalletId = 'all';
}

$periodOptions  = ['7d' => '7д', '30d' => '30д', '90d' => '90д', 'all' => 'Всё'];
$selectedPeriod = $_GET['period'] ?? 'all';
if (!isset($periodOptions[$selectedPeriod])) {
    $selectedPeriod = 'all';
}
$periodFromTs = period_from_ts($selectedPeriod);

function analytics_qs(array $overrides = []): string
{
    global $filterWalletId, $selectedPeriod;
    $params = array_merge(['wallet' => $filterWalletId, 'period' => $selectedPeriod], $overrides);
    $params = array_filter($params, fn($v) => $v !== null && $v !== '' && $v !== 'all');
    $qs = http_build_query($params);
    return $qs === '' ? '' : '?' . $qs;
}

$trades = filter_trades_since(
    $filterWalletId === 'all' ? storage_get_closed_trades() : storage_get_closed_trades($filterWalletId),
    $periodFromTs
);

// --- Кривая капитала + просадка ---------------------------------

/**
 * По массиву сделок строит две параллельных серии:
 *   equity[]   — накопительный Net PnL ($ от стартового 0)
 *   drawdown[] — просадка в $ от пика (всегда ≤ 0)
 */
function calc_equity_and_drawdown(array $trades): array
{
    $labels   = [];
    $equity   = [];
    $drawdown = [];

    $running = 0.0;
    $peak    = 0.0;
    $maxDd   = 0.0;

    foreach ($trades as $t) {
        $running += (float) ($t['net_pnl'] ?? 0);
        if ($running > $peak) {
            $peak = $running;
        }
        $dd = $running - $peak;   // всегда ≤ 0

        $labels[]   = date('d.m H:i', strtotime($t['close_time']));
        $equity[]   = round($running, 2);
        $drawdown[] = round($dd, 2);

        if ($dd < $maxDd) {
            $maxDd = $dd;
        }
    }

    return [
        'labels'           => $labels,
        'equity'           => $equity,
        'drawdown'         => $drawdown,
        'max_drawdown_usd' => round($maxDd, 2),
    ];
}

// --- PnL по инструментам ----------------------------------------

function calc_by_symbol(array $trades): array
{
    $map = [];
    foreach ($trades as $t) {
        $sym = $t['symbol'] ?? '?';
        if (!isset($map[$sym])) {
            $map[$sym] = ['net_pnl' => 0.0, 'trades' => 0, 'wins' => 0];
        }
        $pnl = (float) ($t['net_pnl'] ?? 0);
        $map[$sym]['net_pnl'] += $pnl;
        $map[$sym]['trades']++;
        // Победа — строго net > 0 (после комиссий), единое определение с
        // balance_tracker/calculate_summary.
        if ($pnl > 0) {
            $map[$sym]['wins']++;
        }
    }

    uasort($map, fn($a, $b) => abs($b['net_pnl']) <=> abs($a['net_pnl']));

    $result = [];
    foreach ($map as $sym => $d) {
        $result[] = [
            'symbol'   => $sym,
            'net_pnl'  => round($d['net_pnl'], 2),
            'trades'   => $d['trades'],
            'win_rate' => $d['trades'] > 0 ? round($d['wins'] / $d['trades'] * 100, 1) : 0,
        ];
    }

    return $result;
}

// --- Распределение сделок по размеру PnL (%)-бакеты -------------

function calc_pnl_distribution(array $trades): array
{
    $buckets = [
        'big_loss'  => ['label' => '< -5%',   'count' => 0],
        'loss'      => ['label' => '-5%..0%',  'count' => 0],
        'small_win' => ['label' => '0%..5%',   'count' => 0],
        'big_win'   => ['label' => '> 5%',     'count' => 0],
    ];

    foreach ($trades as $t) {
        $pct = (float) ($t['pnl_pct'] ?? 0);
        if      ($pct < -5) { $buckets['big_loss']['count']++;  }
        elseif  ($pct <  0) { $buckets['loss']['count']++;      }
        elseif  ($pct <= 5) { $buckets['small_win']['count']++; }
        else                { $buckets['big_win']['count']++;    }
    }

    return array_values($buckets);
}

// --- Среднее время удержания по дням недели ---------------------

function calc_holding_by_weekday(array $trades): array
{
    $days = ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'];
    $map  = array_fill(0, 7, ['sum' => 0, 'count' => 0]);

    foreach ($trades as $t) {
        $ct = strtotime($t['close_time']);
        if (!$ct) {
            continue;
        }
        $ot = strtotime($t['open_time']);
        $holding = max(0, $ct - $ot);
        $dow = (int) date('w', $ct);   // 0=Sun
        $map[$dow]['sum']   += $holding;
        $map[$dow]['count'] += 1;
    }

    $result = [];
    foreach ($days as $i => $label) {
        $avg = $map[$i]['count'] > 0 ? $map[$i]['sum'] / $map[$i]['count'] : 0;
        $result[] = [
            'label' => $label,
            'avg_h' => round($avg / 3600, 2),
        ];
    }

    return $result;
}

// --- Данные для страницы ----------------------------------------

$equityData   = calc_equity_and_drawdown($trades);
$bySymbol     = calc_by_symbol($trades);
$distribution = calc_pnl_distribution($trades);
$holdingByDay = calc_holding_by_weekday($trades);
$summary      = calculate_summary($trades);

$topSymbols = array_slice($bySymbol, 0, 10);

$peakEquity = 0.0;
foreach ($equityData['equity'] as $v) {
    if ($v > $peakEquity) {
        $peakEquity = $v;
    }
}
$maxDdPct = ($peakEquity > 0)
    ? round($equityData['max_drawdown_usd'] / $peakEquity * 100, 2)
    : 0;

layout_header(['title' => 'Аналитика', 'page' => 'analytics']);
?>

<div class="toolbar">
    <form method="GET" style="display:inline-flex; align-items:center; gap:8px">
        <?php if ($selectedPeriod !== 'all'): ?>
        <input type="hidden" name="period" value="<?= htmlspecialchars($selectedPeriod) ?>">
        <?php endif; ?>
        <select name="wallet" onchange="this.form.submit()">
            <option value="all">Все трейдеры</option>
            <?php foreach ($allWallets as $w): ?>
            <option value="<?= htmlspecialchars($w['id']) ?>" <?= $filterWalletId === $w['id'] ? 'selected' : '' ?>><?= htmlspecialchars(($w['label'] ?? '') !== '' ? $w['label'] : $w['id']) ?></option>
            <?php endforeach; ?>
        </select>
        <?php if ($filterWalletId !== 'all'): ?><?= hyperdash_link($walletAddressById[$filterWalletId] ?? '') ?><?php endif; ?>
    </form>
    <div class="seg">
        <?php foreach ($periodOptions as $pKey => $pLabel): ?>
        <a href="analytics.php<?= analytics_qs(['period' => $pKey]) ?>" class="<?= $selectedPeriod === $pKey ? 'active' : '' ?>"><?= $pLabel ?></a>
        <?php endforeach; ?>
    </div>
    <span class="count"><?= $summary['total_trades'] ?> сделок в выборке</span>
</div>

<?php if (empty($trades)): ?>
<div class="empty" style="padding:60px 20px">Нет закрытых сделок<?= $selectedPeriod !== 'all' ? ' за выбранный период' : '' ?>. Данные появятся после первых срабатываний бота.</div>
<?php else: ?>

<div class="kpi-grid">
    <div class="kpi">
        <div class="k-label">Net PnL</div>
        <div class="k-value <?= pnl_class($summary['total_net_pnl']) ?>"><?= fmt_usd($summary['total_net_pnl']) ?></div>
    </div>
    <div class="kpi">
        <div class="k-label">Win rate</div>
        <div class="k-value <?= $summary['win_rate'] >= 50 ? 'pos' : 'neg' ?>"><?= $summary['win_rate'] ?>%</div>
    </div>
    <div class="kpi">
        <div class="k-label">Max drawdown</div>
        <div class="k-value <?= $equityData['max_drawdown_usd'] < 0 ? 'neg' : '' ?>">
            <?= number_format($equityData['max_drawdown_usd'], 2) ?> $
            <?php if ($maxDdPct != 0): ?><span style="font-size:13px; color:var(--text-dim)">(<?= $maxDdPct ?>%)</span><?php endif; ?>
        </div>
    </div>
    <div class="kpi">
        <div class="k-label">Avg ROI / сделка</div>
        <div class="k-value <?= pnl_class($summary['avg_pnl_pct']) ?>"><?= fmt_pct($summary['avg_pnl_pct']) ?></div>
    </div>
    <div class="kpi">
        <div class="k-label">Комиссии</div>
        <div class="k-value neg"><?= fmt_usd(-$summary['total_fees']) ?></div>
    </div>
</div>

<div class="card section">
    <div class="card-title">Кривая капитала — накопительный Net PnL, $</div>
    <div class="chart-box" id="ch-equity"></div>
</div>

<div class="card section">
    <div class="card-title">Просадка от пика, $</div>
    <div class="chart-box" id="ch-dd"></div>
</div>

<div class="charts-2 section">
    <div class="card" style="margin-top:0">
        <div class="card-title">Net PnL по инструментам (топ-10), $</div>
        <div class="chart-box" id="ch-symbols"></div>
    </div>
    <div class="card" style="margin-top:0">
        <div class="card-title">Распределение сделок по ROI</div>
        <div id="ch-dist"></div>
    </div>
</div>

<div class="card section">
    <div class="card-title">Среднее время удержания по дням закрытия, ч</div>
    <div class="chart-box" id="ch-hold"></div>
</div>

<div class="card section">
    <div class="card-title">Детализация по инструментам</div>
    <div class="table-wrap" style="border:none; background:transparent">
        <table class="sortable stack">
            <thead><tr><th>Символ</th><th class="num">Net PnL $</th><th class="num">Сделок</th><th class="num">Win rate</th></tr></thead>
            <tbody>
                <?php foreach ($bySymbol as $row): ?>
                <tr>
                    <td class="stack-main"><b><?= htmlspecialchars($row['symbol']) ?></b> <?= tradingview_link($row['symbol']) ?></td>
                    <td class="num <?= pnl_class($row['net_pnl']) ?>" data-label="Net PnL $" data-sort="<?= $row['net_pnl'] ?>" style="font-weight:650"><?= fmt_usd($row['net_pnl']) ?></td>
                    <td class="num" data-label="Сделок" data-sort="<?= $row['trades'] ?>"><?= $row['trades'] ?></td>
                    <td class="num <?= $row['win_rate'] >= 50 ? 'pos' : 'neg' ?>" data-label="Win rate" data-sort="<?= $row['win_rate'] ?>"><?= $row['win_rate'] ?>%</td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
(function () {
    const equityLabels = <?= json_encode($equityData['labels'], JSON_UNESCAPED_UNICODE) ?>;
    UI.lineChart('ch-equity', equityLabels, <?= json_encode($equityData['equity']) ?>, {
        color: <?= json_encode((end($equityData['equity']) ?: 0) >= 0 ? '#F5B942' : '#FF6B7A') ?>, suffix: ' $', h: 230,
    });
    UI.lineChart('ch-dd', equityLabels, <?= json_encode($equityData['drawdown']) ?>, { color: UI.C.neg, suffix: ' $', h: 150 });
    UI.barChart('ch-symbols', <?= json_encode(array_column($topSymbols, 'symbol')) ?>, <?= json_encode(array_column($topSymbols, 'net_pnl')) ?>, ' $');
    // Donut: дивергентная шкала убыток→прибыль
    UI.donut('ch-dist',
        <?= json_encode(array_map(fn($d) => ['label' => $d['label'], 'count' => $d['count']], $distribution), JSON_UNESCAPED_UNICODE) ?>,
        ['#FF6B7A', '#C77E6E', '#5FAE8C', '#3DDBA5']);
    UI.barChart('ch-hold', <?= json_encode(array_column($holdingByDay, 'label'), JSON_UNESCAPED_UNICODE) ?>, <?= json_encode(array_column($holdingByDay, 'avg_h')) ?>, ' ч');
})();
</script>

<?php endif; // empty trades ?>

<?php layout_footer(); ?>
