<?php

require_once __DIR__ . '/admin_tool_helper.php';

/*
|--------------------------------------------------------------------------
| Safe local helpers
|--------------------------------------------------------------------------
*/

if (!function_exists('trading_style_column_exists')) {
    function trading_style_column_exists($column)
    {
        try {
            $stmt = db()->prepare("SHOW COLUMNS FROM trading_style_settings LIKE ?");
            $stmt->execute([$column]);
            return (bool)$stmt->fetchColumn();
        } catch (Throwable $e) {
            return false;
        }
    }
}

if (!function_exists('trading_style_table_exists')) {
    function trading_style_table_exists($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;
        }
    }
}

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

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

/*
|--------------------------------------------------------------------------
| Column groups
|--------------------------------------------------------------------------
| Only existing DB columns are rendered/saved.
|--------------------------------------------------------------------------
*/

$assetGroups = [
    'forex' => [
        'label' => 'Forex',
        'columns' => [
            'forex_sl_pips' => 'SL Pips',
            'forex_tp1_rr' => 'TP1 RR',
            'forex_tp2_rr' => 'TP2 RR',
            'forex_tp3_rr' => 'TP3 RR',
        ],
    ],
    'gold' => [
        'label' => 'Metals - Gold (XAUUSD)',
        'columns' => [
            'gold_sl_pips' => 'SL Pips',
            'gold_tp1_rr' => 'TP1 RR',
            'gold_tp2_rr' => 'TP2 RR',
            'gold_tp3_rr' => 'TP3 RR',
        ],
    ],
    'silver' => [
        'label' => 'Metals - Silver (XAGUSD)',
        'columns' => [
            'silver_sl_pips' => 'SL Pips',
            'silver_tp1_rr' => 'TP1 RR',
            'silver_tp2_rr' => 'TP2 RR',
            'silver_tp3_rr' => 'TP3 RR',
        ],
    ],
    'crypto' => [
        'label' => 'Crypto',
        'columns' => [
            'crypto_sl_pips' => 'SL Pips',
            'crypto_tp1_rr' => 'TP1 RR',
            'crypto_tp2_rr' => 'TP2 RR',
            'crypto_tp3_rr' => 'TP3 RR',
        ],
    ],
    'indices' => [
        'label' => 'Indices',
        'columns' => [
            'indices_sl_pips' => 'SL Pips',
            'indices_tp1_rr' => 'TP1 RR',
            'indices_tp2_rr' => 'TP2 RR',
            'indices_tp3_rr' => 'TP3 RR',
        ],
    ],
    'commodities' => [
        'label' => 'Commodities',
        'columns' => [
            'commodities_sl_pips' => 'SL Pips',
            'commodities_tp1_rr' => 'TP1 RR',
            'commodities_tp2_rr' => 'TP2 RR',
            'commodities_tp3_rr' => 'TP3 RR',
        ],
    ],
    'stocks' => [
        'label' => 'Stocks',
        'columns' => [
            'stocks_sl_pips' => 'SL Pips',
            'stocks_tp1_rr' => 'TP1 RR',
            'stocks_tp2_rr' => 'TP2 RR',
            'stocks_tp3_rr' => 'TP3 RR',
        ],
    ],
];

$riskColumns = [
    'atr_multiplier' => 'ATR Multiplier',
    'min_rr' => 'Minimum RR',
    'buffer_percent' => 'Risk Buffer %',
];

$logicColumns = [
    'sweep_strength' => 'Sweep Strength',
    'bos_strength' => 'BOS Strength',
    'confirmation_strictness' => 'Confirmation Strictness',
];

$metaColumns = [
    'style_key' => 'Style Key',
    'style_name' => 'Style Name',
    'sort_order' => 'Sort Order',
    'is_active' => 'Active',
];

$allPossibleColumns = [];

foreach ($metaColumns as $column => $label) {
    $allPossibleColumns[$column] = $label;
}

foreach ($assetGroups as $group) {
    foreach ($group['columns'] as $column => $label) {
        $allPossibleColumns[$column] = $label;
    }
}

