<?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 news_setting($key, $default = '')
{
    try {

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

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

        $value = $stmt->fetchColumn();

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

    } catch (Throwable $e) {

        return $default;
    }
}

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

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

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

$defaults = [

    'enable_high_impact_news_filter' => '1',
    'enable_speech_detection'        => '1',
    'enable_geopolitical_filter'     => '1',
    'enable_news_blackout'           => '1',

    'pre_news_blackout_minutes'      => '30',
    'post_news_blackout_minutes'     => '30',

    'speech_blackout_minutes'        => '45',

    'minimum_news_severity'          => 'HIGH',

    'allow_execution_during_news'    => '0',

    'track_fed_speeches'             => '1',
    'track_trump_speeches'           => '1',
    'track_ecb_speeches'             => '1',
    'track_boj_speeches'             => '1',

    'auto_pause_alerts'              => '1',
    'auto_resume_after_news'         => '1',

    'news_cache_refresh_minutes'     => '10',

    'enable_manual_news_override'    => '1',

];

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

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

    save_news_setting(
        $key,
        news_setting($key, $value)
    );
}

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

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

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

    try {

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

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

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

    } catch (Throwable $e) {

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

admin_layout_header('News Engine Settings');

?>

<style>

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

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

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

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

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

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

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

.news-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;
}

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

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

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

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

.news-label{
    display:block;
}

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

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

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

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

.news-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);
}

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

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

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

.news-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){

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

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

</style>

<div class="news-wrapper">

    <div class="news-header">

        <div class="news-title">
            News Engine Settings
        </div>

        <div class="news-subtitle">
            Configure institutional news protection, speeches, blackout windows and macro volatility filtering.
        </div>

    </div>

    <?php if ($message): ?>

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

    <?php endif; ?>

    <?php if ($error): ?>

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

    <?php endif; ?>

    <div class="news-info">

        <strong>Institutional News Protection Engine</strong>

        <br><br>

        The system automatically tracks:

        <br><br>

        • High-impact economic releases<br>
        • Fed / ECB / BOJ speeches<br>
        • Trump speeches and geopolitical events<br>
        • CPI, NFP, FOMC and rate decisions<br>
        • Volatility blackout periods

        <br><br>

        Alerts and execution setups can be paused automatically during dangerous volatility windows.

    </div>

    <form method="post">

        <div class="news-grid">

            <section class="news-card">

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

                    <div class="news-card-title">
                        News Filtering
                    </div>

                    <div class="news-card-subtitle">
                        Configure high-impact event filtering and execution restrictions.
                    </div>

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

                </div>

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

                    <div class="news-fields">

                        <?php

                        $toggleFields = [

                            'enable_high_impact_news_filter' => 'High Impact News Filter',
                            'enable_speech_detection'        => 'Speech Detection',
                            'enable_geopolitical_filter'     => 'Geopolitical Filter',
                            'enable_news_blackout'           => 'News Blackout',
                            'allow_execution_during_news'    => 'Allow Execution During News',
                            'auto_pause_alerts'              => 'Auto Pause Alerts',
                            'auto_resume_after_news'         => 'Auto Resume Alerts',
                            'enable_manual_news_override'    => 'Manual Override'

                        ];

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

                        ?>

                            <label class="news-label">

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

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

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

                            </label>

                        <?php endforeach; ?>

                    </div>

                </div>

            </section>

            <section class="news-card">

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

                    <div class="news-card-title">
                        Blackout & Speech Rules
                    </div>

                    <div class="news-card-subtitle">
                        Configure blackout timing and speech-event sensitivity.
                    </div>

                    <div class="news-badge">
                        Macro Intelligence Engine
                    </div>

                </div>

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

                    <div class="news-fields">

                        <?php

                        $numericFields = [

                            'pre_news_blackout_minutes'   => 'Pre-News Blackout (mins)',
                            'post_news_blackout_minutes'  => 'Post-News Blackout (mins)',
                            'speech_blackout_minutes'     => 'Speech Blackout (mins)',
                            'news_cache_refresh_minutes'  => 'Cache Refresh Interval',
                        ];

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

                        ?>

                            <label class="news-label">

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

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

                            </label>

                        <?php endforeach; ?>

                        <label class="news-label">

                            <span class="news-label-text">
                                Minimum News Severity
                            </span>

                            <select
                                class="news-select"
                                name="settings[minimum_news_severity]"
                            >
                                <?php foreach (['LOW', 'MEDIUM', 'HIGH'] as $level): ?>

                                    <option
                                        value="<?= e($level) ?>"
                                        <?= news_setting('minimum_news_severity') === $level ? 'selected' : '' ?>
                                    >
                                        <?= e($level) ?>
                                    </option>

                                <?php endforeach; ?>
                            </select>

                        </label>

                        <?php

                        $speechFields = [

                            'track_fed_speeches'   => 'Track Fed Speeches',
                            'track_trump_speeches' => 'Track Trump Speeches',
                            'track_ecb_speeches'   => 'Track ECB Speeches',
                            'track_boj_speeches'   => 'Track BOJ Speeches',

                        ];

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

                        ?>

                            <label class="news-label">

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

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

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

                            </label>

                        <?php endforeach; ?>

                    </div>

                </div>

            </section>

        </div>

        <div class="news-save">

            <button class="news-btn">
                Save News Engine Settings
            </button>

        </div>

    </form>

</div>

<?php admin_layout_footer(); ?>
