<?php

require_once __DIR__ . '/admin_tool_helper.php';

/*
|--------------------------------------------------------------------------
| Safe local 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;
        }
    }
}

function alert_setting_get($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 ? $value : $default;
    } catch (Throwable $e) {
        return $default;
    }
}

function alert_setting_save($key, $value)
{
    try {
        $columns = db()->query("SHOW COLUMNS FROM system_settings")->fetchAll(PDO::FETCH_COLUMN) ?: [];
        $columns = array_map('strtolower', $columns);

        if (in_array('created_at', $columns, true) && in_array('updated_at', $columns, true)) {
            $stmt = db()->prepare("
                INSERT INTO system_settings (setting_key, setting_value, created_at, updated_at)
                VALUES (?, ?, NOW(), NOW())
                ON DUPLICATE KEY UPDATE
                    setting_value = VALUES(setting_value),
                    updated_at = NOW()
            ");
            $stmt->execute([$key, $value]);
            return;
        }

        $stmt = db()->prepare("
            INSERT INTO system_settings (setting_key, setting_value)
            VALUES (?, ?)
            ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)
        ");
        $stmt->execute([$key, $value]);
    } catch (Throwable $e) {
        throw $e;
    }
}

function alert_template_get($key, $default = '')
{
    if (!admin_table_exists_local('alert_templates')) {
        return $default;
    }

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

        if ($value !== false) {
            return $value;
        }

        $stmt = db()->prepare("SELECT body FROM alert_templates WHERE template_key = ? LIMIT 1");
        $stmt->execute([$key]);
        $value = $stmt->fetchColumn();

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

function alert_template_save($key, $channel, $subject, $body)
{
    if (!admin_table_exists_local('alert_templates')) {
        return;
    }

    try {
        $stmt = db()->prepare("
            INSERT INTO alert_templates
                (template_key, channel, subject, template_body, is_active, created_at, updated_at)
            VALUES
                (?, ?, ?, ?, 1, NOW(), NOW())
            ON DUPLICATE KEY UPDATE
                channel = VALUES(channel),
                subject = VALUES(subject),
                template_body = VALUES(template_body),
                is_active = 1,
                updated_at = NOW()
        ");
        $stmt->execute([$key, $channel, $subject, $body]);
        return;
    } catch (Throwable $e) {
    }

    try {
        $stmt = db()->prepare("
            INSERT INTO alert_templates
                (template_key, channel, subject, body, is_active, created_at, updated_at)
            VALUES
                (?, ?, ?, ?, 1, NOW(), NOW())
            ON DUPLICATE KEY UPDATE
                channel = VALUES(channel),
                subject = VALUES(subject),
                body = VALUES(body),
                is_active = 1,
                updated_at = NOW()
        ");
        $stmt->execute([$key, $channel, $subject, $body]);
    } catch (Throwable $e) {
    }
}

/*
|--------------------------------------------------------------------------
| Defaults
|--------------------------------------------------------------------------
*/

$defaultEmailSubject = '{{symbol}} {{side}} Institutional Setup Ready';

