<?php

require_once __DIR__ . '/admin_tool_helper.php';

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

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

function system_setting_save($key, $value)
{
    $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]);
}

function system_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;
    }
}

/*
|--------------------------------------------------------------------------
| SMTP + Telegram are managed ONLY in alert_settings.php
|--------------------------------------------------------------------------
*/

$excludedSettings = [
    'smtp_host',
    'smtp_port',
    'smtp_username',
    'smtp_password',
    'smtp_encryption',
    'system_email',
    'system_from_name',
    'telegram_bot_token',
    'send_stage_alerts'
];

/*
|--------------------------------------------------------------------------
| Recommended core platform settings
|--------------------------------------------------------------------------
*/

$coreDefaults = [

    'application_name'        => 'Institutional Trading Assistant',
    'timezone'                => 'Africa/Lagos',
    'maintenance_mode'        => '0',
    'dashboard_refresh_rate'  => '30',
    'default_risk_percent'    => '1',
    'news_blackout_minutes'   => '30',
    'weekend_trading'         => '0',
    'institutional_mode'      => '1',
    'default_execution_model' => 'pullback_confirmation',
    'default_session'         => 'London/New York',
    'default_news_filter'     => 'HIGH',
    'max_active_alerts'       => '10',
    'default_rr_target'       => '3',
    'default_confluence_min'  => '5.5',
    'enable_stage_alerts'     => '1',
    'enable_news_filter'      => '1',
    'enable_geopolitical_filter' => '1',
    'default_macro_bias'      => 'NEUTRAL',
    'enable_weekend_analysis' => '0'

];

/*
|--------------------------------------------------------------------------
| Auto-create missing core settings
|--------------------------------------------------------------------------
*/

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

    if (in_array($key, $excludedSettings, true)) {
        continue;
    }

    system_setting_save(
        $key,
        system_setting_get($key, $value)
    );
}

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

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

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

    try {

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

            if (in_array($key, $excludedSettings, true)) {
                continue;
            }

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

        $message = 'System settings updated successfully.';

    } catch (Throwable $e) {

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

/*
|--------------------------------------------------------------------------
| Fetch settings
|--------------------------------------------------------------------------
*/

$rows = [];

try {

    $placeholders = implode(
        ',',
        array_fill(0, count($excludedSettings), '?')
    );

    $stmt = db()->prepare("
        SELECT *
        FROM system_settings
        WHERE setting_key NOT IN ($placeholders)
        ORDER BY setting_key ASC
    ");

    $stmt->execute($excludedSettings);

    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (Throwable $e) {

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

admin_layout_header('System Settings');

?>

<style>

.settings-wrapper{
    max-width:1400px;
    margin:0 auto;
}

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

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

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

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

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

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

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

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

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

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

.settings-label{
    display:block;
}

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

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

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

.settings-save{
    margin-top:26px;
    display:flex;
    justify-content:flex-end;
}

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

.settings-info{
    background:#eff6ff;
    border:1px solid #bfdbfe;
    color:#1d4ed8;
    padding:16px 18px;
    border-radius:18px;
    margin-bottom:22px;
    font-size:14px;
    line-height:1.6;
}

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

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

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

.settings-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:1000px){

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

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

</style>

<div class="settings-wrapper">

    <div class="settings-header">

        <div class="settings-title">
            System Settings
        </div>

        <div class="settings-subtitle">
            Core institutional platform configuration and operational defaults.
        </div>

    </div>

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

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

    <div class="settings-info">

        SMTP, Telegram and alert templates are now managed ONLY inside:

        <strong>alert_settings.php</strong>

        <br><br>

        This page now controls only core platform settings and institutional engine defaults.

    </div>

    <form method="post">

        <div class="settings-grid">

            <section class="settings-card">

                <div class="settings-card-header">

                    <div class="settings-card-title">
                        Platform Configuration
                    </div>

                    <div class="settings-card-subtitle">
                        Global application behavior and institutional defaults.
                    </div>

                    <div class="settings-badge">
                        Core Platform
                    </div>

                </div>

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

                    <div class="settings-fields">

                        <?php foreach ($rows as $row): ?>

                            <?php

                            $key = $row['setting_key'];
                            $value = $row['setting_value'];

                            ?>

                            <label class="settings-label">

                                <span class="settings-label-text">
                                    <?= e(str_replace('_', ' ', $key)) ?>
                                </span>

                                <?php if (
                                    in_array($key, [
                                        'maintenance_mode',
                                        'weekend_trading',
                                        'institutional_mode',
                                        'enable_stage_alerts',
                                        'enable_news_filter',
                                        'enable_geopolitical_filter',
                                        'enable_weekend_analysis'
                                    ], true)
                                ): ?>

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

                                        <option value="0" <?= $value === '0' ? 'selected' : '' ?>>
                                            Disabled
                                        </option>
                                    </select>

                                <?php else: ?>

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

                                <?php endif; ?>

                            </label>

                        <?php endforeach; ?>

                    </div>

                </div>

            </section>

        </div>

        <div class="settings-save">

            <button class="settings-btn">
                Save System Settings
            </button>

        </div>

    </form>

</div>

<?php admin_layout_footer(); ?>
