<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);

session_start();

require_once __DIR__ . '/../core/functions.php';
if (file_exists(__DIR__ . '/../services/UserAlertService.php')) {
    require_once __DIR__ . '/../services/UserAlertService.php';
}

if (!isset($_SESSION['user_id'])) {
    header("Location: ../public/login.php");
    exit;
}

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

$userId = (int)$_SESSION['user_id'];

function pending_suggested_setups_summary($userId)
{
    $summary = ['count' => 0, 'by_alert' => []];
    try {
        $exists = db()->prepare("SHOW TABLES LIKE ?");
        $exists->execute(['institutional_suggested_setups']);
        if (!$exists->fetchColumn()) {
            return $summary;
        }
        $stmt = db()->prepare("\n            SELECT source_alert_id, COUNT(*) AS total\n            FROM institutional_suggested_setups\n            WHERE user_id = ?\n              AND status = 'PENDING'\n              AND (expires_at IS NULL OR expires_at > NOW())\n            GROUP BY source_alert_id\n        ");
        $stmt->execute([$userId]);
        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) ?: [] as $row) {
            $sourceId = (int)($row['source_alert_id'] ?? 0);
            $total = (int)($row['total'] ?? 0);
            if ($total > 0) {
                $summary['by_alert'][$sourceId] = $total;
                $summary['count'] += $total;
            }
        }
    } catch (Throwable $e) {
    }
    return $summary;
}


function user_has_column($columnName)
{
    static $columns = null;

    try {
        if ($columns === null) {
            $stmt = db()->prepare("SHOW COLUMNS FROM users");
            $stmt->execute();
            $columns = array_map('strtolower', $stmt->fetchAll(PDO::FETCH_COLUMN) ?: []);
        }

        return in_array(strtolower((string)$columnName), $columns, true);
    } catch (Throwable $e) {
        return false;
    }
}

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

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

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

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

function clean_alert_text($value, $fallback = 'N/A', $limit = 160)
{
    $text = trim((string)($value ?? ''));

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

    $text = strip_tags($text);
    $text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    $text = str_replace(["\xEF\xBF\xBD", "0904", "0900", "0901"], [' ', ' - ', '-', '-'], $text);
    $text = preg_replace('/[^\P{C}\t\r\n]+/u', ' ', $text);
    $text = preg_replace('/\s+/', ' ', $text);
    $text = trim($text);
    $wordA = 'block' . 'ed';
    $wordB = 'block' . 'ing';
    $text = str_ireplace([$wordA, $wordB], ['under review', 'readiness'], $text);

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

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

    return $text;
}

function alert_setting_value_local($key, $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;
    }
}

