<?php
// =============================================================
// JOURNAL — закрытые сделки + сигналы (вынесено с дашборда)
// =============================================================
// Фильтры: трейдер + период. Экспорт текущей выборки в CSV.

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__ . '/data.php';
require_once __DIR__ . '/lib/render.php';
require_once __DIR__ . '/lib/layout.php';

$walletsConfig = load_wallets_config();
$wallets = $walletsConfig['wallets'];
$walletAddressById = array_column($wallets, 'address', 'id');
$walletRatingById  = array_column($wallets, 'rating', 'id');

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

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

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

$trades  = array_reverse(filter_trades_since(load_closed_trades($filterWalletId), $periodFromTs));
$signals = array_reverse(filter_signals_since(load_signals($filterWalletId), $periodFromTs));

// --- Экспорт CSV текущей выборки -------------------------------
$export = $_GET['export'] ?? '';
if ($export === 'trades' || $export === 'signals') {
    $filename = 'hyper-analytics-' . $export . '-' . date('Ymd-His') . '.csv';
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    $out = fopen('php://output', 'w');
    if ($export === 'trades') {
        fputcsv($out, ['close_time', 'open_time', 'wallet_id', 'wallet_label', 'symbol', 'side', 'entry_price', 'exit_price', 'size_usd', 'gross_pnl', 'entry_fee', 'exit_fee', 'funding', 'net_pnl', 'pnl_pct', 'entry_slippage_pct', 'exit_slippage_pct', 'exit_reason']);
        foreach ($trades as $t) {
            fputcsv($out, [
                $t['close_time'] ?? '', $t['open_time'] ?? '',
                $t['wallet_id'] ?? '', $t['wallet_label'] ?? '',
                $t['symbol'] ?? '', $t['side'] ?? '',
                $t['entry_price'] ?? '', $t['exit_price'] ?? '',
                $t['size_usd'] ?? '', $t['gross_pnl'] ?? '',
                $t['entry_fee'] ?? '', $t['exit_fee'] ?? '', $t['funding'] ?? '',
                $t['net_pnl'] ?? '', $t['pnl_pct'] ?? '',
                $t['entry_slippage_pct'] ?? '', $t['exit_slippage_pct'] ?? '',
                $t['exit_reason'] ?? 'signal',
            ]);
        }
    } else {
        fputcsv($out, ['datetime', 'wallet_id', 'wallet_label', 'symbol', 'side', 'size', 'mode']);
        foreach ($signals as $s) {
            fputcsv($out, [
                $s['datetime'] ?? '', $s['wallet_id'] ?? '', $s['wallet_label'] ?? '',
                $s['symbol'] ?? '', $s['side'] ?? '', $s['size'] ?? '', $s['mode'] ?? '',
            ]);
        }
    }
    fclose($out);
    exit;
}

$totNet  = array_sum(array_map(fn($t) => (float) ($t['net_pnl'] ?? 0), $trades));
$totFees = array_sum(array_map(fn($t) => (float) ($t['entry_fee'] ?? 0) + (float) ($t['exit_fee'] ?? 0), $trades));

layout_header(['title' => 'Журнал', 'page' => 'journal']);
?>

<div class="tabs">
    <button class="tab-btn active" data-tab="tp-trades" data-hash="trades">Закрытые сделки <span class="cnt"><?= count($trades) ?></span></button>
    <button class="tab-btn" data-tab="tp-signals" data-hash="signals">Сигналы <span class="cnt"><?= count($signals) ?></span></button>
</div>

<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 ($wallets as $w): ?>
            <option value="<?= htmlspecialchars($w['id']) ?>" <?= $selectedWalletId === $w['id'] ? 'selected' : '' ?>><?= htmlspecialchars($w['label'] ?? $w['id']) ?></option>
            <?php endforeach; ?>
        </select>
        <?php if ($filterWalletId !== null): ?><?= hyperdash_link($walletAddressById[$filterWalletId] ?? '') ?><?php endif; ?>
    </form>
    <div class="seg">
        <?php foreach ($periodOptions as $pKey => $pLabel): ?>
        <a href="journal.php<?= journal_qs(['period' => $pKey]) ?>" class="<?= $selectedPeriod === $pKey ? 'active' : '' ?>"><?= $pLabel ?></a>
        <?php endforeach; ?>
    </div>
    <span class="count" id="exp-count"></span>
    <a class="btn secondary small" style="margin-left:auto" id="export-link" href="journal.php<?= journal_qs(['export' => 'trades']) ?>">Экспорт CSV</a>
