<?php

require_once __DIR__ . '/admin_tool_helper.php';

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

/*
|--------------------------------------------------------------------------
| Helpers
|--------------------------------------------------------------------------
*/

function engine_setting($key, $default = '')
{
    try {

        $stmt = db()->prepare("
            SELECT setting_value
            FROM engine_settings
            WHERE setting_group = 'alert_engine'
            AND setting_key = ?
            LIMIT 1
        ");

        $stmt->execute([$key]);

        $value = $stmt->fetchColumn();

        return $value !== false ? $value : $default;

    } catch (Throwable $e) {

        return $default;
    }
}

function save_engine_setting($key, $value, $description = '')
{
    $stmt = db()->prepare("
        INSERT INTO engine_settings (
            setting_group,
            setting_key,
            setting_value,
            description
        )
        VALUES (
            'alert_engine',
            ?,
            ?,
            ?
        )
        ON DUPLICATE KEY UPDATE
            setting_value = VALUES(setting_value),
            description = VALUES(description)
    ");

    $stmt->execute([
        $key,
        $value,
        $description
    ]);

    /*
     * Keep live AlertService and this admin page in sync.
     * Older AlertService builds read system_settings while this page saved
     * engine_settings only. Mirroring removes that mismatch.
     */
    try {
        $mirror = 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()
        ");
        $mirror->execute([$key, $value]);

        $aliases = [
            'duplicate_alert_cooldown' => ['stage_cooldown_minutes', 'stage_alert_throttle_minutes'],
            'minimum_confluence_score' => ['minimum_quality_score'],
            'require_htf_alignment' => ['enable_mtf_confirmation'],
        ];

        foreach (($aliases[$key] ?? []) as $alias) {
            $mirror->execute([$alias, $value]);
        }
    } catch (Throwable $e) {
        /*
         * Do not block settings save if system_settings has an older schema.
         */
    }
}

/*
|--------------------------------------------------------------------------
| Default settings
|--------------------------------------------------------------------------
*/

$defaults = [

    'stage_1_zone_alert'          => '1',
    'stage_2_liquidity_alert'     => '1',
    'stage_3_bos_alert'           => '1',
    'stage_4_execution_alert'     => '1',

    'minimum_confluence_score'    => '5.5',
    'duplicate_alert_cooldown'    => '30',
    'max_alerts_per_symbol'       => '4',
    'alert_expiry_hours'          => '12',

    'require_liquidity_sweep'     => '1',
    'require_bos_confirmation'    => '1',
    'require_choch_confirmation'  => '1',
    'require_htf_alignment'       => '1',

    'zone_distance_buffer_pips'   => '5',
    'bos_confirmation_candles'    => '2',
    'minimum_rr_required'         => '2.0',

    'news_blackout_minutes'       => '30',
    'high_impact_news_filter'     => '1',
    'speech_event_filter'         => '1',

    'telegram_alerts_enabled'     => '1',
    'email_alerts_enabled'        => '1',

    'allow_countertrend_setups'   => '0',
    'enable_execution_ready_only' => '0',

    /*
    |--------------------------------------------------------------------------
    | Live-mode reliability defaults
    |--------------------------------------------------------------------------
    | Stage alerts should keep monitoring even after one stage fires.
    | These values are read by AlertService from system_settings/engine_settings.
    |--------------------------------------------------------------------------
    */
    'require_candle_close_confirmation' => '1',
    'stage_cooldown_minutes' => '2',
    'stage_alert_throttle_minutes' => '2',
    'final_cooldown_minutes' => '240',
    'final_alert_throttle_minutes' => '240',
    'enable_session_filter' => '0',
    'enable_volatility_filter' => '0',

];

/*
|--------------------------------------------------------------------------
| Seed missing settings
|--------------------------------------------------------------------------
*/

foreach ($defaults as $key => $value) {

    save_engine_setting(
        $key,
        engine_setting($key, $value)
    );
}

/*
|--------------------------------------------------------------------------
| Save
|--------------------------------------------------------------------------
*/

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    try {

        foreach ($_POST['settings'] ?? [] as $key => $value) {

            save_engine_setting(
                $key,
                is_array($value)
                    ? json_encode($value)
                    : trim((string)$value)
            );
        }

        $message = 'Alert engine settings updated successfully.';

    } catch (Throwable $e) {

        $error = $e->getMessage();
    }
}

admin_layout_header('Alert Engine Settings');

?>

<style>

.alert-wrapper{
    max-width:1450px;
    margin:0 auto;
}

.alert-header{
    margin-bottom:28px;
}

.alert-title{
    font-size:42px;
    font-weight:900;
    letter-spacing:-0.04em;
    color:#020617;
}

.alert-subtitle{
    margin-top:8px;
    color:#64748b;
    font-size:15px;
}

.alert-grid{
    display:grid;
    grid-template-columns:repeat(2,minmax(0,1fr));
    gap:24px;
}

.alert-card{
    background:#fff;
    border:1px solid #e2e8f0;
    border-radius:28px;
    overflow:hidden;
    box-shadow:0 10px 24px rgba(15,23,42,.05);
}

.alert-card-head{
    padding:22px 24px;
    border-bottom:1px solid #e2e8f0;
    background:
        linear-gradient(
            135deg,
            rgba(37,99,235,.05),
            rgba(15,23,42,.02)
        ),
        #fff;
}

.alert-card-title{
    font-size:22px;
    font-weight:900;
    color:#020617;
}

.alert-card-subtitle{
    margin-top:6px;
    color:#64748b;
    font-size:13px;
}

.alert-card-body{
    padding:24px;
}

.alert-fields{
    display:grid;
    grid-template-columns:repeat(2,minmax(0,1fr));
    gap:18px;
}

.alert-label{
    display:block;
}

.alert-label-text{
    display:block;
    margin-bottom:8px;
    color:#64748b;
    font-size:11px;
    font-weight:900;
    letter-spacing:.08em;
    text-transform:uppercase;
}

.alert-input,
.alert-select{
    width:100%;
    height:48px;
    border:1px solid #cbd5e1;
    border-radius:14px;
    padding:0 14px;
    background:#fff;
    color:#0f172a;
    font-weight:700;
}

.alert-input:focus,
.alert-select:focus{
    outline:none;
    border-color:#2563eb;
    box-shadow:0 0 0 4px rgba(37,99,235,.12);
}

.alert-save{
    margin-top:28px;
    display:flex;
    justify-content:flex-end;
}

.alert-btn{
    height:52px;
    border:0;
    border-radius:16px;
    padding:0 30px;
    background:#2563eb;
    color:#fff;
    font-weight:900;
    cursor:pointer;
    box-shadow:0 10px 24px rgba(37,99,235,.2);
}

.alert-info{
    background:#eff6ff;
    border:1px solid #bfdbfe;
    color:#1d4ed8;
    padding:18px;
    border-radius:18px;
    line-height:1.7;
    margin-bottom:24px;
    font-size:14px;
}

.alert-success,
.alert-error{
    margin-bottom:20px;
    padding:14px 18px;
    border-radius:16px;
    font-weight:800;
}

.alert-success{
    background:#ecfdf5;
    border:1px solid #a7f3d0;
    color:#047857;
}

.alert-error{
    background:#fef2f2;
    border:1px solid #fecaca;
    color:#b91c1c;
}

.alert-badge{
    display:inline-flex;
    align-items:center;
    padding:6px 10px;
    border-radius:999px;
    background:#dbeafe;
    color:#1d4ed8;
    font-size:11px;
    font-weight:900;
    margin-top:10px;
}

@media(max-width:1100px){

    .alert-grid{
        grid-template-columns:1fr;
    }

    .alert-fields{
        grid-template-columns:1fr;
    }
}

</style>

<div class="alert-wrapper">

    <div class="alert-header">

        <div class="alert-title">
            Alert Engine Settings
        </div>

        <div class="alert-subtitle">
            Configure institutional stage alerts, BOS/CHoCH validation, liquidity sweep logic and delivery rules.
        </div>

    </div>

    <?php if ($message): ?>

        <div class="alert-success">
            <?= e($message) ?>
        </div>

    <?php endif; ?>

    <?php if ($error): ?>

        <div class="alert-error">
            <?= e($error) ?>
        </div>

    <?php endif; ?>

    <div class="alert-info">

        <strong>Institutional Multi-Stage Alert Flow</strong>

        <br><br>

        Stage 1 → Price enters institutional zone<br>
        Stage 2 → Liquidity sweep detected<br>
        Stage 3 → BOS / CHoCH confirmed<br>
        Stage 4 → Execution-ready alert delivered

        <br><br>

        The engine now keeps live monitoring active after each stage, so fast zone touches, sweeps and BOS/CHoCH confirmations are not missed between cron runs.

    </div>

    <form method="post">

        <div class="alert-grid">

            <section class="alert-card">

                <div class="alert-card-head">

                    <div class="alert-card-title">
                        Stage Alert Logic
                    </div>

                    <div class="alert-card-subtitle">
                        Configure the institutional confirmation sequence.
                    </div>

                    <div class="alert-badge">
                        Smart Confirmation Engine
                    </div>

                </div>

                <div class="alert-card-body">

                    <div class="alert-fields">

                        <?php

                        $stageFields = [

                            'stage_1_zone_alert'         => 'Zone Approach Alert',
                            'stage_2_liquidity_alert'    => 'Liquidity Sweep Alert',
                            'stage_3_bos_alert'          => 'BOS / CHoCH Alert',
                            'stage_4_execution_alert'    => 'Execution Ready Alert',
                            'require_liquidity_sweep'    => 'Require Liquidity Sweep',
                            'require_bos_confirmation'   => 'Require BOS Confirmation',
                            'require_choch_confirmation' => 'Require CHoCH Confirmation',
                            'require_htf_alignment'      => 'Require HTF Alignment'

                        ];

                        foreach ($stageFields as $key => $label):

                        ?>

                            <label class="alert-label">

                                <span class="alert-label-text">
                                    <?= e($label) ?>
                                </span>

                                <select
                                    class="alert-select"
                                    name="settings[<?= e($key) ?>]"
                                >
                                    <option value="1" <?= engine_setting($key) === '1' ? 'selected' : '' ?>>
                                        Enabled
                                    </option>

                                    <option value="0" <?= engine_setting($key) === '0' ? 'selected' : '' ?>>
                                        Disabled
                                    </option>
                                </select>

                            </label>

                        <?php endforeach; ?>

                    </div>

                </div>

            </section>

            <section class="alert-card">

                <div class="alert-card-head">

                    <div class="alert-card-title">
                        Risk & News Controls
                    </div>

                    <div class="alert-card-subtitle">
                        Control execution filtering, cooldowns and event protection.
                    </div>

                    <div class="alert-badge">
                        Volatility Protection
                    </div>

                </div>

                <div class="alert-card-body">

                    <div class="alert-fields">

                        <?php

                        $numericFields = [

                            'minimum_confluence_score' => 'Minimum Confluence Score',
                            'duplicate_alert_cooldown' => 'Duplicate Alert Cooldown (mins)',
                            'max_alerts_per_symbol'    => 'Max Alerts Per Symbol',
                            'alert_expiry_hours'       => 'Alert Expiry Hours',
                            'zone_distance_buffer_pips'=> 'Zone Buffer (pips)',
                            'bos_confirmation_candles' => 'BOS Confirmation Candles',
                            'minimum_rr_required'      => 'Minimum RR Required',
                            'stage_cooldown_minutes'    => 'Stage Cooldown (mins)',
                            'final_cooldown_minutes'    => 'Final Cooldown (mins)'

                        ];

                        foreach ($numericFields as $key => $label):

                        ?>

                            <label class="alert-label">

                                <span class="alert-label-text">
                                    <?= e($label) ?>
                                </span>

                                <input
                                    class="alert-input"
                                    name="settings[<?= e($key) ?>]"
                                    value="<?= e(engine_setting($key)) ?>"
                                >

                            </label>

                        <?php endforeach; ?>

                        <?php

                        $toggleFields = [

                            'high_impact_news_filter'     => 'High Impact News Filter',
                            'speech_event_filter'         => 'Speech/Event Filter',
                            'telegram_alerts_enabled'     => 'Telegram Alerts',
                            'email_alerts_enabled'        => 'Email Alerts',
                            'allow_countertrend_setups'   => 'Allow Countertrend Setups',
                            'enable_execution_ready_only' => 'Execution Ready Only',
                            'require_candle_close_confirmation' => 'Require Candle Close',
                            'enable_session_filter' => 'Session Filter',
                            'enable_volatility_filter' => 'Volatility Filter'

                        ];

                        foreach ($toggleFields as $key => $label):

                        ?>

                            <label class="alert-label">

                                <span class="alert-label-text">
                                    <?= e($label) ?>
                                </span>

                                <select
                                    class="alert-select"
                                    name="settings[<?= e($key) ?>]"
                                >
                                    <option value="1" <?= engine_setting($key) === '1' ? 'selected' : '' ?>>
                                        Enabled
                                    </option>

                                    <option value="0" <?= engine_setting($key) === '0' ? 'selected' : '' ?>>
                                        Disabled
                                    </option>
                                </select>

                            </label>

                        <?php endforeach; ?>

                    </div>

                </div>

            </section>

        </div>

        <div class="alert-save">

            <button class="alert-btn">
                Save Alert Engine Settings
            </button>

        </div>

    </form>

</div>

<?php admin_layout_footer(); ?>
