<?php
require_once __DIR__ . '/admin_tool_helper.php';

/*
|--------------------------------------------------------------------------
| Safe helpers
|--------------------------------------------------------------------------
*/
if (!function_exists('e')) {
    function e($value)
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('admin_table_exists_local')) {
    function admin_table_exists_local($table)
    {
        if (function_exists('admin_table_exists')) {
            return admin_table_exists($table);
        }

        try {
            $stmt = db()->prepare("SHOW TABLES LIKE ?");
            $stmt->execute([$table]);
            return (bool)$stmt->fetchColumn();
        } catch (Throwable $e) {
            return false;
        }
    }
}

if (!function_exists('admin_column_exists_local')) {
    function admin_column_exists_local($table, $column)
    {
        try {
            $stmt = db()->prepare("SHOW COLUMNS FROM `$table` LIKE ?");
            $stmt->execute([$column]);
            return (bool)$stmt->fetchColumn();
        } catch (Throwable $e) {
            return false;
        }
    }
}

if (!function_exists('admin_json_decode_local')) {
    function admin_json_decode_local($value)
    {
        if ($value === null || $value === '') {
            return [];
        }

        if (is_array($value)) {
            return $value;
        }

        $decoded = json_decode((string)$value, true);

        return is_array($decoded) ? $decoded : [];
    }
}

if (!function_exists('admin_clean_text_local')) {
    function admin_clean_text_local($value, $fallback = 'N/A', $limit = 180)
    {
        $text = trim((string)($value ?? ''));

        if ($text === '') {
            return $fallback;
        }

        $text = strip_tags($text);
        $text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
        $text = preg_replace('/[^\P{C}\t\r\n]+/u', ' ', $text);
        $text = preg_replace('/\s+/', ' ', $text);
        $text = trim($text);

        if ($text === '') {
            return $fallback;
        }

        if ($limit > 0 && mb_strlen($text) > $limit) {
            return mb_substr($text, 0, $limit) . '...';
        }

        return $text;
    }
}

if (!function_exists('admin_price_local')) {
    function admin_price_local($value)
    {
        if ($value === null || $value === '' || !is_numeric($value)) {
            return 'N/A';
        }

        $value = (float)$value;

        if (abs($value) >= 100) {
            return number_format($value, 2);
        }

        if (abs($value) >= 1) {
            return rtrim(rtrim(number_format($value, 5), '0'), '.');
        }

        return number_format($value, 5);
    }
}

if (!function_exists('admin_tf_label_local')) {
    function admin_tf_label_local($tf)
    {
        $tf = strtoupper(str_replace([' ', '_'], '', trim((string)$tf)));
        $map = [
            'M1'=>'1M','1M'=>'1M','M3'=>'3M','3M'=>'3M','M5'=>'5M','5M'=>'5M',
            'M15'=>'15M','15M'=>'15M','M30'=>'30M','30M'=>'30M',
            'H1'=>'1H','1H'=>'1H','H2'=>'2H','2H'=>'2H','H4'=>'4H','4H'=>'4H',
            'D1'=>'1D','1D'=>'1D','W1'=>'1W','1W'=>'1W'
        ];

        return $map[$tf] ?? ($tf ?: 'N/A');
    }
}

if (!function_exists('admin_setting_get_local')) {
    function admin_setting_get_local($key, $default = '')
    {
        if (!admin_table_exists_local('system_settings')) {
            return $default;
        }

        try {
            $stmt = db()->prepare("SELECT setting_value FROM system_settings WHERE setting_key = ? LIMIT 1");
            $stmt->execute([$key]);
            $value = $stmt->fetchColumn();

            return $value !== false ? (string)$value : $default;
        } catch (Throwable $e) {
            return $default;
        }
    }
}

if (!function_exists('admin_confirm_tf_for_setup_local')) {
    function admin_confirm_tf_for_setup_local($setupTf)
    {
        $setupTf = strtolower(trim((string)$setupTf));
        $configured = trim((string)admin_setting_get_local('alert_confirmation_timeframe_map', ''));

        if ($configured !== '') {
            $json = json_decode($configured, true);

            if (is_array($json) && isset($json[$setupTf])) {
                return $json[$setupTf];
            }

            foreach (explode(',', $configured) as $pair) {
                $parts = array_map('trim', explode(':', $pair, 2));
                if (count($parts) === 2 && strtolower($parts[0]) === $setupTf) {
                    return $parts[1];
                }
            }
        }

        $map = [
            '1m' => '1m',
            '3m' => '1m',
            '5m' => '1m',
            '15m' => '5m',
            '30m' => '5m',
            '1h' => '15m',
            '2h' => '15m',
            '4h' => '1h',
            '1d' => '4h',
            '1w' => '1d',
        ];

        return $map[$setupTf] ?? $setupTf;
    }
}