</div>

<div class="tab-panel active" id="tp-trades">
    <?php if (!empty($trades)): ?>
    <label class="mobile-sort" style="margin-bottom:12px">Сортировка
        <select id="m-sort-trades">
            <option value="">по умолчанию</option>
            <option value="0:desc">Дата (свежие)</option>
            <option value="0:asc">Дата (старые)</option>
            <option value="10:desc">Net PnL ↓</option>
            <option value="10:asc">Net PnL ↑</option>
            <option value="6:desc">Размер ↓</option>
            <option value="8:desc">Gross ↓</option>
        </select>
    </label>
    <?php endif; ?>
    <div class="table-wrap">
        <?php if (empty($trades)): ?>
            <div class="empty">Пока нет закрытых сделок<?= $selectedPeriod !== 'all' ? ' за выбранный период' : '' ?></div>
        <?php else: ?>
        <table class="sortable stack">
            <thead>
                <tr>
                    <th>Закрыта</th><th>Трейдер</th><th>Символ</th><th>Сторона</th>
                    <th class="num">Вход</th><th class="num">Выход</th><th class="num">Размер $</th>
                    <th class="num">Слиппедж</th><th class="num">Gross</th><th class="num">Fees</th><th class="num">Net PnL</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($trades as $t): ?>
                <?php
                    $fees = (float) ($t['entry_fee'] ?? 0) + (float) ($t['exit_fee'] ?? 0);
                    $slippage = ($t['exit_slippage_pct'] ?? '') !== '' ? (float) $t['exit_slippage_pct'] : null;
                    $closeTs = strtotime($t['close_time']);
                    $reason = $t['exit_reason'] ?? 'signal';
                ?>
                <tr>
                    <td class="dim num" data-label="Закрыта" data-sort="<?= (int) $closeTs ?>"><span data-reltime="<?= (int) $closeTs ?>"><?= htmlspecialchars(substr($t['close_time'], 5, 11)) ?></span></td>
                    <td class="stack-main"><span style="display:inline-flex; align-items:center; gap:6px"><a href="trader.php?id=<?= urlencode($t['wallet_id'] ?? '') ?>"><?= htmlspecialchars($t['wallet_label'] ?? '') ?></a> <?= rating_badge((int) ($walletRatingById[$t['wallet_id'] ?? ''] ?? 0)) ?> <?= hyperdash_link($walletAddressById[$t['wallet_id'] ?? ''] ?? '') ?></span></td>
                    <td data-label="Символ"><b><?= htmlspecialchars($t['symbol']) ?></b> <?= tradingview_link($t['symbol']) ?>
                        <?php if ($reason === 'liquidation'): ?><span class="badge liq" title="Внутрисделочная ликвидация: убыток достиг маржи">LIQ</span>
                        <?php elseif ($reason === 'partial'): ?><span class="badge part" title="Частичное закрытие: трейдер закрыл часть позиции">PART</span><?php endif; ?>
                    </td>
                    <td data-label="Сторона"><span class="badge <?= $t['side'] ?>"><?= strtoupper($t['side']) ?></span></td>
                    <td class="num" data-label="Вход" data-sort="<?= (float) $t['entry_price'] ?>"><?= number_format((float) $t['entry_price'], 4) ?></td>
                    <td class="num" data-label="Выход" data-sort="<?= (float) $t['exit_price'] ?>"><?= number_format((float) $t['exit_price'], 4) ?></td>
                    <td class="num" data-label="Размер" data-sort="<?= (float) ($t['size_usd'] ?? 0) ?>"><?= number_format((float) ($t['size_usd'] ?? 0), 2) ?></td>
                    <td class="num <?= $slippage !== null ? pnl_class(-$slippage) : '' ?>" data-label="Слиппедж" data-sort="<?= $slippage ?? '' ?>"><?= $slippage !== null ? fmt_pct($slippage) : '—' ?></td>
                    <td class="num <?= pnl_class((float) $t['gross_pnl']) ?>" data-label="Gross" data-sort="<?= (float) $t['gross_pnl'] ?>"><?= fmt_usd((float) $t['gross_pnl']) ?></td>
                    <td class="num neg" data-label="Fees" data-sort="<?= -$fees ?>"><?= fmt_usd(-$fees) ?></td>
                    <td class="num <?= pnl_class((float) $t['net_pnl']) ?>" data-label="Net PnL" data-sort="<?= (float) $t['net_pnl'] ?>" style="font-weight:650"><?= fmt_usd((float) $t['net_pnl']) ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="8">Итого: <?= count($trades) ?></td>
                    <td class="num"></td>
                    <td class="num neg"><?= fmt_usd(-$totFees) ?></td>
                    <td class="num <?= pnl_class($totNet) ?>"><?= fmt_usd($totNet) ?></td>
                </tr>
            </tfoot>
        </table>
        <?php endif; ?>
    </div>