$defaultEmailBody = <<<'HTML'
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>Institutional Setup Ready</title></head>
<body style="margin:0;padding:0;background:#f1f5f9;font-family:Arial,sans-serif;color:#0f172a;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f1f5f9;padding:28px 12px;">
<tr><td align="center">
<table role="presentation" width="680" cellpadding="0" cellspacing="0" style="max-width:680px;background:#ffffff;border-radius:18px;overflow:hidden;border:1px solid #e2e8f0;">
<tr><td style="background:#0f172a;padding:26px 30px;color:#ffffff;">
<div style="font-size:26px;font-weight:800;letter-spacing:-0.02em;">Institutional Setup Ready</div>
<div style="margin-top:7px;color:#cbd5e1;font-size:14px;">{{symbol}} • {{side}} • Setup {{setup_timeframe}} • Confirm {{scan_timeframe}}</div>
</td></tr>
<tr><td style="padding:30px;">
<p style="margin:0 0 16px;font-size:15px;line-height:1.7;">Hi <strong>{{name}}</strong>,</p>
<p style="margin:0 0 22px;font-size:15px;line-height:1.7;">{{message}}</p>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;border:1px solid #e2e8f0;border-radius:12px;overflow:hidden;">
<tr><td style="padding:13px 16px;background:#f8fafc;color:#64748b;font-weight:bold;">Current Price</td><td style="padding:13px 16px;background:#f8fafc;font-weight:bold;">{{current_price}}</td></tr>
<tr><td style="padding:13px 16px;color:#64748b;font-weight:bold;">Entry Zone</td><td style="padding:13px 16px;">{{entry_zone}}</td></tr>
<tr><td style="padding:13px 16px;background:#f8fafc;color:#64748b;font-weight:bold;">New Entry</td><td style="padding:13px 16px;background:#f8fafc;font-weight:bold;">{{entry_price}}</td></tr>
<tr><td style="padding:13px 16px;color:#64748b;font-weight:bold;">Stop Loss</td><td style="padding:13px 16px;color:#dc2626;font-weight:bold;">{{stop_loss}}</td></tr>
<tr><td style="padding:13px 16px;background:#f8fafc;color:#64748b;font-weight:bold;">Targets</td><td style="padding:13px 16px;background:#f8fafc;color:#16a34a;font-weight:bold;">{{targets_summary}}</td></tr>
<tr><td style="padding:13px 16px;color:#64748b;font-weight:bold;">Risk Distance</td><td style="padding:13px 16px;">{{risk_distance_label}}</td></tr>
<tr><td style="padding:13px 16px;background:#f8fafc;color:#64748b;font-weight:bold;">Checklist</td><td style="padding:13px 16px;background:#f8fafc;">{{execution_checklist_status}}</td></tr>
</table>
{{execution_checklist_html}}
<p style="margin:24px 0 0;color:#64748b;font-size:12px;line-height:1.7;">Important: This is not financial advice. Use your own risk management before execution.</p>
</td></tr>
</table>
</td></tr>
</table>
</body>
</html>
HTML;

$defaultTelegram = <<<'TXT'
<b>Institutional Setup Ready</b>

<b>{{symbol}} {{side}}</b> • Setup {{setup_timeframe}} • Confirm {{scan_timeframe}}
<b>Current Price:</b> {{current_price}}
<b>Entry Zone:</b> {{entry_zone}}
<b>New Entry:</b> {{entry_price}}
<b>Stop Loss:</b> {{stop_loss}}
<b>Targets:</b> {{targets_summary}}
<b>Risk Distance:</b> {{risk_distance_label}}

{{execution_checklist_telegram}}

<b>Next Step:</b> {{next_step}}
Use proper risk management.
TXT;

$defaultStageZone = <<<'TXT'
<b>Stage 1: Zone Approached</b>

<b>{{symbol}} {{side}}</b> • Setup {{setup_timeframe}} • Confirm {{scan_timeframe}}
<b>Current Price:</b> {{current_price}}
<b>Tracked Zone:</b> {{entry_zone}}

<b>Status:</b> Fresh post-baseline touch/entry into the tracked zone.
{{execution_checklist_telegram}}

<b>Next Step:</b> Wait for a fresh liquidity sweep.
TXT;

$defaultStageSweep = <<<'TXT'
<b>Stage 2: Liquidity Swept</b>

<b>{{symbol}} {{side}}</b> • Setup {{setup_timeframe}} • Confirm {{scan_timeframe}}
<b>Current Price:</b> {{current_price}}
<b>Tracked Zone:</b> {{entry_zone}}

<b>Status:</b> Fresh liquidity sweep after Stage 1.
{{execution_checklist_telegram}}

<b>Next Step:</b> Wait for displacement / BOS / CHoCH confirmation.
TXT;

$defaultStageStructure = <<<'TXT'
<b>Stage 3: Structure Confirmed</b>

<b>{{symbol}} {{side}}</b> • Setup {{setup_timeframe}} • Confirm {{scan_timeframe}}
<b>Current Price:</b> {{current_price}}
<b>Tracked Zone:</b> {{entry_zone}}

<b>Status:</b> Closed-candle BOS/CHoCH confirmation detected.
{{execution_checklist_telegram}}

<b>Next Step:</b> Wait for final checklist and risk validation.
TXT;