if (!function_exists('admin_stage_label_local')) {
    function admin_stage_label_local($stage)
    {
        $stage = strtoupper((string)$stage);
        $map = [
            'TRACKING' => 'Tracking',
            'ZONE_APPROACHED' => 'Stage 1: Zone',
            'LIQUIDITY_SWEPT' => 'Stage 2: Sweep',
            'STRUCTURE_CONFIRMED' => 'Stage 3: Structure',
            'READY_TO_EXECUTE' => 'Ready',
            'ALERT_SENT' => 'Sent',
            'EXPIRED' => 'Expired',
            'INVALIDATED' => 'Invalidated',
        ];

        return $map[$stage] ?? ucwords(strtolower(str_replace('_', ' ', $stage)));
    }
}

if (!function_exists('admin_badge_class_local')) {
    function admin_badge_class_local($value)
    {
        $v = strtolower((string)$value);

        if (in_array($v, ['sent', 'passed', 'ok', 'ready', 'active', 'yes'], true)) {
            return 'bg-emerald-50 text-emerald-700 border-emerald-200';
        }

        if (in_array($v, ['failed', 'blocked', 'error', 'expired', 'invalidated', 'no'], true)) {
            return 'bg-rose-50 text-rose-700 border-rose-200';
        }

        if (in_array($v, ['pending', 'tracking', 'skipped', 'paused'], true)) {
            return 'bg-amber-50 text-amber-700 border-amber-200';
        }

        return 'bg-slate-50 text-slate-700 border-slate-200';
    }
}

if (!function_exists('admin_checklist_items_local')) {
    function admin_checklist_items_local(array $alert)
    {
        $evaluation = admin_json_decode_local($alert['last_evaluation_snapshot'] ?? '');
        $checklist = admin_json_decode_local($alert['last_execution_checklist'] ?? '');

        if (!$checklist && !empty($evaluation['execution_checklist']) && is_array($evaluation['execution_checklist'])) {
            $checklist = $evaluation['execution_checklist'];
        }

        return [
            $checklist,
            is_array($checklist['items'] ?? null) ? $checklist['items'] : [],
            $evaluation
        ];
    }
}

/*
|--------------------------------------------------------------------------
| Delete/Clear actions
|--------------------------------------------------------------------------
*/
$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? '');

    try {
        if ($action === 'delete_selected') {
            $ids = $_POST['log_ids'] ?? [];
            $ids = array_values(array_filter(array_map('intval', (array)$ids)));

            if ($ids) {
                $placeholders = implode(',', array_fill(0, count($ids), '?'));
                $stmt = db()->prepare("DELETE FROM institutional_alert_logs WHERE id IN ({$placeholders})");
                $stmt->execute($ids);
                $message = 'Selected logs deleted. Deleted rows: ' . $stmt->rowCount() . '.';
            } else {
                $message = 'No logs selected.';
            }
        } elseif ($action === 'clear_old') {
            $days = max(1, min(365, (int)($_POST['days'] ?? 30)));
            $stmt = db()->prepare("DELETE FROM institutional_alert_logs WHERE created_at < DATE_SUB(NOW(), INTERVAL ? DAY)");
            $stmt->execute([$days]);
            $message = 'Old logs cleared.';
        } elseif ($action === 'clear_filtered') {
            [$whereSql, $params] = admin_log_filter_sql($_POST);
            $sql = "DELETE l FROM institutional_alert_logs l LEFT JOIN institutional_alerts a ON a.id = l.alert_id LEFT JOIN users u ON u.id = l.user_id {$whereSql}";
            $stmt = db()->prepare($sql);
            $stmt->execute($params);
            $message = 'Filtered logs cleared. Deleted rows: ' . $stmt->rowCount() . '.';
        } elseif ($action === 'clear_all') {
            /*
             * Admin-only log cleanup.
             * This clears only institutional_alert_logs and does not touch
             * institutional_alerts, users, or user-facing tracked setups.
             */
            db()->exec("DELETE FROM institutional_alert_logs");
            $message = 'All alert logs cleared successfully.';
        }
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }

    $redirect = 'alert_logs.php';
    if ($message) {
        $redirect .= '?message=' . urlencode($message);
    } elseif ($error) {
        $redirect .= '?error=' . urlencode($error);
    }

    header('Location: ' . $redirect);
    exit;
}