foreach ($riskColumns as $column => $label) {
    $allPossibleColumns[$column] = $label;
}

foreach ($logicColumns as $column => $label) {
    $allPossibleColumns[$column] = $label;
}

$existingColumns = [];

foreach ($allPossibleColumns as $column => $label) {
    if (trading_style_column_exists($column)) {
        $existingColumns[$column] = $label;
    }
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        foreach ($_POST['styles'] ?? [] as $id => $style) {
            $id = (int)$id;

            if ($id <= 0) {
                continue;
            }

            if (isset($existingColumns['is_active'])) {
                $style['is_active'] = !empty($style['is_active']) ? 1 : 0;
            }

            $sets = [];
            $params = [];

            foreach ($style as $column => $value) {
                if (!isset($existingColumns[$column])) {
                    continue;
                }

                if (!trading_style_column_exists($column)) {
                    continue;
                }

                if ($column === 'is_active') {
                    $value = !empty($value) ? 1 : 0;
                }

                $sets[] = "`" . str_replace('`', '', $column) . "` = ?";
                $params[] = $value;
            }

            if (!$sets) {
                continue;
            }

            $params[] = $id;

            db()->prepare("
                UPDATE trading_style_settings
                SET " . implode(', ', $sets) . "
                WHERE id = ?
            ")->execute($params);
        }

        $message = 'Trading style settings saved successfully.';
    } catch (Throwable $e) {
        $error = 'Save failed: ' . $e->getMessage();
    }
}

/*
|--------------------------------------------------------------------------
| Fetch rows
|--------------------------------------------------------------------------
*/

$styles = [];