$defaultStageZoneEmail = '<h2 style="margin-top:0;color:#2563eb;">Stage 1: Zone Approached</h2><p><strong>{{symbol}} {{side}}</strong> • Setup {{setup_timeframe}} • Confirm {{scan_timeframe}}</p><p>Fresh post-baseline touch/entry into the tracked zone.</p><p><strong>Entry Zone:</strong> {{entry_zone}}</p><p><strong>Current Price:</strong> {{current_price}}</p>{{execution_checklist_html}}';

$defaultStageSweepEmail = '<h2 style="margin-top:0;color:#2563eb;">Stage 2: Liquidity Sweep Detected</h2><p><strong>{{symbol}} {{side}}</strong> • Setup {{setup_timeframe}} • Confirm {{scan_timeframe}}</p><p>Liquidity has been swept after Stage 1.</p><p><strong>Entry Zone:</strong> {{entry_zone}}</p><p><strong>Current Price:</strong> {{current_price}}</p>{{execution_checklist_html}}';

$defaultStageStructureEmail = '<h2 style="margin-top:0;color:#2563eb;">Stage 3: Structure Confirmed</h2><p><strong>{{symbol}} {{side}}</strong> • Setup {{setup_timeframe}} • Confirm {{scan_timeframe}}</p><p>BOS/CHoCH confirmation has been detected after the liquidity sweep.</p><p><strong>Current Price:</strong> {{current_price}}</p>{{execution_checklist_html}}';

$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $settings = [
            'smtp_host',
            'smtp_port',
            'smtp_username',
            'smtp_encryption',
            'system_email',
            'system_from_name',
            'telegram_bot_token',
        ];

        foreach ($settings as $key) {
            alert_setting_save($key, trim($_POST[$key] ?? ''));
        }

        if (trim($_POST['smtp_password'] ?? '') !== '') {
            alert_setting_save('smtp_password', $_POST['smtp_password']);
        }

        /*
        |--------------------------------------------------------------------------
        | Stage delivery and final execution controls
        |--------------------------------------------------------------------------
        */
        alert_setting_save('send_stage_alerts', !empty($_POST['send_stage_alerts']) ? '1' : '0');
        alert_setting_save('stage_1_zone_alert', !empty($_POST['stage_1_zone_alert']) ? '1' : '0');
        alert_setting_save('stage_2_liquidity_alert', !empty($_POST['stage_2_liquidity_alert']) ? '1' : '0');
        alert_setting_save('stage_3_bos_alert', !empty($_POST['stage_3_bos_alert']) ? '1' : '0');
        alert_setting_save('stage_4_execution_alert', !empty($_POST['stage_4_execution_alert']) ? '1' : '0');
        alert_setting_save('require_candle_close_confirmation', !empty($_POST['require_candle_close_confirmation']) ? '1' : '0');

        /*
        |--------------------------------------------------------------------------
        | Lower-timeframe execution confirmation
        |--------------------------------------------------------------------------
        */
        alert_setting_save('alert_use_ltf_confirmation', !empty($_POST['alert_use_ltf_confirmation']) ? '1' : '0');
        alert_setting_save('alert_confirmation_timeframe_map', trim($_POST['alert_confirmation_timeframe_map'] ?? '15m:5m,30m:5m,1h:15m,2h:15m,4h:1h,1d:4h'));
        alert_setting_save('displacement_min_body_ratio', trim($_POST['displacement_min_body_ratio'] ?? '0.55'));

        /*
        |--------------------------------------------------------------------------
        | Developer Test Mode
        |--------------------------------------------------------------------------
        */
        alert_setting_save('test_mode', !empty($_POST['test_mode']) ? '1' : '0');
        alert_setting_save('simulate_zone_touch', !empty($_POST['simulate_zone_touch']) ? '1' : '0');
        alert_setting_save('simulate_liquidity_sweep', !empty($_POST['simulate_liquidity_sweep']) ? '1' : '0');
        alert_setting_save('simulate_structure_break', !empty($_POST['simulate_structure_break']) ? '1' : '0');
        alert_setting_save('simulate_ready_setup', !empty($_POST['simulate_ready_setup']) ? '1' : '0');

        /*
        |--------------------------------------------------------------------------
        | Multi-Timeframe Confirmation Settings
        |--------------------------------------------------------------------------
        */
        alert_setting_save('enable_mtf_confirmation', !empty($_POST['enable_mtf_confirmation']) ? '1' : '0');
        alert_setting_save('mtf_confirmation_mode', trim($_POST['mtf_confirmation_mode'] ?? 'score'));
        alert_setting_save('mtf_strictness_mode', trim($_POST['mtf_confirmation_mode'] ?? 'medium'));
        alert_setting_save('mtf_score_weight', trim($_POST['mtf_score_weight'] ?? '25'));
        alert_setting_save('mtf_strictness_scalper', trim($_POST['mtf_strictness_scalper'] ?? 'relaxed'));
        alert_setting_save('mtf_strictness_intraday', trim($_POST['mtf_strictness_intraday'] ?? 'medium'));
        alert_setting_save('mtf_strictness_swing', trim($_POST['mtf_strictness_swing'] ?? 'strict'));
        alert_setting_save('mtf_required_agreement_count', trim($_POST['mtf_required_agreement_count'] ?? '1'));
        alert_setting_save('mtf_confirmation_timeframes', trim($_POST['mtf_confirmation_timeframes'] ?? ''));
        alert_setting_save('minimum_quality_score', trim($_POST['minimum_quality_score'] ?? '60'));

        alert_template_save('institutional_alert_email_subject', 'email_subject', 'Institutional Alert Email Subject', $_POST['email_subject'] ?? $defaultEmailSubject);
        alert_template_save('institutional_alert_email_body', 'email', 'Institutional Alert Email Body', $_POST['email_body'] ?? $defaultEmailBody);
        alert_template_save('institutional_alert_telegram_body', 'telegram', 'Telegram Final Alert', $_POST['telegram_body'] ?? $defaultTelegram);
        alert_template_save('stage_zone_approached_telegram', 'telegram', 'Stage 1 Zone Approached', $_POST['stage_zone'] ?? $defaultStageZone);
        alert_template_save('stage_liquidity_swept_telegram', 'telegram', 'Stage 2 Liquidity Swept', $_POST['stage_sweep'] ?? $defaultStageSweep);
        alert_template_save('stage_structure_confirmed_telegram', 'telegram', 'Stage 3 Structure Confirmed', $_POST['stage_structure'] ?? $defaultStageStructure);
        alert_template_save('stage_zone_approached_email', 'email', 'Stage 1 Zone Approached Email', $_POST['stage_zone_email'] ?? $defaultStageZoneEmail);
        alert_template_save('stage_liquidity_swept_email', 'email', 'Stage 2 Liquidity Swept Email', $_POST['stage_sweep_email'] ?? $defaultStageSweepEmail);
        alert_template_save('stage_structure_confirmed_email', 'email', 'Stage 3 Structure Confirmed Email', $_POST['stage_structure_email'] ?? $defaultStageStructureEmail);

        $message = 'SMTP, Telegram, LTF confirmation, checklist controls, MTF settings and templates saved successfully.';
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