function admin_log_filter_sql($source)
{
    $where = [];
    $params = [];

    $symbol = strtoupper(trim((string)($source['symbol'] ?? '')));
    $user = trim((string)($source['user'] ?? ''));
    $channel = trim((string)($source['channel'] ?? ''));
    $status = trim((string)($source['status'] ?? ''));
    $stage = strtoupper(trim((string)($source['stage'] ?? '')));
    $alertId = trim((string)($source['alert_id'] ?? ''));
    $from = trim((string)($source['from'] ?? ''));
    $to = trim((string)($source['to'] ?? ''));

    if ($symbol !== '') {
        $where[] = 'a.symbol LIKE ?';
        $params[] = '%' . $symbol . '%';
    }

    if ($user !== '') {
        $where[] = '(CAST(l.user_id AS CHAR) = ? OR u.email LIKE ? OR u.name LIKE ?)';
        $params[] = $user;
        $params[] = '%' . $user . '%';
        $params[] = '%' . $user . '%';
    }

    if ($channel !== '') {
        $where[] = 'l.channel = ?';
        $params[] = $channel;
    }

    if ($status !== '') {
        $where[] = 'l.status = ?';
        $params[] = $status;
    }

    if ($stage !== '') {
        $where[] = 'UPPER(l.stage) = ?';
        $params[] = $stage;
    }

    if ($alertId !== '' && is_numeric($alertId)) {
        $where[] = 'l.alert_id = ?';
        $params[] = (int)$alertId;
    }

    if ($from !== '') {
        $where[] = 'l.created_at >= ?';
        $params[] = $from . ' 00:00:00';
    }

    if ($to !== '') {
        $where[] = 'l.created_at <= ?';
        $params[] = $to . ' 23:59:59';
    }

    return [$where ? ('WHERE ' . implode(' AND ', $where)) : '', $params];
}

$message = $_GET['message'] ?? '';
$error = $_GET['error'] ?? '';

$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = max(25, min(200, (int)($_GET['per_page'] ?? 50)));
$offset = ($page - 1) * $perPage;

[$whereSql, $params] = admin_log_filter_sql($_GET);

$totalRows = 0;
$rows = [];

