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

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

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

        $value = $stmt->fetchColumn();

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

    } catch (Throwable $e) {

        return $default;
    }
}

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

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

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

$defaults = [

    'enable_order_blocks'           => '1',
    'enable_fvg_detection'          => '1',
    'enable_liquidity_sweeps'       => '1',
    'enable_bos_detection'          => '1',
    'enable_choch_detection'        => '1',

    'require_discount_buying'       => '1',
    'require_premium_selling'       => '1',

    'minimum_ob_quality'            => '5',
    'minimum_fvg_quality'           => '5',

    'minimum_liquidity_strength'    => '5',
    'minimum_bos_strength'          => '5',

    'minimum_rr_required'           => '2.0',

    'premium_zone_threshold'        => '70',
    'discount_zone_threshold'       => '30',

    'allow_countertrend_setups'     => '0',
    'require_htf_alignment'         => '1',

    'enable_dual_scenarios'         => '1',

    'require_liquidity_before_entry'=> '1',
    'require_bos_after_sweep'       => '1',

    'enable_smart_pullback_logic'   => '1',
    'enable_dynamic_stoploss'       => '1',

    'minimum_confluence_score'      => '5.5',

    'enable_session_filter'         => '1',
    'enable_news_filter'            => '1',

];

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

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

    save_institutional_setting(
        $key,
        institutional_setting($key, $value)
    );
}

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

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

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

    try {

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

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

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

    } catch (Throwable $e) {

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

admin_layout_header('Institutional Engine Settings');

?>

<style>

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

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

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

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

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

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

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

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

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

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

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

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

.inst-label{
    display:block;
}

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

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

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

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

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

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

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

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

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

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

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

</style>

<div class="inst-wrapper">

    <div class="inst-header">

        <div class="inst-title">
            Institutional Engine Settings
        </div>

        <div class="inst-subtitle">
            Configure institutional logic, liquidity sweeps, BOS/CHoCH confirmation and execution behavior.
        </div>

    </div>

    <?php if ($message): ?>

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

    <?php endif; ?>

    <?php if ($error): ?>

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

    <?php endif; ?>

    <div class="inst-info">

        <strong>Institutional Trading Logic Engine</strong>

        <br><br>

        The engine validates:

        <br><br>

        • Premium vs discount positioning<br>
        • Institutional order blocks<br>
        • Liquidity sweeps<br>
        • BOS / CHoCH confirmations<br>
        • Higher timeframe alignment<br>
        • Dynamic stop loss logic<br>
        • Smart pullback entries

        <br><br>

        Dual-scenario execution logic prevents chasing price into premium/discount extremes.

    </div>

    <form method="post">

        <div class="inst-grid">

            <section class="inst-card">

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

                    <div class="inst-card-title">
                        Institutional Structure Engine
                    </div>

                    <div class="inst-card-subtitle">
                        Configure BOS, CHoCH, liquidity and smart execution rules.
                    </div>

                    <div class="inst-badge">
                        Smart Structure Engine
                    </div>

                </div>

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

                    <div class="inst-fields">

                        <?php

                        $toggleFields = [

                            'enable_order_blocks'            => 'Enable Order Blocks',
                            'enable_fvg_detection'           => 'Enable Fair Value Gaps',
                            'enable_liquidity_sweeps'        => 'Enable Liquidity Sweeps',
                            'enable_bos_detection'           => 'Enable BOS Detection',
                            'enable_choch_detection'         => 'Enable CHoCH Detection',

                            'require_discount_buying'        => 'Require Discount Buying',
                            'require_premium_selling'        => 'Require Premium Selling',

                            'require_htf_alignment'          => 'Require HTF Alignment',

                            'enable_dual_scenarios'          => 'Enable Dual Scenarios',

                            'require_liquidity_before_entry' => 'Require Liquidity Before Entry',

                            'require_bos_after_sweep'        => 'Require BOS After Sweep',

                            'enable_smart_pullback_logic'    => 'Enable Smart Pullbacks',

                            'enable_dynamic_stoploss'        => 'Enable Dynamic Stoploss',

                            'enable_session_filter'          => 'Enable Session Filter',

                            'enable_news_filter'             => 'Enable News Filter',

                            'allow_countertrend_setups'      => 'Allow Countertrend'

                        ];

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

                        ?>

                            <label class="inst-label">

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

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

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

                            </label>

                        <?php endforeach; ?>

                    </div>

                </div>

            </section>

            <section class="inst-card">

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

                    <div class="inst-card-title">
                        Institutional Quality Rules
                    </div>

                    <div class="inst-card-subtitle">
                        Configure confluence quality and premium/discount thresholds.
                    </div>

                    <div class="inst-badge">
                        Confluence Intelligence
                    </div>

                </div>

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

                    <div class="inst-fields">

                        <?php

                        $numericFields = [

                            'minimum_ob_quality'          => 'Minimum OB Quality',
                            'minimum_fvg_quality'         => 'Minimum FVG Quality',
                            'minimum_liquidity_strength'  => 'Liquidity Strength',
                            'minimum_bos_strength'        => 'BOS Strength',
                            'minimum_rr_required'         => 'Minimum RR',

                            'premium_zone_threshold'      => 'Premium Threshold %',
                            'discount_zone_threshold'     => 'Discount Threshold %',

                            'minimum_confluence_score'    => 'Minimum Confluence Score',

                        ];

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

                        ?>

                            <label class="inst-label">

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

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

                            </label>

                        <?php endforeach; ?>

                    </div>

                </div>

            </section>

        </div>

        <div class="inst-save">

            <button class="inst-btn">
                Save Institutional Engine Settings
            </button>

        </div>

    </form>

</div>

<?php admin_layout_footer(); ?>