admin_layout_header('SMTP, Telegram & Alert Templates');

?>

<style>
.alert-page{max-width:1400px;margin:0 auto}.alert-title{font-size:38px;font-weight:900;letter-spacing:-.04em;color:#020617}.alert-subtitle{margin-top:8px;color:#64748b;font-size:15px}.alert-grid{display:grid;grid-template-columns:minmax(0,1fr) 420px;gap:22px;margin-top:28px;align-items:start}.alert-card{background:#fff;border:1px solid #e2e8f0;border-radius:26px;box-shadow:0 10px 26px rgba(15,23,42,.045);overflow:hidden;margin-bottom:22px}.alert-card-head{padding:22px 24px;border-bottom:1px solid #e2e8f0;background:linear-gradient(135deg,rgba(37,99,235,.06),rgba(15,23,42,.02)),#fff}.alert-card-title{font-size:22px;font-weight:900;color:#020617}.alert-card-sub{margin-top:4px;font-size:13px;color:#64748b}.alert-card-body{padding:24px}.alert-fields{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}.alert-label{display:block;margin-bottom:7px;color:#64748b;font-size:11px;font-weight:900;text-transform:uppercase;letter-spacing:.06em}.alert-input,.alert-select,.alert-textarea{width:100%;border:1px solid #cbd5e1;border-radius:14px;background:#fff;color:#0f172a;font-weight:700;outline:none}.alert-input,.alert-select{height:46px;padding:0 14px}.alert-textarea{padding:14px;min-height:150px;font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;font-size:13px;line-height:1.5}.alert-input:focus,.alert-select:focus,.alert-textarea:focus{border-color:#2563eb;box-shadow:0 0 0 4px rgba(37,99,235,.12)}.alert-section{margin-bottom:22px}.alert-section:last-child{margin-bottom:0}.alert-help{background:#f8fafc;border:1px solid #e2e8f0;border-radius:18px;padding:16px;color:#475569;font-size:13px;line-height:1.6}.alert-save{margin-top:24px;display:flex;justify-content:flex-end}.alert-btn{height:48px;border:0;border-radius:16px;padding:0 26px;background:#2563eb;color:white;font-weight:900;cursor:pointer;box-shadow:0 12px 24px rgba(37,99,235,.22)}.alert-msg{margin-top:20px;padding:14px 18px;border-radius:16px;font-weight:800;font-size:14px}.alert-success{background:#ecfdf5;border:1px solid #a7f3d0;color:#047857}.alert-error{background:#fef2f2;border:1px solid #fecaca;color:#b91c1c}.check-line{display:flex;align-items:center;gap:10px;font-weight:800;color:#334155;line-height:1.45}.check-line input{width:16px;height:16px;accent-color:#2563eb}.muted-note{font-size:12.5px;color:#64748b;line-height:1.6;margin-top:8px}@media(max-width:1100px){.alert-grid{grid-template-columns:1fr}.alert-fields{grid-template-columns:1fr}}
</style>

<div class="alert-page">

    <div>
        <div class="alert-title">SMTP, Telegram & Alert Templates</div>
        <div class="alert-subtitle">Configure delivery channels, lower-timeframe confirmation, execution checklist rules and alert templates.</div>
    </div>

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

    <form method="post">
        <div class="alert-grid">
            <div>

                <section class="alert-card">
                    <div class="alert-card-head">
                        <div class="alert-card-title">Email Delivery</div>
                        <div class="alert-card-sub">SMTP settings are stored in the system_settings table.</div>
                    </div>
                    <div class="alert-card-body">
                        <div class="alert-fields">
                            <label><span class="alert-label">SMTP Host</span><input class="alert-input" name="smtp_host" value="<?= e(alert_setting_get('smtp_host')) ?>" placeholder="smtp.yourdomain.com"></label>
                            <label><span class="alert-label">SMTP Port</span><input class="alert-input" name="smtp_port" value="<?= e(alert_setting_get('smtp_port', '587')) ?>" placeholder="587"></label>
                            <label><span class="alert-label">SMTP Username</span><input class="alert-input" name="smtp_username" value="<?= e(alert_setting_get('smtp_username')) ?>" placeholder="alerts@yourdomain.com"></label>
                            <label><span class="alert-label">SMTP Password</span><input class="alert-input" type="password" name="smtp_password" placeholder="Leave blank to keep current password"></label>
                            <label><span class="alert-label">Encryption</span><?php $enc = alert_setting_get('smtp_encryption', 'tls'); ?><select class="alert-select" name="smtp_encryption"><option value="tls" <?= $enc === 'tls' ? 'selected' : '' ?>>TLS</option><option value="ssl" <?= $enc === 'ssl' ? 'selected' : '' ?>>SSL</option><option value="" <?= $enc === '' ? 'selected' : '' ?>>None</option></select></label>
                            <label><span class="alert-label">From Email</span><input class="alert-input" name="system_email" value="<?= e(alert_setting_get('system_email', 'alerts@yourdomain.com')) ?>"></label>
                            <label><span class="alert-label">From Name</span><input class="alert-input" name="system_from_name" value="<?= e(alert_setting_get('system_from_name', 'Trading Assistant')) ?>"></label>
                        </div>
                    </div>
                </section>

                <section class="alert-card">
                    <div class="alert-card-head">
                        <div class="alert-card-title">Execution Stages & Checklist Controls</div>
                        <div class="alert-card-sub">Control Stage 1/2/3 notifications and final execution checklist behaviour.</div>
                    </div>
                    <div class="alert-card-body">
                        <div class="alert-fields">
                            <label class="check-line"><input type="checkbox" name="send_stage_alerts" value="1" <?= alert_setting_get('send_stage_alerts', '1') === '1' ? 'checked' : '' ?>> Enable Stage Alerts</label>
                            <label class="check-line"><input type="checkbox" name="stage_1_zone_alert" value="1" <?= alert_setting_get('stage_1_zone_alert', '1') === '1' ? 'checked' : '' ?>> Stage 1 Zone Alert</label>
                            <label class="check-line"><input type="checkbox" name="stage_2_liquidity_alert" value="1" <?= alert_setting_get('stage_2_liquidity_alert', '1') === '1' ? 'checked' : '' ?>> Stage 2 Liquidity Alert</label>
                            <label class="check-line"><input type="checkbox" name="stage_3_bos_alert" value="1" <?= alert_setting_get('stage_3_bos_alert', '1') === '1' ? 'checked' : '' ?>> Stage 3 BOS/CHoCH Alert</label>
                            <label class="check-line"><input type="checkbox" name="stage_4_execution_alert" value="1" <?= alert_setting_get('stage_4_execution_alert', '1') === '1' ? 'checked' : '' ?>> Final Execution Alert</label>
                            <label class="check-line"><input type="checkbox" name="require_candle_close_confirmation" value="1" <?= alert_setting_get('require_candle_close_confirmation', '1') === '1' ? 'checked' : '' ?>> Require Candle Close for Final Confirmation</label>
                        </div>
                        <div class="alert-help" style="margin-top:18px;">
                            Recommended: keep all stage alerts enabled. Stage 1/2 are early warnings; Stage 3/final are confirmation alerts.
                        </div>
                    </div>
                </section>

                <section class="alert-card">
                    <div class="alert-card-head">
                        <div class="alert-card-title">Lower-Timeframe Execution Confirmation</div>
                        <div class="alert-card-sub">Use lower timeframe candles for faster Stage 1/2 monitoring and Stage 3 confirmation.</div>
                    </div>
                    <div class="alert-card-body">
                        <div class="alert-section">
                            <label class="check-line"><input type="checkbox" name="alert_use_ltf_confirmation" value="1" <?= alert_setting_get('alert_use_ltf_confirmation', '1') === '1' ? 'checked' : '' ?>> Enable Setup TF → Confirmation TF engine</label>
                        </div>

                        <div class="alert-fields">
                            <label>
                                <span class="alert-label">Confirmation Timeframe Map</span>
                                <input class="alert-input" name="alert_confirmation_timeframe_map" value="<?= e(alert_setting_get('alert_confirmation_timeframe_map', '15m:5m,30m:5m,1h:15m,2h:15m,4h:1h,1d:4h')) ?>">
                                <div class="muted-note">Example: 1h:15m means a 1H setup uses 15M for alert monitoring and confirmation.</div>
                            </label>

                            <label>
                                <span class="alert-label">Displacement Min Body Ratio</span>
                                <input class="alert-input" name="displacement_min_body_ratio" value="<?= e(alert_setting_get('displacement_min_body_ratio', '0.55')) ?>">
                                <div class="muted-note">Recommended: 0.55. Higher is stricter, lower is more sensitive.</div>
                            </label>
                        </div>

                        <div class="alert-help" style="margin-top:18px;">
                            Recommended mapping: 15M → 5M, 30M → 5M, 1H → 15M, 4H → 1H. For BTCUSD testing, make sure the confirmation timeframe candles are syncing.
                        </div>
                    </div>
                </section>

                <section class="alert-card">
                    <div class="alert-card-head">
                        <div class="alert-card-title">MTF Confirmation & Confidence Scoring</div>
                        <div class="alert-card-sub">Higher-timeframe alignment scoring. This is separate from lower-timeframe execution confirmation.</div>
                    </div>
                    <div class="alert-card-body">
                        <div class="alert-section">
                            <label class="check-line"><input type="checkbox" name="enable_mtf_confirmation" value="1" <?= alert_setting_get('enable_mtf_confirmation', '1') === '1' ? 'checked' : '' ?>> Enable Multi-Timeframe Confirmation</label>
                        </div>
                        <div class="alert-fields">
                            <label><span class="alert-label">MTF Mode</span><?php $mtfMode = alert_setting_get('mtf_confirmation_mode', 'score'); ?><select class="alert-select" name="mtf_confirmation_mode"><option value="score" <?= $mtfMode === 'score' ? 'selected' : '' ?>>Score only - recommended</option><option value="block" <?= $mtfMode === 'block' ? 'selected' : '' ?>>Hard block if MTF fails</option></select></label>
                            <label><span class="alert-label">MTF Score Weight</span><input class="alert-input" name="mtf_score_weight" value="<?= e(alert_setting_get('mtf_score_weight', '25')) ?>"></label>
                            <label><span class="alert-label">Minimum Quality Score</span><input class="alert-input" name="minimum_quality_score" value="<?= e(alert_setting_get('minimum_quality_score', '60')) ?>"></label>
                            <label><span class="alert-label">Required Agreement Count</span><input class="alert-input" name="mtf_required_agreement_count" value="<?= e(alert_setting_get('mtf_required_agreement_count', '1')) ?>"></label>
                            <label><span class="alert-label">Custom HTF Timeframes</span><input class="alert-input" name="mtf_confirmation_timeframes" value="<?= e(alert_setting_get('mtf_confirmation_timeframes', '')) ?>" placeholder="Example: 1h,4h"></label>
                            <label><span class="alert-label">Scalper Strictness</span><?php $v = alert_setting_get('mtf_strictness_scalper', 'relaxed'); ?><select class="alert-select" name="mtf_strictness_scalper"><option value="relaxed" <?= $v === 'relaxed' ? 'selected' : '' ?>>Relaxed</option><option value="medium" <?= $v === 'medium' ? 'selected' : '' ?>>Medium</option><option value="strict" <?= $v === 'strict' ? 'selected' : '' ?>>Strict</option></select></label>
                            <label><span class="alert-label">Intraday Strictness</span><?php $v = alert_setting_get('mtf_strictness_intraday', 'medium'); ?><select class="alert-select" name="mtf_strictness_intraday"><option value="relaxed" <?= $v === 'relaxed' ? 'selected' : '' ?>>Relaxed</option><option value="medium" <?= $v === 'medium' ? 'selected' : '' ?>>Medium</option><option value="strict" <?= $v === 'strict' ? 'selected' : '' ?>>Strict</option></select></label>
                            <label><span class="alert-label">Swing Strictness</span><?php $v = alert_setting_get('mtf_strictness_swing', 'strict'); ?><select class="alert-select" name="mtf_strictness_swing"><option value="relaxed" <?= $v === 'relaxed' ? 'selected' : '' ?>>Relaxed</option><option value="medium" <?= $v === 'medium' ? 'selected' : '' ?>>Medium</option><option value="strict" <?= $v === 'strict' ? 'selected' : '' ?>>Strict</option></select></label>
                        </div>
                    </div>
                </section>

                <section class="alert-card">
                    <div class="alert-card-head">
                        <div class="alert-card-title">Alert Templates</div>
                        <div class="alert-card-sub">Templates support {{setup_timeframe}}, {{scan_timeframe}}, {{execution_checklist_html}} and {{execution_checklist_telegram}}.</div>
                    </div>
                    <div class="alert-card-body">
                        <div class="alert-section"><label><span class="alert-label">Email Subject</span><input class="alert-input" name="email_subject" value="<?= e(alert_template_get('institutional_alert_email_subject', $defaultEmailSubject)) ?>"></label></div>
                        <div class="alert-section"><label><span class="alert-label">Email Body HTML</span><textarea class="alert-textarea" name="email_body" rows="18"><?= e(alert_template_get('institutional_alert_email_body', $defaultEmailBody)) ?></textarea></label></div>
                        <div class="alert-section"><label><span class="alert-label">Telegram Final Alert</span><textarea class="alert-textarea" name="telegram_body" rows="8"><?= e(alert_template_get('institutional_alert_telegram_body', $defaultTelegram)) ?></textarea></label></div>
                        <div class="alert-section"><label><span class="alert-label">Stage 1: Zone Approached</span><textarea class="alert-textarea" name="stage_zone" rows="5"><?= e(alert_template_get('stage_zone_approached_telegram', $defaultStageZone)) ?></textarea></label></div>
                        <div class="alert-section"><label><span class="alert-label">Stage 2: Liquidity Swept</span><textarea class="alert-textarea" name="stage_sweep" rows="5"><?= e(alert_template_get('stage_liquidity_swept_telegram', $defaultStageSweep)) ?></textarea></label></div>
                        <div class="alert-section"><label><span class="alert-label">Stage 3: Structure Confirmed</span><textarea class="alert-textarea" name="stage_structure" rows="5"><?= e(alert_template_get('stage_structure_confirmed_telegram', $defaultStageStructure)) ?></textarea></label></div>
                        <div class="alert-section"><label><span class="alert-label">Stage 1 Email</span><textarea class="alert-textarea" name="stage_zone_email" rows="6"><?= e(alert_template_get('stage_zone_approached_email', $defaultStageZoneEmail)) ?></textarea></label></div>
                        <div class="alert-section"><label><span class="alert-label">Stage 2 Email</span><textarea class="alert-textarea" name="stage_sweep_email" rows="6"><?= e(alert_template_get('stage_liquidity_swept_email', $defaultStageSweepEmail)) ?></textarea></label></div>
                        <div class="alert-section"><label><span class="alert-label">Stage 3 Email</span><textarea class="alert-textarea" name="stage_structure_email" rows="6"><?= e(alert_template_get('stage_structure_confirmed_email', $defaultStageStructureEmail)) ?></textarea></label></div>
                    </div>
                </section>

            </div>

            <aside>
                <section class="alert-card">
                    <div class="alert-card-head">
                        <div class="alert-card-title">Telegram Delivery</div>
                        <div class="alert-card-sub">Bot token used for Telegram alerts.</div>
                    </div>
                    <div class="alert-card-body">
                        <label><span class="alert-label">Telegram Bot Token</span><input class="alert-input" name="telegram_bot_token" value="<?= e(alert_setting_get('telegram_bot_token')) ?>" placeholder="123456:ABC..."></label>
                    </div>
                </section>

                <section class="alert-card">
                    <div class="alert-card-head">
                        <div class="alert-card-title">Developer Testing Mode</div>
                        <div class="alert-card-sub">Keep this off for real BTCUSD testing.</div>
                    </div>
                    <div class="alert-card-body">
                        <div class="alert-section"><label class="check-line"><input type="checkbox" name="test_mode" value="1" <?= alert_setting_get('test_mode', '0') === '1' ? 'checked' : '' ?>> Enable Developer Test Mode</label></div>
                        <div class="alert-section"><label class="check-line"><input type="checkbox" name="simulate_zone_touch" value="1" <?= alert_setting_get('simulate_zone_touch', '0') === '1' ? 'checked' : '' ?>> Simulate Zone Touch</label></div>
                        <div class="alert-section"><label class="check-line"><input type="checkbox" name="simulate_liquidity_sweep" value="1" <?= alert_setting_get('simulate_liquidity_sweep', '0') === '1' ? 'checked' : '' ?>> Simulate Liquidity Sweep</label></div>
                        <div class="alert-section"><label class="check-line"><input type="checkbox" name="simulate_structure_break" value="1" <?= alert_setting_get('simulate_structure_break', '0') === '1' ? 'checked' : '' ?>> Simulate BOS / CHoCH</label></div>
                        <div class="alert-section"><label class="check-line"><input type="checkbox" name="simulate_ready_setup" value="1" <?= alert_setting_get('simulate_ready_setup', '0') === '1' ? 'checked' : '' ?>> Simulate Full Ready Setup</label></div>
                        <div class="alert-help">For live BTCUSD testing, Developer Test Mode and all simulation options should be OFF.</div>
                    </div>
                </section>

                <section class="alert-card">
                    <div class="alert-card-head">
                        <div class="alert-card-title">Recommended BTCUSD Test</div>
                    </div>
                    <div class="alert-card-body">
                        <div class="alert-help">
                            Before tracking BTCUSD, make sure BTCUSD setup timeframe and confirmation timeframe candles are updating. Example: 1H setup should have BTCUSD 15M candles available.
                        </div>
                    </div>
                </section>
            </aside>
        </div>

        <div class="alert-save"><button class="alert-btn" type="submit">Save Alert Settings</button></div>
    </form>
</div>

<?php admin_layout_footer(); ?>