if (admin_table_exists_local('institutional_alert_logs')) {
    try {
        $stmt = db()->prepare("
            SELECT COUNT(*)
            FROM institutional_alert_logs l
            LEFT JOIN institutional_alerts a ON a.id = l.alert_id
            LEFT JOIN users u ON u.id = l.user_id
            {$whereSql}
        ");
        $stmt->execute($params);
        $totalRows = (int)$stmt->fetchColumn();

        $stmt = db()->prepare("
            SELECT l.*, a.symbol, a.side, a.timeframe, u.email AS user_email, u.name AS user_name
            FROM institutional_alert_logs l
            LEFT JOIN institutional_alerts a ON a.id = l.alert_id
            LEFT JOIN users u ON u.id = l.user_id
            {$whereSql}
            ORDER BY l.created_at DESC, l.id DESC
            LIMIT {$perPage} OFFSET {$offset}
        ");
        $stmt->execute($params);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

$totalPages = max(1, (int)ceil(max(1, $totalRows) / $perPage));

admin_layout_header('Alert Logs');
?>

<style>
.log-card{background:#fff;border:1px solid #e2e8f0;border-radius:24px;box-shadow:0 12px 34px rgba(15,23,42,.06);overflow:hidden;max-width:1180px;margin:0 auto}
.log-head{padding:24px 26px;border-bottom:1px solid #e2e8f0;display:flex;align-items:flex-start;justify-content:space-between;gap:18px;flex-wrap:wrap}.log-title{font-size:30px;font-weight:900;letter-spacing:-.04em;color:#020617}.log-sub{margin-top:6px;color:#64748b;font-size:14px;line-height:1.6}
.filter-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px}.filter-input,.filter-select{width:100%;height:42px;border:1px solid #cbd5e1;border-radius:13px;padding:0 11px;font-weight:800;background:#fff;color:#0f172a}
.btn{display:inline-flex;align-items:center;justify-content:center;min-height:40px;padding:0 14px;border-radius:13px;font-weight:900;text-decoration:none;border:0;cursor:pointer}.btn-blue{background:#2563eb;color:#fff}.btn-soft{background:#eff6ff;color:#1d4ed8}.btn-red{background:#fef2f2;color:#b91c1c}.btn-warn{background:#fffbeb;color:#b45309}.btn-slate{background:#f8fafc;color:#334155}
.badge{display:inline-flex;align-items:center;justify-content:center;min-height:26px;border-radius:999px;padding:0 10px;font-size:12px;font-weight:900;border:1px solid}
.table-wrap{overflow-x:auto}.log-table{width:100%;border-collapse:collapse;min-width:980px}.log-table th{background:#f8fafc;color:#64748b;text-align:left;padding:13px 14px;font-size:11px;font-weight:900;text-transform:uppercase;letter-spacing:.08em;border-bottom:1px solid #e2e8f0}.log-table td{padding:13px 14px;border-bottom:1px solid #e2e8f0;vertical-align:top;font-size:13px}.log-table tr:hover{background:#f8fbff}
.muted{display:block;color:#64748b;font-size:12px;line-height:1.5;margin-top:4px;font-weight:700}.msg{max-width:520px}.msg details summary{cursor:pointer;font-weight:900;color:#1d4ed8;margin-top:6px}.msg pre{white-space:pre-wrap;word-break:break-word;background:#020617;color:#dbeafe;border-radius:14px;padding:12px;font-size:12px;line-height:1.5;max-height:260px;overflow:auto}
.notice{margin:0 0 18px;padding:14px 16px;border-radius:16px;font-weight:850}.notice-success{background:#ecfdf5;color:#047857;border:1px solid #a7f3d0}.notice-error{background:#fef2f2;color:#b91c1c;border:1px solid #fecaca}
.bulk-bar{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;padding:14px 24px;background:#f8fafc;border-bottom:1px solid #e2e8f0}.actions{display:flex;gap:8px;flex-wrap:wrap}.pager{padding:18px 24px;display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;border-top:1px solid #e2e8f0;color:#64748b;font-weight:800}
@media(max-width:1200px){.filter-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:700px){.filter-grid{grid-template-columns:1fr}.log-table{min-width:860px}}
</style>

<?php if ($message): ?><div class="notice notice-success"><?= e($message) ?></div><?php endif; ?>
<?php if ($error): ?><div class="notice notice-error"><?= e($error) ?></div><?php endif; ?>

<section class="log-card">
    <div class="log-head">
        <div>
            <div class="log-title">Alert Logs</div>
            <div class="log-sub">Organized admin log viewer with user identity, setup context, filters, pagination and safe log cleanup.</div>
        </div>
        <span class="badge bg-slate-50 text-slate-700 border-slate-200"><?= (int)$totalRows ?> log(s)</span>
    </div>

    <form method="get" style="padding:22px 24px;border-bottom:1px solid #e2e8f0;">
        <div class="filter-grid">
            <input class="filter-input" name="symbol" value="<?= e($_GET['symbol'] ?? '') ?>" placeholder="Symbol">
            <input class="filter-input" name="user" value="<?= e($_GET['user'] ?? '') ?>" placeholder="User ID/email/name">
            <input class="filter-input" name="alert_id" value="<?= e($_GET['alert_id'] ?? '') ?>" placeholder="Alert ID">
            <select class="filter-select" name="channel">
                <?php foreach ([''=>'Any Channel','email'=>'Email','telegram'=>'Telegram','email_stage'=>'Email Stage','telegram_stage'=>'Telegram Stage','execution_checklist'=>'Checklist','stage_validation'=>'Stage Validation'] as $k=>$v): ?>
                    <option value="<?= e($k) ?>" <?= ($_GET['channel'] ?? '') === $k ? 'selected' : '' ?>><?= e($v) ?></option>
                <?php endforeach; ?>
            </select>
            <select class="filter-select" name="status">
                <?php foreach ([''=>'Any Status','sent'=>'Sent','failed'=>'Failed','blocked'=>'Blocked','skipped'=>'Skipped','ok'=>'OK'] as $k=>$v): ?>
                    <option value="<?= e($k) ?>" <?= ($_GET['status'] ?? '') === $k ? 'selected' : '' ?>><?= e($v) ?></option>
                <?php endforeach; ?>
            </select>
            <input class="filter-input" type="date" name="from" value="<?= e($_GET['from'] ?? '') ?>">
            <button class="btn btn-blue" type="submit">Filter</button>
        </div>
    </form>

    <form method="post">
        <div class="bulk-bar">
            <div>
                <strong>Bulk actions</strong>
                <span class="muted" style="display:inline;margin-left:8px;">Select log rows below, then delete selected. This only affects admin log records.</span>
            </div>
            <div class="actions">
                <button class="btn btn-red" name="action" value="delete_selected" type="submit" onclick="return confirm('Delete selected logs? This will not affect users or alerts.');">Delete Selected</button>
            </div>
        </div>

        <div class="table-wrap">
            <table class="log-table">
                <thead>
                    <tr>
                        <th><input type="checkbox" onclick="document.querySelectorAll('.log-check').forEach(cb => cb.checked = this.checked);"></th>
                        <th>Date</th>
                        <th>User</th>
                        <th>Setup</th>
                        <th>Stage</th>
                        <th>Channel</th>
                        <th>Status</th>
                        <th>Message</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (!$rows): ?>
                    <tr><td colspan="8" style="padding:34px;text-align:center;color:#64748b;font-weight:800;">No logs found.</td></tr>
                <?php endif; ?>

                <?php foreach ($rows as $r): ?>
                    <tr>
                        <td><input class="log-check" type="checkbox" name="log_ids[]" value="<?= e($r['id'] ?? '') ?>"></td>
                        <td>
                            <strong><?= e($r['created_at'] ?? 'N/A') ?></strong>
                            <span class="muted">Log #<?= e($r['id'] ?? '') ?> &bull; Alert #<?= e($r['alert_id'] ?? '') ?></span>
                        </td>
                        <td>
                            <strong><?= e($r['user_name'] ?: 'User #' . ($r['user_id'] ?? '')) ?></strong>
                            <span class="muted"><?= e($r['user_email'] ?? 'No email') ?></span>
                        </td>
                        <td>
                            <strong><?= e($r['symbol'] ?? 'N/A') ?> <?= e($r['side'] ?? '') ?></strong>
                            <span class="muted"><?= e(admin_tf_label_local($r['timeframe'] ?? '')) ?></span>
                        </td>
                        <td><span class="badge <?= e(admin_badge_class_local($r['stage'] ?? '')) ?>"><?= e(admin_stage_label_local($r['stage'] ?? 'N/A')) ?></span></td>
                        <td><span class="badge bg-slate-50 text-slate-700 border-slate-200"><?= e($r['channel'] ?? 'N/A') ?></span></td>
                        <td><span class="badge <?= e(admin_badge_class_local($r['status'] ?? '')) ?>"><?= e($r['status'] ?? 'N/A') ?></span></td>
                        <td class="msg">
                            <?= e(admin_clean_text_local($r['message'] ?? '', 'N/A', 180)) ?>
                            <?php if (mb_strlen(strip_tags((string)($r['message'] ?? ''))) > 180): ?>
                                <details><summary>Full message</summary><pre><?= e(admin_clean_text_local($r['message'] ?? '', 'N/A', 0)) ?></pre></details>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </form>

    <div class="pager">
        <div>Page <?= (int)$page ?> of <?= (int)$totalPages ?> &bull; <?= (int)$totalRows ?> logs</div>
        <div class="actions">
            <?php if ($page > 1): ?><a class="btn btn-soft" href="?<?= e(http_build_query(array_merge($_GET, ['page' => $page - 1]))) ?>">Previous</a><?php endif; ?>
            <?php if ($page < $totalPages): ?><a class="btn btn-blue" href="?<?= e(http_build_query(array_merge($_GET, ['page' => $page + 1]))) ?>">Next</a><?php endif; ?>
        </div>
    </div>
</section>

<section class="log-card" style="margin-top:18px;padding:22px 24px;">
    <h2 style="font-size:20px;font-weight:900;margin:0 0 10px;">Log Cleanup</h2>
    <p style="color:#64748b;margin:0 0 18px;">These actions only remove admin log records from <code>institutional_alert_logs</code>. They do not delete user alerts or affect user dashboards.</p>

    <div class="actions">
        <form method="post" onsubmit="return confirm('Clear logs older than selected days?');">
            <input type="hidden" name="action" value="clear_old">
            <select name="days" class="filter-select" style="width:150px;">
                <option value="7">Older than 7 days</option>
                <option value="14">Older than 14 days</option>
                <option value="30" selected>Older than 30 days</option>
                <option value="90">Older than 90 days</option>
            </select>
            <button class="btn btn-warn" type="submit">Clear Old Logs</button>
        </form>

        <form method="post" onsubmit="return confirm('Clear all logs matching the current filters? This does not affect users.');">
            <?php foreach (['symbol','user','alert_id','channel','status','stage','from','to'] as $key): ?>
                <input type="hidden" name="<?= e($key) ?>" value="<?= e($_GET[$key] ?? '') ?>">
            <?php endforeach; ?>
            <button name="action" value="clear_filtered" class="btn btn-red" type="submit">Clear Filtered Logs</button>
        </form>

        <form method="post" onsubmit="return confirm('Clear ALL alert logs? This cannot be undone, but it will not affect user alerts or dashboards.');">
            <input type="hidden" name="action" value="clear_all">
            <button class="btn btn-red" type="submit">Clear All Logs</button>
        </form>
    </div>
</section>

<?php admin_layout_footer(); ?>