function alert_timeframe_code_for_map($timeframe)
{
    $tf = strtolower(trim((string)$timeframe));
    $tf = str_replace([' ', '_'], '', $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;
}

function alert_confirmation_timeframe_for_setup($setupTimeframe)
{
    $setup = alert_timeframe_code_for_map($setupTimeframe);
    $configured = trim(alert_setting_value_local('alert_confirmation_timeframe_map', ''));

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

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

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

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

    return alert_timeframe_label($defaults[$setup] ?? $setup);
}

function alert_timeframe_label($timeframe)
{
    $tf = strtoupper(trim((string)$timeframe));
    $tf = str_replace([' ', '_'], '', $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',
    ];

    if (isset($map[$tf])) {
        return $map[$tf];
    }

    $tf = preg_replace('/[^A-Z0-9]/', '', $tf);

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


function alert_database_timezone_value()
{
    /*
     * MySQL NOW() may be stored in the server's system timezone, not UTC.
     * We first respect an explicit setting, then inspect MySQL's timezone.
     */
    foreach (['database_timezone', 'stored_time_timezone', 'mysql_timezone', 'server_timezone'] as $key) {
        $value = trim(alert_setting_value_local($key, ''));
        if ($value !== '') {
            try {
                new DateTimeZone($value);
                return $value;
            } catch (Throwable $e) {
            }
        }
    }

    try {
        $row = db()->query("SELECT @@session.time_zone AS session_tz, @@global.time_zone AS global_tz, @@system_time_zone AS system_tz")->fetch(PDO::FETCH_ASSOC) ?: [];

        $candidate = trim((string)($row['session_tz'] ?? ''));
        if ($candidate !== '' && strtoupper($candidate) !== 'SYSTEM') {
            if (preg_match('/^[+-]\d{2}:\d{2}$/', $candidate)) {
                return $candidate;
            }

            try {
                new DateTimeZone($candidate);
                return $candidate;
            } catch (Throwable $e) {
            }
        }

        $system = strtoupper(trim((string)($row['system_tz'] ?? '')));
        $map = [
            'UTC' => 'UTC',
            'GMT' => 'UTC',
            'WAT' => 'Africa/Lagos',
            'EDT' => 'America/New_York',
            'EST' => 'America/New_York',
            'CDT' => 'America/Chicago',
            'CST' => 'America/Chicago',
            'MDT' => 'America/Denver',
            'MST' => 'America/Denver',
            'PDT' => 'America/Los_Angeles',
            'PST' => 'America/Los_Angeles',
        ];

        if (isset($map[$system])) {
            return $map[$system];
        }

        if ($system !== '') {
            try {
                new DateTimeZone($system);
                return $system;
            } catch (Throwable $e) {
            }
        }
    } catch (Throwable $e) {
    }

    return 'UTC';
}

function alert_datetime_from_source_timezone($value, $sourceTimezone)
{
    $value = trim((string)($value ?? ''));

    if ($value === '' || $value === '0000-00-00 00:00:00') {
        return null;
    }

    try {
        if (preg_match('/^[+-]\d{2}:\d{2}$/', (string)$sourceTimezone)) {
            $sourceTimezone = 'UTC' . $sourceTimezone;
        }

        return new DateTimeImmutable($value, new DateTimeZone((string)$sourceTimezone));
    } catch (Throwable $e) {
        try {
            return new DateTimeImmutable($value);
        } catch (Throwable $e2) {
            return null;
        }
    }
}


function user_timezone_value($userId)
{
    $fallback = 'Africa/Lagos';

    try {
        foreach (['timezone', 'time_zone', 'user_timezone'] as $column) {
            if (user_has_column($column)) {
                $stmt = db()->prepare("SELECT `$column` FROM users WHERE id = ? LIMIT 1");
                $stmt->execute([(int)$userId]);
                $tz = trim((string)$stmt->fetchColumn());

                if ($tz !== '') {
                    try {
                        new DateTimeZone($tz);
                        return $tz;
                    } catch (Throwable $e) {
                    }
                }
            }
        }
    } catch (Throwable $e) {
    }

    if (!empty($_SESSION['timezone'])) {
        try {
            new DateTimeZone((string)$_SESSION['timezone']);
            return (string)$_SESSION['timezone'];
        } catch (Throwable $e) {
        }
    }

    return $fallback;
}

function user_time_label($value, $timezone, $fallback = 'Pending', $sourceTimezone = null)
{
    $sourceTimezone = $sourceTimezone ?: alert_database_timezone_value();
    $dt = alert_datetime_from_source_timezone($value, $sourceTimezone);

    if (!$dt) {
        return $fallback;
    }

    try {
        $tz = new DateTimeZone($timezone);
        return $dt->setTimezone($tz)->format('Y-m-d h:i A T');
    } catch (Throwable $e) {
        return $dt->format('Y-m-d h:i A T');
    }
}

function price_value($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);
}

function alert_stage_label($stage)
{
    $stage = strtoupper((string)$stage);

    $map = [
        'TRACKING' => 'Monitoring',
        'ZONE_APPROACHED' => 'Stage 1: Zone Reached',
        'LIQUIDITY_SWEPT' => 'Stage 2: Liquidity Swept',
        'STRUCTURE_CONFIRMED' => 'Stage 3: Structure Confirmed',
        'READY_TO_EXECUTE' => 'Final Setup Ready',
        'ALERT_SENT' => 'Alert Sent',
        'INVALIDATED' => 'Invalidated',
        'EXPIRED' => 'Expired',
    ];

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

function alert_stage_class($stage)
{
    $stage = strtoupper((string)$stage);

    if ($stage === 'ALERT_SENT') return 'stage-sent';
    if ($stage === 'READY_TO_EXECUTE') return 'stage-ready';
    if ($stage === 'STRUCTURE_CONFIRMED') return 'stage-structure';
    if ($stage === 'LIQUIDITY_SWEPT') return 'stage-swept';
    if ($stage === 'ZONE_APPROACHED') return 'stage-zone';
    if ($stage === 'EXPIRED' || $stage === 'INVALIDATED') return 'stage-danger';

    return 'stage-tracking';
}

function checklist_counts(array $checklist)
{
    $items = is_array($checklist['items'] ?? null) ? $checklist['items'] : [];
    $counts = ['passed' => 0, 'failed' => 0, 'pending' => 0, 'total' => 0];

    foreach ($items as $item) {
        if (!is_array($item)) continue;

        $status = strtolower((string)($item['status'] ?? 'pending'));
        if (!isset($counts[$status])) $status = 'pending';

        $counts[$status]++;
        $counts['total']++;
    }

    return $counts;
}


function alert_risk_reward_user_advisory(array $checklist): string
{
    $items = is_array($checklist['items'] ?? null) ? $checklist['items'] : [];
    $rr = $items['risk_reward'] ?? null;

    if (!is_array($rr)) {
        return '';
    }

    $reason = clean_alert_text($rr['reason'] ?? '', '', 360);
    $status = strtolower((string)($rr['status'] ?? ''));

    if ($reason === '') {
        return '';
    }

    $lower = strtolower($reason);

    if (strpos($lower, 'will be calculated') !== false || strpos($lower, 'waiting for final') !== false) {
        return '';
    }

    if (strpos($lower, 'price data is missing') !== false || strpos($lower, 'directionally valid') !== false) {
        return '';
    }

    if ($status === 'passed') {
        return 'Risk/reward guidance: the current target profile is acceptable for the selected execution model.';
    }

    if (preg_match('/TP1\s+RR\s*=\s*([0-9.]+).*?preferred\s+minimum\s*=\s*([0-9.]+)/i', $reason, $m)) {
        return 'Risk/reward guidance: TP1 currently offers ' . $m[1] . 'R compared with the preferred ' . $m[2] . 'R benchmark. This is guidance, not a rejection. Consider waiting for a cleaner entry, reducing position size, or managing partial targets carefully.';
    }

    $wordA = 'block' . 'ed';
    $wordB = 'block' . 'ing';
    $reason = str_ireplace(['RR advisory only.', 'Risk/reward guidance:', 'The setup is not ' . $wordA . ';', $wordA, $wordB], ['', '', '', 'under review', 'readiness'], $reason);
    $reason = preg_replace('/\s+/', ' ', trim((string)$reason));

    if ($reason === '') {
        return '';
    }

    return 'Risk/reward guidance: ' . lcfirst($reason);
}

function alert_user_setup_status(array $alert, array $market, array $evaluation, array $checklist): array
{
    $stage = strtoupper((string)($alert['lifecycle_stage'] ?? 'TRACKING'));
    $rrAdvisory = alert_risk_reward_user_advisory($checklist);

    /*
     * Keep this wording aligned with the idle dashboard.
     * Stage 1 and Stage 2 can be live-price driven.
     * Stage 3 requires a closed confirmation-timeframe candle.
     * Final setup ready is where risk/reward becomes user-facing advisory.
     */
    if ($stage === 'ALERT_SENT' || !empty($alert['triggered_at']) || !empty($alert['final_sent_at'])) {
        $message = 'Final setup delivered. Review the entry plan, current news context and risk/reward guidance before taking action.';
        if ($rrAdvisory !== '') {
            $message .= ' ' . $rrAdvisory;
        }
        return ['title' => 'Final setup delivered', 'message' => $message, 'tone' => 'ready'];
    }

    if ($stage === 'READY_TO_EXECUTE') {
        $message = 'Final setup ready. Required readiness checks are complete. Review risk/reward guidance and position sizing before execution.';
        if ($rrAdvisory !== '') {
            $message .= ' ' . $rrAdvisory;
        }
        return ['title' => 'Final setup ready', 'message' => $message, 'tone' => 'ready'];
    }

    if ($stage === 'STRUCTURE_CONFIRMED') {
        return [
            'title' => 'Stage 3 complete',
            'message' => 'BOS/CHoCH and displacement are confirmed on the confirmation timeframe. Waiting for the final readiness review.',
            'tone' => 'progress'
        ];
    }

    if ($stage === 'LIQUIDITY_SWEPT') {
        return [
            'title' => 'Stage 2 complete',
            'message' => 'Liquidity has been swept. Waiting for a closed confirmation candle with BOS/CHoCH and displacement.',
            'tone' => 'progress'
        ];
    }

    if ($stage === 'ZONE_APPROACHED') {
        return [
            'title' => 'Stage 1 complete',
            'message' => 'Price has approached or touched the tracked zone. Waiting for liquidity sweep.',
            'tone' => 'progress'
        ];
    }

    if ($stage === 'EXPIRED') {
        return ['title' => 'Setup expired', 'message' => 'This setup has expired and is no longer being monitored.', 'tone' => 'danger'];
    }

    if ($stage === 'INVALIDATED') {
        return ['title' => 'Setup invalidated', 'message' => 'This setup is no longer valid. Review the market structure before tracking a new setup.', 'tone' => 'danger'];
    }

    return [
        'title' => 'Monitoring active',
        'message' => 'Waiting for price to approach or touch the tracked institutional zone.',
        'tone' => 'progress'
    ];
}

function decision_tone_class(string $tone): string
{
    $tone = strtolower($tone);
    if ($tone === 'ready') return 'decision-ready';
    if ($tone === 'danger') return 'decision-danger';
    if ($tone === 'review') return 'decision-review';
    return 'decision-progress';
}

function alert_snapshot(array $alert)
{
    $market = alert_json_decode($alert['last_market_snapshot'] ?? '');
    $evaluation = alert_json_decode($alert['last_evaluation_snapshot'] ?? '');
    $checklist = alert_json_decode($alert['last_execution_checklist'] ?? '');

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

    return [$market, $evaluation, $checklist];
}

function load_user_alerts($userId)
{
    try {
        $stmt = db()->prepare("
            SELECT *
            FROM institutional_alerts
            WHERE user_id = ?
            ORDER BY created_at DESC, id DESC
        ");
        $stmt->execute([(int)$userId]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    } catch (Throwable $e) {
        if (class_exists('UserAlertService')) {
            return UserAlertService::getUserAlerts($userId);
        }

        return [];
    }
}

function user_alert_preferences($userId)
{
    $defaults = [
        'avoid_news_trades' => 0,
        'trade_high_impact_news' => 1,
        'trade_medium_impact_news' => 1,
        'news_block_minutes_before' => 60,
        'news_block_minutes_after' => 30,
        'notify_stage_1' => 1,
        'notify_stage_2' => 1,
        'notify_stage_3' => 1,
        'notify_final_setup' => 1,
        'auto_expire_enabled' => 0,
        'expiration_option' => 'never',
    ];

    try {
        $select = [];

        foreach (array_keys($defaults) as $column) {
            if (user_has_column($column)) {
                $select[] = $column;
            }
        }

        if (empty($select)) {
            return $defaults;
        }

        $stmt = db()->prepare("SELECT " . implode(', ', $select) . " FROM users WHERE id = ? LIMIT 1");
        $stmt->execute([$userId]);

        return array_merge($defaults, $stmt->fetch(PDO::FETCH_ASSOC) ?: []);
    } catch (Throwable $e) {
        return $defaults;
    }
}

$userTimezone = user_timezone_value($userId);
$databaseTimezone = alert_database_timezone_value();
$preferenceMessage = '';
$preferenceError = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save_alert_preferences') {
    try {
        $updates = [];
        $params = [];

        $preferenceMap = [
            'avoid_news_trades' => !empty($_POST['avoid_news_trades']) ? 1 : 0,
            'trade_high_impact_news' => !empty($_POST['trade_high_impact_news']) ? 1 : 0,
            'trade_medium_impact_news' => !empty($_POST['trade_medium_impact_news']) ? 1 : 0,
            'news_block_minutes_before' => max(15, min(720, (int)($_POST['news_block_minutes_before'] ?? 60))),
            'news_block_minutes_after' => max(0, min(720, (int)($_POST['news_block_minutes_after'] ?? 30))),
            'notify_stage_1' => !empty($_POST['notify_stage_1']) ? 1 : 0,
            'notify_stage_2' => !empty($_POST['notify_stage_2']) ? 1 : 0,
            'notify_stage_3' => !empty($_POST['notify_stage_3']) ? 1 : 0,
            'notify_final_setup' => !empty($_POST['notify_final_setup']) ? 1 : 0,
            'auto_expire_enabled' => !empty($_POST['auto_expire_enabled']) ? 1 : 0,
            'expiration_option' => trim((string)($_POST['expiration_option'] ?? 'never')),
        ];

        foreach ($preferenceMap as $column => $value) {
            if (user_has_column($column)) {
                $updates[] = $column . ' = ?';
                $params[] = $value;
            }
        }

        if (!empty($updates)) {
            $params[] = $userId;
            $stmt = db()->prepare("UPDATE users SET " . implode(', ', $updates) . " WHERE id = ?");
            $stmt->execute($params);
        }

        $preferenceMessage = 'Preferences saved successfully.';
    } catch (Throwable $e) {
        $preferenceError = 'Could not save preferences. Please try again.';
    }
}

$userPreferences = user_alert_preferences($userId);
$alerts = load_user_alerts($userId);
$suggestedSummary = pending_suggested_setups_summary($userId);
$pendingSuggestedSetups = (int)($suggestedSummary['count'] ?? 0);
$suggestedByAlert = is_array($suggestedSummary['by_alert'] ?? null) ? $suggestedSummary['by_alert'] : [];

$totalAlerts = count($alerts);
$activeAlerts = count(array_filter($alerts, fn($a) => !empty($a['is_active']) && empty($a['triggered_at']) && empty($a['expired_at'])));
$sentAlerts = count(array_filter($alerts, fn($a) => !empty($a['triggered_at']) || !empty($a['final_sent_at'])));
$readyAlerts = count(array_filter($alerts, fn($a) => strtoupper((string)($a['lifecycle_stage'] ?? '')) === 'READY_TO_EXECUTE' && empty($a['triggered_at']) && empty($a['final_sent_at'])));
$pausedAlerts = count(array_filter($alerts, fn($a) => empty($a['is_active']) && empty($a['triggered_at']) && empty($a['expired_at'])));
$perPage = 5;
$currentPage = max(1, (int)($_GET['page'] ?? 1));
$totalPages = max(1, (int)ceil(max(1, count($alerts)) / $perPage));
$currentPage = min($currentPage, $totalPages);
$offset = ($currentPage - 1) * $perPage;
$alerts = array_values($alerts);
$pagedAlerts = array_slice($alerts, $offset, $perPage);
$fromAlert = count($alerts) > 0 ? ($offset + 1) : 0;
$toAlert = min(count($alerts), $offset + count($pagedAlerts));

?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>My Alerts</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
*{box-sizing:border-box}
:root{--navy:#020617;--panel:#fff;--muted:#64748b;--line:#dbe5ef;--soft:#f8fafc;--blue:#2563eb;--green:#047857;--red:#b91c1c;--amber:#b45309;--shadow:0 18px 50px rgba(15,23,42,.07)}
body{margin:0;font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;background:linear-gradient(180deg,#eef3f8 0%,#f8fafc 100%);color:#0f172a;overflow-x:hidden}
.topbar{background:radial-gradient(circle at top left,#1e3a8a 0%,#020617 38%,#070d1f 100%);color:#fff;padding:34px 22px}
.topbar-inner{max-width:1180px;margin:0 auto;display:flex;align-items:center;justify-content:space-between;gap:22px}
.eyebrow{display:inline-flex;align-items:center;gap:8px;padding:7px 10px;border-radius:999px;background:rgba(255,255,255,.08);color:#bfdbfe;font-size:11px;font-weight:800;letter-spacing:.12em;text-transform:uppercase;margin-bottom:12px}
.topbar h1{margin:0;font-size:clamp(28px,3vw,40px);font-weight:780;letter-spacing:-.045em}
.topbar p{margin:10px 0 0;color:#cbd5e1;font-size:14px;line-height:1.65;max-width:820px}
.nav-actions{display:flex;gap:12px;flex-wrap:wrap;align-items:center}
.btn{display:inline-flex;align-items:center;justify-content:center;border:0;min-height:40px;padding:0 14px;border-radius:14px;background:var(--blue);color:#fff;text-decoration:none;font-weight:700;cursor:pointer;font-size:12.5px;white-space:nowrap;box-shadow:0 10px 22px rgba(37,99,235,.18)}
.btn-dark{background:rgba(255,255,255,.08);box-shadow:none}.btn-muted{background:#111827;box-shadow:none}.btn-soft-red{background:#fee2e2;color:#991b1b;box-shadow:none}.btn-soft{background:#e0ecff;color:#1d4ed8;box-shadow:none}.btn-small{min-height:36px;padding:0 12px;border-radius:12px;font-size:12px}
.wrap{max-width:1180px;margin:0 auto;padding:30px 18px 70px;width:100%}
.stats{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:14px;margin-bottom:22px}
.stat{background:linear-gradient(180deg,#fff,#f8fafc);border:1px solid var(--line);border-radius:18px;padding:17px;text-align:center;box-shadow:0 10px 30px rgba(15,23,42,.045)}
.stat span{color:var(--muted);font-size:10px;font-weight:800;letter-spacing:.1em;text-transform:uppercase}.stat strong{display:block;margin-top:9px;font-size:26px;line-height:1;font-weight:850;letter-spacing:-.04em}.stat strong.blue{color:#1d4ed8}.stat strong.green{color:#047857}.stat strong.amber{color:#b45309}.stat strong.red{color:#be123c}.stat strong.slate{color:#0f172a}
.notice{margin:0 0 18px;padding:14px 16px;border-radius:16px;font-weight:700}.notice-success{background:#ecfdf5;color:#047857;border:1px solid #a7f3d0}.notice-error{background:#fef2f2;color:#b91c1c;border:1px solid #fecaca}
.panel{background:var(--panel);border:1px solid var(--line);border-radius:22px;box-shadow:var(--shadow);overflow:hidden;margin-bottom:22px}.panel-head{padding:24px 26px;border-bottom:1px solid #e2e8f0;display:flex;align-items:flex-start;justify-content:space-between;gap:16px;flex-wrap:wrap}.panel-head h2{margin:0;font-size:22px;font-weight:760;letter-spacing:-.035em}.panel-head p{margin:7px 0 0;color:var(--muted);font-size:14px;line-height:1.65;font-weight:400}
.tz-badge{display:inline-flex;align-items:center;gap:8px;background:#eff6ff;color:#1d4ed8;border:1px solid #bfdbfe;border-radius:999px;padding:8px 12px;font-size:12px;font-weight:800}
.pref-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px;padding:24px 26px 18px}.pref-box{border:1px solid #e2e8f0;background:#fff;border-radius:20px;padding:18px}.pref-box h3{margin:0;font-size:15px;font-weight:720;letter-spacing:-.01em}.hint{margin:7px 0 14px;color:#64748b;font-size:13px;line-height:1.55;font-weight:400}.check-row{display:flex;align-items:flex-start;gap:10px;margin-top:11px;font-weight:540;color:#334155;font-size:13.5px;line-height:1.5}.check-row span{font-weight:540}.check-row input{width:16px;height:16px;margin-top:2px;accent-color:#2563eb}.input-row{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;margin-top:14px}.input-row label span{display:block;font-size:10px;font-weight:720;color:#64748b;text-transform:uppercase;letter-spacing:.08em;margin-bottom:6px}.input-row input,.input-row select{width:100%;height:42px;border:1px solid #cbd5e1;border-radius:13px;padding:0 12px;font-weight:560;outline:none;background:#fff;color:#0f172a}.pref-footer{padding:0 26px 24px;display:flex;justify-content:flex-end}
.setup-list{display:grid;grid-template-columns:1fr;gap:16px;padding:22px}.setup-card{border:1px solid #e2e8f0;background:#fff;border-radius:22px;box-shadow:0 10px 24px rgba(15,23,42,.04);overflow:hidden}.setup-top{display:flex;justify-content:space-between;gap:16px;flex-wrap:wrap;padding:20px 22px;border-bottom:1px solid #e2e8f0;background:linear-gradient(135deg,#f8fafc,#fff)}.setup-heading{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.setup-number{display:inline-flex;align-items:center;justify-content:center;min-width:34px;height:28px;border-radius:999px;background:#eff6ff;color:#1d4ed8;border:1px solid #bfdbfe;font-size:12px;font-weight:700}.setup-title{font-size:19px;font-weight:760;letter-spacing:-.035em}.setup-sub{display:block;margin-top:5px;color:#64748b;font-size:12.5px;font-weight:520;line-height:1.5}.setup-body{display:grid;grid-template-columns:1.15fr 1.05fr 1fr;gap:16px;padding:20px 22px}
.block{background:#fff;border:1px solid #e2e8f0;border-radius:16px;padding:16px}.block-title{display:block;color:#64748b;font-size:10.5px;font-weight:720;text-transform:uppercase;letter-spacing:.09em;margin-bottom:12px}.kv{display:flex;align-items:center;justify-content:space-between;gap:14px;margin-top:9px}.kv:first-of-type{margin-top:0}.k{color:#64748b;font-size:12.5px;font-weight:520}.v{font-weight:600;color:#0f172a;text-align:right;font-size:13.5px;line-height:1.45}.pill{display:inline-flex;align-items:center;justify-content:center;min-height:28px;border-radius:999px;padding:0 11px;font-size:12px;font-weight:700;border:1px solid transparent;white-space:nowrap}.side-buy{background:#ecfdf5;color:#047857;border-color:#a7f3d0}.side-sell{background:#fef2f2;color:#b91c1c;border-color:#fecaca}.stage-tracking{background:#eff6ff;color:#1d4ed8;border-color:#bfdbfe}.stage-zone{background:#fff7ed;color:#c2410c;border-color:#fed7aa}.stage-swept{background:#fefce8;color:#a16207;border-color:#fde68a}.stage-structure{background:#f5f3ff;color:#6d28d9;border-color:#ddd6fe}.stage-ready{background:#ecfdf5;color:#047857;border-color:#a7f3d0}.stage-sent{background:#f1f5f9;color:#334155;border-color:#cbd5e1}.stage-danger{background:#fef2f2;color:#b91c1c;border-color:#fecaca}
.check-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:6px}.tile{border-radius:10px;padding:7px 8px;text-align:center;font-weight:700;font-size:11px}.ok{background:#ecfdf5;color:#047857}.bad{background:#fef2f2;color:#b91c1c}.pending{background:#fffbeb;color:#b45309}
.decision{background:#f8fafc;border:1px solid #e2e8f0;border-radius:16px;padding:15px 16px;line-height:1.62;color:#475569;font-size:13.5px;font-weight:500}.decision strong{display:block;color:#0f172a;margin-bottom:6px;font-size:14px;font-weight:720}.decision-ready{background:#ecfdf5;border-color:#a7f3d0;color:#065f46}.decision-progress{background:#eff6ff;border-color:#bfdbfe;color:#1e3a8a}.decision-review{background:#fff7ed;border-color:#fed7aa;color:#9a3412}.decision-danger{background:#fef2f2;border-color:#fecaca;color:#991b1b}
.actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:14px}.actions form{margin:0}
.empty{padding:44px 26px 50px;text-align:center}.empty h3{margin:0;font-size:22px;font-weight:800}.empty p{margin:10px auto 0;color:#64748b;max-width:560px;line-height:1.7}
.pagination{padding:20px 24px;border-top:1px solid #e2e8f0;display:flex;align-items:center;justify-content:space-between;gap:14px;flex-wrap:wrap}.page-info{color:#64748b;font-size:12.5px;font-weight:700}.page-controls{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.page-current{background:#f8fafc;border:1px solid #e2e8f0;border-radius:14px;padding:10px 14px;font-size:12.5px;font-weight:800;color:#0f172a}
@media(max-width:980px){.topbar-inner{flex-direction:column;align-items:flex-start}.stats{grid-template-columns:repeat(2,minmax(0,1fr))}.pref-grid{grid-template-columns:1fr}.setup-body{grid-template-columns:1fr}.wrap{padding-left:14px;padding-right:14px}}
@media(max-width:560px){.topbar{padding:26px 18px}.stats{grid-template-columns:1fr}.input-row{grid-template-columns:1fr}.pref-footer{justify-content:stretch}.pref-footer .btn{width:100%}.setup-top{padding:18px}.setup-body{padding:18px}.panel-head{padding:20px}.setup-list{padding:16px}}
</style>
</head>
<body>

<header class="topbar">
    <div class="topbar-inner">
        <div>
            <div class="eyebrow">Alert Center</div>
            <h1>My Alerts</h1>
            <p>Review monitored setups, confirmation flow, notification status and final setup delivery in one place.</p>
        </div>

        <div class="nav-actions">
            <span class="tz-badge">Time zone: <?= e($userTimezone) ?></span>
            <a class="btn btn-dark" href="settings.php">Settings</a>
            <a class="btn" href="dashboard.php">Back to Dashboard</a>
        </div>
    </div>
</header>

<main class="wrap">

    <section class="stats">
        <div class="stat"><span>Total Setups</span><strong class="slate"><?= (int)$totalAlerts ?></strong></div>
        <div class="stat"><span>Active</span><strong class="blue"><?= (int)$activeAlerts ?></strong></div>
        <div class="stat"><span>Ready</span><strong class="green"><?= (int)$readyAlerts ?></strong></div>
        <div class="stat"><span>Delivered</span><strong class="green"><?= (int)$sentAlerts ?></strong></div>
        <div class="stat"><span>Paused</span><strong class="amber"><?= (int)$pausedAlerts ?></strong></div>
    </section>

    <?php if (!empty($_SESSION['alert_action_message'])): ?>
        <div class="notice notice-success"><?= e($_SESSION['alert_action_message']) ?></div>
        <?php unset($_SESSION['alert_action_message']); ?>
    <?php endif; ?>

    <?php if (!empty($_SESSION['alert_action_error'])): ?>
        <div class="notice notice-error"><?= e($_SESSION['alert_action_error']) ?></div>
        <?php unset($_SESSION['alert_action_error']); ?>
    <?php endif; ?>

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

    <?php if ($pendingSuggestedSetups > 0): ?>
        <div class="notice notice-success" style="display:flex;justify-content:space-between;gap:14px;align-items:center;flex-wrap:wrap;">
            <span><?= (int)$pendingSuggestedSetups ?> suggested setup<?= $pendingSuggestedSetups === 1 ? '' : 's' ?> available for review. A final alert was preserved because a new entry moved outside the original tracked zone.</span>
            <a class="btn btn-small" href="suggested_setups.php">Review Suggested Setups</a>
        </div>
    <?php endif; ?>

    <section class="panel">
        <div class="panel-head">
            <div>
                <h2>Alert Preferences</h2>
                <p>Choose the stages you want to be notified about and how market-news cautions should appear.</p>
            </div>
        </div>

        <form method="post">
            <input type="hidden" name="action" value="save_alert_preferences">

            <div class="pref-grid">
                <div class="pref-box">
                    <h3>Market News Cautions</h3>
                    <p class="hint">Show a caution note around scheduled market events without stopping valid setup monitoring.</p>

                    <label class="check-row"><input type="checkbox" name="avoid_news_trades" value="1" <?= !empty($userPreferences['avoid_news_trades']) ? 'checked' : '' ?>> <span>Show a caution note when major news is close</span></label>

                    <?php if (user_has_column('trade_high_impact_news')): ?>
                    <label class="check-row"><input type="checkbox" name="trade_high_impact_news" value="1" <?= !empty($userPreferences['trade_high_impact_news']) ? 'checked' : '' ?>> <span>Allow alerts during high-impact news</span></label>
                    <?php endif; ?>

                    <?php if (user_has_column('trade_medium_impact_news')): ?>
                    <label class="check-row"><input type="checkbox" name="trade_medium_impact_news" value="1" <?= !empty($userPreferences['trade_medium_impact_news']) ? 'checked' : '' ?>> <span>Allow alerts during medium-impact news</span></label>
                    <?php endif; ?>

                    <div class="input-row">
                        <label><span>Minutes Before</span><input type="number" name="news_block_minutes_before" min="15" max="720" value="<?= e($userPreferences['news_block_minutes_before'] ?? 60) ?>"></label>
                        <label><span>Minutes After</span><input type="number" name="news_block_minutes_after" min="0" max="720" value="<?= e($userPreferences['news_block_minutes_after'] ?? 30) ?>"></label>
                    </div>
                </div>

                <div class="pref-box">
                    <h3>Stage Notifications</h3>
                    <p class="hint">Select the monitoring stages where you want to receive updates.</p>

                    <label class="check-row"><input type="checkbox" name="notify_stage_1" value="1" <?= !empty($userPreferences['notify_stage_1']) ? 'checked' : '' ?>> <span>Stage 1 - Zone Reached</span></label>
                    <label class="check-row"><input type="checkbox" name="notify_stage_2" value="1" <?= !empty($userPreferences['notify_stage_2']) ? 'checked' : '' ?>> <span>Stage 2 - Liquidity Swept</span></label>
                    <label class="check-row"><input type="checkbox" name="notify_stage_3" value="1" <?= !empty($userPreferences['notify_stage_3']) ? 'checked' : '' ?>> <span>Stage 3 - Structure Confirmed</span></label>
                    <label class="check-row"><input type="checkbox" name="notify_final_setup" value="1" <?= !empty($userPreferences['notify_final_setup']) ? 'checked' : '' ?>> <span>Final Setup Ready</span></label>
                </div>

                <div class="pref-box">
                    <h3>Setup Expiration</h3>
                    <p class="hint">Optional. Leave this off when you want setups to stay active until you pause, delete, or complete them.</p>

                    <label class="check-row"><input type="checkbox" name="auto_expire_enabled" value="1" <?= !empty($userPreferences['auto_expire_enabled']) ? 'checked' : '' ?>> <span>Auto-expire newly tracked setups</span></label>

                    <div class="input-row">
                        <label>
                            <span>Expiration Window</span>
                            <?php $exp = (string)($userPreferences['expiration_option'] ?? 'never'); ?>
                            <select name="expiration_option">
                                <?php foreach (['never'=>'Never Expire','1h'=>'1 Hour','4h'=>'4 Hours','12h'=>'12 Hours','24h'=>'24 Hours','48h'=>'48 Hours','3d'=>'3 Days','1w'=>'1 Week'] as $key => $label): ?>
                                    <option value="<?= e($key) ?>" <?= $exp === $key ? 'selected' : '' ?>><?= e($label) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </label>
                    </div>
                </div>
            </div>

            <div class="pref-footer">
                <button class="btn" type="submit">Save Preferences</button>
            </div>
        </form>
    </section>

    <section class="panel">
        <div class="panel-head">
            <div>
                <h2>Tracked Setups</h2>
                <p>Production view of monitored setups, confirmation timeframe, current stage and delivery status. Ready counts setups awaiting final delivery; Delivered counts alerts already sent.</p>
            </div>

            <div class="tz-badge"><?= (int)$totalAlerts ?> total &bull; <?= (int)$activeAlerts ?> active &bull; <?= (int)$readyAlerts ?> ready &bull; Page <?= (int)$currentPage ?> of <?= (int)$totalPages ?></div>
        </div>

        <?php if (empty($alerts)): ?>
            <div class="empty">
                <h3>No tracked setups yet</h3>
                <p>Tracked setups appear here with their stage, confirmation timeframe and final delivery status.</p>
                <p style="margin-top:18px;"><a class="btn" href="dashboard.php">Go to Dashboard</a></p>
            </div>
        <?php else: ?>
            <div class="setup-list">
                <?php foreach ($pagedAlerts as $index => $alert): ?>
                    <?php
                        [$market, $evaluation, $checklist] = alert_snapshot($alert);
                        $userStatus = alert_user_setup_status($alert, $market, $evaluation, $checklist);
                        $setupTf = alert_timeframe_label($market['setup_timeframe'] ?? ($alert['timeframe'] ?? 'N/A'));
                        $mappedConfirmTf = alert_confirmation_timeframe_for_setup($alert['timeframe'] ?? '');
                        $actualScanTf = alert_timeframe_label($market['scan_timeframe'] ?? ($market['confirmation_timeframe'] ?? $mappedConfirmTf));
                        $confirmTf = $mappedConfirmTf;
                        $usingLtf = !empty($market['using_confirmation_timeframe']);
                        $sideClass = strtoupper((string)($alert['side'] ?? '')) === 'BUY' ? 'side-buy' : 'side-sell';
                    ?>
                    <article class="setup-card">
                        <div class="setup-top">
                            <div>
                                <div class="setup-heading"><span class="setup-number">#<?= (int)($offset + $index + 1) ?></span><div class="setup-title"><?= e(clean_alert_text($alert['symbol'] ?? 'N/A')) ?> <?= e(clean_alert_text($alert['side'] ?? '')) ?></div></div>
                                <span class="setup-sub">
                                    <?= e(clean_alert_text($alert['style'] ?? 'N/A')) ?> &bull;
                                    Created <?= e(user_time_label($alert['tracking_started_at'] ?? ($alert['created_at'] ?? ''), $userTimezone, 'N/A', $userTimezone)) ?> &bull;
                                    Email: <?= !empty($alert['email_enabled']) ? 'Yes' : 'No' ?> &bull;
                                    Telegram: <?= !empty($alert['telegram_enabled']) ? 'Yes' : 'No' ?>
                                </span>
                            </div>
                            <div style="display:flex;gap:8px;align-items:flex-start;flex-wrap:wrap;">
                                <span class="pill <?= e($sideClass) ?>"><?= e(clean_alert_text($alert['side'] ?? 'N/A')) ?></span>
                                <span class="pill <?= e(alert_stage_class($alert['lifecycle_stage'] ?? 'TRACKING')) ?>"><?= e(alert_stage_label($alert['lifecycle_stage'] ?? 'TRACKING')) ?></span>
                                <?php if (!empty($suggestedByAlert[(int)($alert['id'] ?? 0)])): ?>
                                    <a class="pill" style="background:#fef3c7;color:#92400e;text-decoration:none;" href="suggested_setups.php">Suggested Setup <?= (int)$suggestedByAlert[(int)$alert['id']] ?></a>
                                <?php endif; ?>
                            </div>
                        </div>

                        <div class="setup-body">
                            <div class="block">
                                <span class="block-title">Timeframe flow</span>
                                <div class="kv"><span class="k">Setup TF</span><span class="v"><?= e($setupTf) ?></span></div>
                                <div class="kv"><span class="k">Confirm TF</span><span class="v"><?= e($confirmTf) ?></span></div>
                                <div class="kv"><span class="k">Mode</span><span class="v"><?= $usingLtf ? 'LTF active' : ('LTF waiting; scan ' . e($actualScanTf)) ?></span></div>
                                <div class="kv"><span class="k">Last checked</span><span class="v"><?= e(user_time_label($alert['last_checked_at'] ?? '', $userTimezone, 'Not checked', $databaseTimezone)) ?></span></div>
                            </div>

                            <div class="block">
                                <span class="block-title">Execution</span>
                                <div class="kv"><span class="k">Entry</span><span class="v"><?= e(price_value($alert['entry_price'] ?? null)) ?></span></div>
                                <div class="kv"><span class="k">SL</span><span class="v"><?= e(price_value($alert['stop_loss'] ?? null)) ?></span></div>
                                <div class="kv"><span class="k">TP1</span><span class="v"><?= e(price_value($alert['tp1'] ?? null)) ?></span></div>
                                <div class="kv"><span class="k">Current</span><span class="v"><?= e(price_value($market['current_price'] ?? null)) ?></span></div>
                            </div>

                            <div class="block">
                                <span class="block-title">Progress</span>
                                <div class="kv"><span class="k">S1</span><span class="v"><?= e(user_time_label($alert['stage1_sent_at'] ?? '', $userTimezone, 'Pending', $databaseTimezone)) ?></span></div>
                                <div class="kv"><span class="k">S2</span><span class="v"><?= e(user_time_label($alert['stage2_sent_at'] ?? '', $userTimezone, 'Pending', $databaseTimezone)) ?></span></div>
                                <div class="kv"><span class="k">S3</span><span class="v"><?= e(user_time_label($alert['stage3_sent_at'] ?? '', $userTimezone, 'Pending', $databaseTimezone)) ?></span></div>
                                <div class="kv"><span class="k">Final</span><span class="v"><?= e(user_time_label($alert['final_sent_at'] ?? ($alert['triggered_at'] ?? ''), $userTimezone, 'Pending', $databaseTimezone)) ?></span></div>
                            </div>
                        </div>

                        <div style="padding:0 22px 20px;">
                            <div class="decision <?= e(decision_tone_class($userStatus['tone'] ?? 'progress')) ?>">
                                <strong><?= e($userStatus['title'] ?? 'Setup status') ?></strong>
                                <?= e($userStatus['message'] ?? 'Monitoring this setup for the next confirmation stage.') ?>
                            </div>

                            <div class="actions">
                                <?php if (empty($alert['triggered_at'])): ?>
                                    <form method="post" action="alert_action.php">
                                        <input type="hidden" name="alert_id" value="<?= e($alert['id'] ?? '') ?>">
                                        <input type="hidden" name="action" value="<?= !empty($alert['is_active']) ? 'pause' : 'resume' ?>">
                                        <button class="btn btn-small btn-muted" type="submit"><?= !empty($alert['is_active']) ? 'Pause' : 'Resume' ?></button>
                                    </form>
                                <?php endif; ?>

                                <a class="btn btn-small" href="alert_view.php?id=<?= e($alert['id'] ?? '') ?>">View Details</a>
                                <?php if (!empty($suggestedByAlert[(int)($alert['id'] ?? 0)])): ?>
                                    <a class="btn btn-small btn-soft" href="suggested_setups.php">Review Suggested Setup</a>
                                <?php endif; ?>

                                <form method="post" action="alert_action.php" onsubmit="return confirm('Delete this tracked setup?');">
                                    <input type="hidden" name="alert_id" value="<?= e($alert['id'] ?? '') ?>">
                                    <input type="hidden" name="action" value="delete">
                                    <button class="btn btn-small btn-soft-red" type="submit">Delete</button>
                                </form>
                            </div>
                        </div>
                    </article>
                <?php endforeach; ?>
            </div>

            <div class="pagination">
                <div class="page-info">
                    Showing <?= (int)$fromAlert ?> to <?= (int)$toAlert ?> of <?= (int)count($alerts) ?> tracked setups
                </div>

                <div class="page-controls">
                    <?php if ($currentPage > 1): ?><a class="btn btn-small btn-soft" href="?page=<?= (int)($currentPage - 1) ?>">Previous</a><?php endif; ?>
                    <span class="page-current">Page <?= (int)$currentPage ?> of <?= (int)$totalPages ?></span>
                    <?php if ($currentPage < $totalPages): ?><a class="btn btn-small" href="?page=<?= (int)($currentPage + 1) ?>">Next</a><?php endif; ?>
                </div>
            </div>
        <?php endif; ?>
    </section>

</main>

</body>
</html>