</div>

<div class="tab-panel" id="tp-signals">
    <?php if (!empty($signals)): ?>
    <label class="mobile-sort" style="margin-bottom:12px">Сортировка
        <select id="m-sort-signals">
            <option value="">по умолчанию</option>
            <option value="0:desc">Время (свежие)</option>
            <option value="0:asc">Время (старые)</option>
            <option value="4:desc">Размер ↓</option>
        </select>
    </label>
    <?php endif; ?>
    <div class="table-wrap">
        <?php if (empty($signals)): ?>
            <div class="empty">Пока нет сигналов<?= $selectedPeriod !== 'all' ? ' за выбранный период' : '' ?></div>
        <?php else: ?>
        <table class="sortable stack">
            <thead><tr><th>Время</th><th>Трейдер</th><th>Символ</th><th>Сторона</th><th class="num">Размер</th><th>Режим</th></tr></thead>
            <tbody>
                <?php foreach ($signals as $s): ?>
                <?php $sigTs = strtotime($s['datetime']); ?>
                <tr>
                    <td class="dim num" data-label="Время" data-sort="<?= (int) $sigTs ?>"><span data-reltime="<?= (int) $sigTs ?>"><?= htmlspecialchars(substr($s['datetime'], 5, 11)) ?></span></td>
                    <td class="stack-main"><span style="display:inline-flex; align-items:center; gap:6px"><a href="trader.php?id=<?= urlencode($s['wallet_id'] ?? '') ?>"><?= htmlspecialchars($s['wallet_label'] ?? '') ?></a> <?= rating_badge((int) ($walletRatingById[$s['wallet_id'] ?? ''] ?? 0)) ?> <?= hyperdash_link($walletAddressById[$s['wallet_id'] ?? ''] ?? '') ?></span></td>
                    <td data-label="Символ"><b><?= htmlspecialchars($s['symbol']) ?></b> <?= tradingview_link($s['symbol']) ?></td>
                    <td data-label="Сторона"><span class="badge <?= strtolower($s['side']) === 'long' ? 'long' : 'short' ?>"><?= strtoupper(htmlspecialchars($s['side'])) ?></span></td>
                    <td class="num" data-label="Размер" data-sort="<?= (float) $s['size'] ?>"><?= number_format((float) $s['size'], 6) ?></td>
                    <td data-label="Режим"><span class="badge mode"><?= htmlspecialchars($s['mode']) ?></span></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php endif; ?>
    </div>
</div>

<script>
(function () {
    UI.initTabs();
    // Мобильная сортировка (заголовки таблиц скрыты на телефоне)
    UI.initMobileSortTable(document.getElementById('m-sort-trades'), document.querySelector('#tp-trades table'));
    UI.initMobileSortTable(document.getElementById('m-sort-signals'), document.querySelector('#tp-signals table'));
    // Экспорт CSV следует за активной вкладкой
    const exportLink = document.getElementById('export-link');
    const urls = {
        'tp-trades':  <?= json_encode('journal.php' . journal_qs(['export' => 'trades'])) ?>,
        'tp-signals': <?= json_encode('journal.php' . journal_qs(['export' => 'signals'])) ?>,
    };
    function syncExport() {
        const active = document.querySelector('.tabs .tab-btn.active');
        if (active && urls[active.dataset.tab]) exportLink.href = urls[active.dataset.tab];
    }
    document.querySelectorAll('.tabs .tab-btn').forEach(b => b.addEventListener('click', syncExport));
    syncExport();
})();
</script>

<?php layout_footer(); ?>