try {
    if (!trading_style_table_exists('trading_style_settings')) {
        $error = 'The trading_style_settings table does not exist.';
    } else {
        $orderBy = trading_style_column_exists('sort_order')
            ? "ORDER BY COALESCE(sort_order, 999), id ASC"
            : "ORDER BY id ASC";

        $styles = db()->query("
            SELECT *
            FROM trading_style_settings
            {$orderBy}
        ")->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Throwable $e) {
    $error = 'Load failed: ' . $e->getMessage();
}

admin_layout_header('Trading Style Settings');

?>

<style>
/*
|--------------------------------------------------------------------------
| Layout protection
|--------------------------------------------------------------------------
| Prevents wide content from compressing the sidebar.
|--------------------------------------------------------------------------
*/
body {
    overflow-x: hidden;
}

body > div.min-h-screen.flex {
    align-items: stretch;
}

body > div.min-h-screen.flex > aside {
    flex: 0 0 280px !important;
    width: 280px !important;
    min-width: 280px !important;
}

body > div.min-h-screen.flex > main {
    min-width: 0 !important;
    overflow-x: hidden !important;
}

.ts-page {
    max-width: 1420px;
    margin: 0 auto;
}

.ts-hero {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    gap: 24px;
    margin-bottom: 22px;
}

.ts-title {
    font-size: 38px;
    line-height: 1.05;
    font-weight: 900;
    letter-spacing: -0.045em;
    color: #020617;
}

.ts-subtitle {
    margin-top: 8px;
    color: #64748b;
    font-size: 15px;
    max-width: 760px;
}

.ts-summary {
    display: flex;
    gap: 10px;
}

.ts-stat {
    min-width: 110px;
    background: #ffffff;
    border: 1px solid #e2e8f0;
    border-radius: 18px;
    padding: 12px 16px;
    box-shadow: 0 10px 24px rgba(15, 23, 42, .045);
}

.ts-stat span {
    display: block;
    color: #94a3b8;
    text-transform: uppercase;
    font-size: 10px;
    letter-spacing: .08em;
    font-weight: 900;
}

.ts-stat strong {
    display: block;
    color: #020617;
    font-size: 24px;
    line-height: 1.1;
    margin-top: 4px;
    font-weight: 900;
}

.ts-alert {
    border-radius: 16px;
    padding: 14px 18px;
    margin-bottom: 18px;
    font-weight: 800;
    font-size: 14px;
}

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

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

.ts-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
    background: #ffffff;
    border: 1px solid #e2e8f0;
    border-radius: 22px;
    padding: 14px;
    margin-bottom: 18px;
    box-shadow: 0 10px 24px rgba(15, 23, 42, .04);
}

.ts-search {
    width: 100%;
    max-width: 420px;
    height: 46px;
    border: 1px solid #cbd5e1;
    border-radius: 15px;
    padding: 0 15px;
    font-weight: 700;
    color: #0f172a;
    outline: none;
}

.ts-search:focus {
    border-color: #2563eb;
    box-shadow: 0 0 0 4px rgba(37, 99, 235, .12);
}

.ts-save-top {
    height: 46px;
    border: 0;
    border-radius: 15px;
    background: #2563eb;
    color: #ffffff;
    font-weight: 900;
    padding: 0 22px;
    cursor: pointer;
    box-shadow: 0 10px 20px rgba(37, 99, 235, .20);
}

.ts-grid {
    display: grid;
    grid-template-columns: 1fr;
    gap: 18px;
}

.ts-card {
    background: #ffffff;
    border: 1px solid #e2e8f0;
    border-radius: 26px;
    overflow: hidden;
    box-shadow: 0 10px 26px rgba(15, 23, 42, .045);
}

.ts-card-head {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 18px;
    padding: 20px 22px;
    background:
        linear-gradient(135deg, rgba(37, 99, 235, .06), rgba(15, 23, 42, .02)),
        #ffffff;
    border-bottom: 1px solid #e2e8f0;
}

.ts-style-name {
    font-size: 24px;
    font-weight: 900;
    letter-spacing: -0.03em;
    color: #020617;
}

.ts-style-key {
    color: #64748b;
    font-size: 13px;
    margin-top: 3px;
    font-weight: 700;
}

.ts-badges {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    justify-content: flex-end;
}

.ts-badge {
    display: inline-flex;
    align-items: center;
    height: 28px;
    padding: 0 10px;
    border-radius: 999px;
    background: #eff6ff;
    color: #1d4ed8;
    font-size: 12px;
    font-weight: 900;
}

.ts-card-body {
    padding: 20px 22px 22px;
}

.ts-section {
    margin-bottom: 20px;
}

.ts-section:last-child {
    margin-bottom: 0;
}

.ts-section-title {
    font-size: 12px;
    text-transform: uppercase;
    letter-spacing: .09em;
    color: #64748b;
    font-weight: 900;
    margin-bottom: 12px;
}

.ts-form-grid {
    display: grid;
    grid-template-columns: repeat(4, minmax(0, 1fr));
    gap: 12px;
}

.ts-asset-grid {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 14px;
}

.ts-asset-box {
    border: 1px solid #e2e8f0;
    background: #f8fafc;
    border-radius: 18px;
    padding: 14px;
}

.ts-asset-title {
    font-size: 14px;
    font-weight: 900;
    color: #020617;
    margin-bottom: 12px;
}

.ts-asset-inputs {
    display: grid;
    grid-template-columns: repeat(4, minmax(0, 1fr));
    gap: 10px;
}

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

.ts-input,
.ts-select {
    width: 100%;
    height: 42px;
    border: 1px solid #cbd5e1;
    border-radius: 13px;
    padding: 0 12px;
    font-size: 13px;
    color: #0f172a;
    font-weight: 750;
    outline: none;
    background: #ffffff;
}

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

.ts-toggle-wrap {
    height: 42px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.ts-check {
    width: 20px;
    height: 20px;
}

.ts-card-save {
    display: flex;
    justify-content: flex-end;
    padding: 16px 22px;
    border-top: 1px solid #e2e8f0;
    background: #f8fafc;
}

.ts-save-btn {
    height: 44px;
    border: 0;
    border-radius: 15px;
    background: #020617;
    color: #ffffff;
    font-weight: 900;
    padding: 0 20px;
    cursor: pointer;
}

.ts-empty {
    background: #ffffff;
    border: 1px solid #e2e8f0;
    border-radius: 24px;
    padding: 28px;
    color: #64748b;
    font-weight: 700;
}

@media (max-width: 1300px) {
    .ts-asset-grid {
        grid-template-columns: repeat(2, minmax(0, 1fr));
    }
}

@media (max-width: 980px) {
    body > div.min-h-screen.flex {
        display: block !important;
    }

    body > div.min-h-screen.flex > aside {
        width: 100% !important;
        min-width: 100% !important;
    }

    .ts-hero,
    .ts-toolbar,
    .ts-card-head {
        flex-direction: column;
        align-items: stretch;
    }

    .ts-summary {
        width: 100%;
    }

    .ts-stat {
        flex: 1;
    }

    .ts-form-grid,
    .ts-asset-grid {
        grid-template-columns: 1fr;
    }

    .ts-asset-inputs {
        grid-template-columns: repeat(2, minmax(0, 1fr));
    }
}
</style>

<div class="ts-page">

    <div class="ts-hero">
        <div>
            <div class="ts-title">Trading Style Settings</div>
            <div class="ts-subtitle">
                Manage execution models by style, asset class, risk profile, and institutional confirmation behavior. Gold and Silver are both metals, but Silver has its own SL-pip settings because XAGUSD price scale differs from XAUUSD.
            </div>
        </div>

        <div class="ts-summary">
            <div class="ts-stat">
                <span>Models</span>
                <strong><?= e(count($styles)) ?></strong>
            </div>

            <div class="ts-stat">
                <span>Active</span>
                <strong><?= e(count(array_filter($styles, fn($s) => !empty($s['is_active'])))) ?></strong>
            </div>
        </div>
    </div>

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

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

    <form method="post" id="styleForm">

        <div class="ts-toolbar">
            <input
                type="search"
                id="styleSearch"
                class="ts-search"
                placeholder="Search style, e.g. scalping, intraday, swing..."
            >

            <button type="submit" class="ts-save-top">
                Save All Changes
            </button>
        </div>

        <?php if (!$styles): ?>

            <div class="ts-empty">No trading styles found.</div>

        <?php else: ?>

            <div class="ts-grid">

                <?php foreach ($styles as $style): ?>

                    <?php
                        $styleId = (int)($style['id'] ?? 0);
                        $styleName = $style['style_name'] ?? ('Style #' . $styleId);
                        $styleKey = $style['style_key'] ?? '';
                    ?>

                    <section
                        class="ts-card"
                        data-style-card
                        data-style-search="<?= e(strtolower($styleName . ' ' . $styleKey)) ?>"
                    >

                        <div class="ts-card-head">
                            <div>
                                <div class="ts-style-name"><?= e($styleName) ?></div>
                                <div class="ts-style-key"><?= e($styleKey ? $styleKey : 'No style key') ?></div>
                            </div>

                            <div class="ts-badges">
                                <?php if (!empty($style['is_active'])): ?>
                                    <span class="ts-badge">Active</span>
                                <?php else: ?>
                                    <span class="ts-badge" style="background:#f1f5f9;color:#64748b;">Inactive</span>
                                <?php endif; ?>

                                <?php if (isset($style['min_rr'])): ?>
                                    <span class="ts-badge">Min RR <?= e($style['min_rr']) ?></span>
                                <?php endif; ?>

                                <?php if (isset($style['confirmation_strictness'])): ?>
                                    <span class="ts-badge"><?= e($style['confirmation_strictness']) ?> Confirm</span>
                                <?php endif; ?>
                            </div>
                        </div>

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

                            <div class="ts-section">
                                <div class="ts-section-title">Model Identity</div>

                                <div class="ts-form-grid">
                                    <?php foreach ($metaColumns as $column => $label): ?>
                                        <?php if (!isset($existingColumns[$column])) continue; ?>

                                        <div>
                                            <label class="ts-label"><?= e($label) ?></label>

                                            <?php if ($column === 'is_active'): ?>
                                                <div class="ts-toggle-wrap">
                                                    <input
                                                        class="ts-check"
                                                        type="checkbox"
                                                        name="styles[<?= e($styleId) ?>][<?= e($column) ?>]"
                                                        value="1"
                                                        <?= !empty($style[$column]) ? 'checked' : '' ?>
                                                    >
                                                    <span style="font-weight:800;color:#334155;">Enabled</span>
                                                </div>
                                            <?php else: ?>
                                                <input
                                                    class="ts-input"
                                                    type="text"
                                                    name="styles[<?= e($styleId) ?>][<?= e($column) ?>]"
                                                    value="<?= e($style[$column] ?? '') ?>"
                                                >
                                            <?php endif; ?>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>

                            <div class="ts-section">
                                <div class="ts-section-title">Asset Execution Models</div>
                                <div style="margin:-4px 0 12px;color:#64748b;font-size:12px;font-weight:700;">Gold and Silver share the metals logic, but use separate SL pips. TP RR can remain the same if desired.</div>

                                <div class="ts-asset-grid">
                                    <?php foreach ($assetGroups as $assetKey => $asset): ?>

                                        <?php
                                            $visibleAssetColumns = [];
                                            foreach ($asset['columns'] as $column => $label) {
                                                if (isset($existingColumns[$column])) {
                                                    $visibleAssetColumns[$column] = $label;
                                                }
                                            }

                                            if (!$visibleAssetColumns) {
                                                continue;
                                            }
                                        ?>

                                        <div class="ts-asset-box">
                                            <div class="ts-asset-title"><?= e($asset['label']) ?></div>

                                            <div class="ts-asset-inputs">
                                                <?php foreach ($visibleAssetColumns as $column => $label): ?>
                                                    <div>
                                                        <label class="ts-label"><?= e($label) ?></label>

                                                        <input
                                                            class="ts-input"
                                                            type="text"
                                                            name="styles[<?= e($styleId) ?>][<?= e($column) ?>]"
                                                            value="<?= e($style[$column] ?? '') ?>"
                                                        >
                                                    </div>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>

                            <div class="ts-section">
                                <div class="ts-section-title">Risk Engine</div>

                                <div class="ts-form-grid">
                                    <?php foreach ($riskColumns as $column => $label): ?>
                                        <?php if (!isset($existingColumns[$column])) continue; ?>

                                        <div>
                                            <label class="ts-label"><?= e($label) ?></label>

                                            <input
                                                class="ts-input"
                                                type="text"
                                                name="styles[<?= e($styleId) ?>][<?= e($column) ?>]"
                                                value="<?= e($style[$column] ?? '') ?>"
                                            >
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>

                            <div class="ts-section">
                                <div class="ts-section-title">Institutional Confirmation Logic</div>

                                <div class="ts-form-grid">
                                    <?php foreach ($logicColumns as $column => $label): ?>
                                        <?php if (!isset($existingColumns[$column])) continue; ?>

                                        <div>
                                            <label class="ts-label"><?= e($label) ?></label>

                                            <input
                                                class="ts-input"
                                                type="text"
                                                name="styles[<?= e($styleId) ?>][<?= e($column) ?>]"
                                                value="<?= e($style[$column] ?? '') ?>"
                                            >
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>

                        </div>

                        <div class="ts-card-save">
                            <button type="submit" class="ts-save-btn">Save This Model</button>
                        </div>

                    </section>

                <?php endforeach; ?>

            </div>

        <?php endif; ?>

    </form>

</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const search = document.getElementById('styleSearch');
    const cards = document.querySelectorAll('[data-style-card]');

    if (!search || !cards.length) {
        return;
    }

    search.addEventListener('input', function () {
        const value = search.value.trim().toLowerCase();

        cards.forEach(function (card) {
            const haystack = card.getAttribute('data-style-search') || '';
            card.style.display = haystack.includes(value) ? '' : 'none';
        });
    });
});
</script>

<?php admin_layout_footer(); ?>
