<?php

require_once __DIR__ . '/admin_tool_helper.php';

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

$roles = ['execution', 'confirmation', 'structure', 'bias', 'macro'];

/**
 * Convert timeframe code to minutes for correct ordering.
 * MN/month is intentionally after weekly.
 */
function timeframe_minutes($code): int
{
    $code = strtoupper(trim((string)$code));

    if (in_array($code, ['MN', '1MN', 'MO', '1MO', 'MONTH', '1MONTH'], true)) {
        return 43200; // month, after 1W
    }

    if (preg_match('/^(\d+)\s*MIN$/', $code, $m)) {
        return (int)$m[1];
    }

    if (preg_match('/^(\d+)\s*M$/', $code, $m)) {
        return (int)$m[1];
    }

    if (preg_match('/^(\d+)\s*H$/', $code, $m)) {
        return (int)$m[1] * 60;
    }

    if (preg_match('/^(\d+)\s*D$/', $code, $m)) {
        return (int)$m[1] * 1440;
    }

    if (preg_match('/^(\d+)\s*W$/', $code, $m)) {
        return (int)$m[1] * 10080;
    }

    return 999999;
}

/*
|--------------------------------------------------------------------------
| Handle Actions
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['delete_id'])) {
            $deleteId = (int)$_POST['delete_id'];

            if ($deleteId > 0) {
                $stmt = db()->prepare("DELETE FROM timeframes WHERE id = ?");
                $stmt->execute([$deleteId]);
                $message = 'Timeframe deleted successfully.';
            }
        } elseif (($_POST['action'] ?? '') === 'add') {
            $newCode = strtoupper(trim($_POST['new_code'] ?? ''));
            $newInterval = trim($_POST['new_api_interval'] ?? '');

            if ($newCode === '') {
                throw new Exception('Code is required.');
            }

            if ($newInterval === '') {
                throw new Exception('API interval is required.');
            }

            $stmt = db()->prepare("
                INSERT INTO timeframes
                (
                    code,
                    api_interval,
                    role,
                    weight,
                    sweep_sensitivity,
                    bos_sensitivity,
                    is_active
                )
                VALUES (?, ?, ?, ?, ?, ?, ?)
            ");

            $stmt->execute([
                $newCode,
                $newInterval,
                trim($_POST['new_role'] ?? 'execution'),
                (float)($_POST['new_weight'] ?? 1),
                (int)($_POST['new_sweep_sensitivity'] ?? 5),
                (int)($_POST['new_bos_sensitivity'] ?? 5),
                !empty($_POST['new_is_active']) ? 1 : 0
            ]);

            $message = 'Timeframe added successfully.';
        } elseif (($_POST['action'] ?? '') === 'save') {
            foreach ($_POST['id'] ?? [] as $index => $id) {
                $id = (int)$id;

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

                $stmt = db()->prepare("
                    UPDATE timeframes
                    SET
                        code = ?,
                        api_interval = ?,
                        role = ?,
                        weight = ?,
                        sweep_sensitivity = ?,
                        bos_sensitivity = ?,
                        is_active = ?
                    WHERE id = ?
                ");

                $stmt->execute([
                    strtoupper(trim($_POST['code'][$index] ?? '')),
                    trim($_POST['api_interval'][$index] ?? ''),
                    trim($_POST['role'][$index] ?? 'execution'),
                    (float)($_POST['weight'][$index] ?? 1),
                    (int)($_POST['sweep_sensitivity'][$index] ?? 5),
                    (int)($_POST['bos_sensitivity'][$index] ?? 5),
                    isset($_POST['is_active'][$id]) ? 1 : 0,
                    $id
                ]);
            }

            $message = 'Timeframes updated successfully.';
        }
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

/*
|--------------------------------------------------------------------------
| Load Timeframes
|--------------------------------------------------------------------------
*/
$timeframes = [];

try {
    $stmt = db()->query("SELECT * FROM timeframes");
    $timeframes = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

    usort($timeframes, function ($a, $b) {
        $result = timeframe_minutes($a['code'] ?? '') <=> timeframe_minutes($b['code'] ?? '');

        if ($result !== 0) {
            return $result;
        }

        return (int)($a['id'] ?? 0) <=> (int)($b['id'] ?? 0);
    });
} catch (Throwable $e) {
    $error = 'Unable to load timeframes: ' . $e->getMessage();
}

$activeCount = count(array_filter($timeframes, fn($tf) => !empty($tf['is_active'])));

admin_layout_header('Timeframes');

?>

<style>
    /*
    |--------------------------------------------------------------------------
    | Page-level layout fix
    |--------------------------------------------------------------------------
    | This intentionally overrides the older admin_tool_helper.php layout
    | so the sidebar is no longer too wide and the content fits cleanly.
    |--------------------------------------------------------------------------
    */

    body {
        overflow-x: hidden;
    }

    body > div.min-h-screen.flex {
        display: grid !important;
        grid-template-columns: 224px minmax(0, 1fr) !important;
        width: 100% !important;
    }

    body > div.min-h-screen.flex > aside {
        width: 224px !important;
        min-width: 224px !important;
        max-width: 224px !important;
        padding: 20px 16px !important;
    }

    body > div.min-h-screen.flex > aside h1 {
        font-size: 22px !important;
        line-height: 1.15 !important;
        margin-top: 12px !important;
    }

    body > div.min-h-screen.flex > aside p {
        font-size: 11px !important;
        letter-spacing: .24em !important;
    }

    body > div.min-h-screen.flex > aside a {
        padding: 11px 14px !important;
        border-radius: 13px !important;
        font-size: 14px !important;
        line-height: 1.25 !important;
    }

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

    .tf-wrap {
        max-width: 1180px;
        margin: 0 auto;
    }

    .tf-top {
        display: grid;
        grid-template-columns: minmax(0, 1fr) auto;
        gap: 18px;
        align-items: end;
        margin-bottom: 18px;
    }

    .tf-title {
        font-size: 34px;
        font-weight: 900;
        letter-spacing: -0.035em;
        color: #020617;
        margin: 0;
    }

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

    .tf-stats {
        display: flex;
        gap: 10px;
    }

    .tf-stat {
        background: #ffffff;
        border: 1px solid #e2e8f0;
        border-radius: 18px;
        padding: 11px 16px;
        min-width: 88px;
        box-shadow: 0 8px 20px rgba(15, 23, 42, .035);
    }

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

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

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

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

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

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

    .tf-add {
        padding: 18px;
        border-bottom: 1px solid #e2e8f0;
        background:
            linear-gradient(135deg, rgba(37, 99, 235, .07), rgba(15, 23, 42, .02)),
            #ffffff;
    }

    .tf-add-title {
        font-size: 16px;
        font-weight: 900;
        color: #020617;
        margin-bottom: 14px;
    }

    .tf-add-grid {
        display: grid;
        grid-template-columns: 90px 120px 150px 90px 80px 80px 90px 150px;
        gap: 10px;
        align-items: end;
    }

    .tf-table-scroll {
        width: 100%;
        overflow-x: auto;
    }

    .tf-inner {
        min-width: 910px;
    }

    .tf-head,
    .tf-row {
        display: grid;
        grid-template-columns: 90px 120px 150px 90px 80px 80px 70px 130px;
        gap: 10px;
        align-items: center;
        padding: 12px 18px;
    }

    .tf-head {
        background: #f8fafc;
        border-bottom: 1px solid #e2e8f0;
        color: #64748b;
        font-size: 11px;
        font-weight: 900;
        text-transform: uppercase;
        letter-spacing: .055em;
    }

    .tf-row {
        border-bottom: 1px solid #f1f5f9;
        transition: background .15s ease;
    }

    .tf-row:hover {
        background: #f8fafc;
    }

    .tf-field {
        width: 100%;
        height: 40px;
        border: 1px solid #cbd5e1;
        background: #ffffff;
        border-radius: 12px;
        padding: 0 11px;
        color: #0f172a;
        font-size: 14px;
        font-weight: 750;
        outline: none;
    }

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

    .tf-label {
        display: block;
        margin-bottom: 6px;
        color: #475569;
        font-size: 11px;
        line-height: 1;
        text-transform: uppercase;
        font-weight: 900;
        letter-spacing: .05em;
    }

    .tf-check-wrap {
        height: 40px;
        display: flex;
        align-items: center;
    }

    .tf-check {
        width: 19px;
        height: 19px;
    }

    .tf-delete {
        height: 40px;
        border: 1px solid #fecaca;
        background: #fef2f2;
        color: #b91c1c;
        border-radius: 12px;
        padding: 0 14px;
        font-size: 13px;
        font-weight: 900;
        cursor: pointer;
    }

    .tf-delete:hover {
        background: #fee2e2;
    }

    .tf-savebar {
        display: flex;
        justify-content: space-between;
        gap: 16px;
        align-items: center;
        padding: 16px 18px;
        background: #f8fafc;
        border-top: 1px solid #e2e8f0;
    }

    .tf-note {
        color: #64748b;
        font-size: 13px;
    }

    .tf-primary {
        height: 44px;
        border: 0;
        border-radius: 14px;
        background: #2563eb;
        color: white;
        padding: 0 22px;
        font-size: 14px;
        font-weight: 900;
        box-shadow: 0 10px 18px rgba(37, 99, 235, .20);
        cursor: pointer;
    }

    .tf-primary:hover {
        background: #1d4ed8;
    }

    .tf-dark {
        height: 40px;
        border: 0;
        border-radius: 13px;
        background: #020617;
        color: #ffffff;
        padding: 0 18px;
        font-size: 13px;
        font-weight: 900;
        cursor: pointer;
    }

    .tf-dark:hover {
        background: #0f172a;
    }

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

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

        body > div.min-h-screen.flex > main {
            padding: 20px !important;
        }

        .tf-top {
            grid-template-columns: 1fr;
        }

        .tf-stats {
            justify-content: flex-start;
        }
    }

    @media (max-width: 700px) {
        .tf-title {
            font-size: 28px;
        }

        .tf-savebar {
            flex-direction: column;
            align-items: stretch;
        }

        .tf-primary {
            width: 100%;
        }
    }
</style>

<div class="tf-wrap">

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

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

    <div class="tf-top">
        <div>
            <h1 class="tf-title">Timeframes</h1>
            <p class="tf-subtitle">Manage chart intervals used by the institutional engine.</p>
        </div>

        <div class="tf-stats">
            <div class="tf-stat">
                <span>Active</span>
                <strong><?= e($activeCount) ?></strong>
            </div>

            <div class="tf-stat">
                <span>Total</span>
                <strong><?= e(count($timeframes)) ?></strong>
            </div>
        </div>
    </div>

    <section class="tf-card">

        <form method="post" class="tf-add">
            <input type="hidden" name="action" value="add">

            <div class="tf-add-title">Add New Timeframe</div>

            <div class="tf-add-grid">
                <div>
                    <label class="tf-label">Code</label>
                    <input class="tf-field" type="text" name="new_code" placeholder="5M" required>
                </div>

                <div>
                    <label class="tf-label">API</label>
                    <input class="tf-field" type="text" name="new_api_interval" placeholder="5min" required>
                </div>

                <div>
                    <label class="tf-label">Role</label>
                    <select class="tf-field" name="new_role">
                        <?php foreach ($roles as $role): ?>
                            <option value="<?= e($role) ?>"><?= e(ucfirst($role)) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div>
                    <label class="tf-label">Weight</label>
                    <input class="tf-field" type="number" step="0.01" name="new_weight" value="1.00">
                </div>

                <div>
                    <label class="tf-label">Sweep</label>
                    <input class="tf-field" type="number" min="1" max="10" name="new_sweep_sensitivity" value="5">
                </div>

                <div>
                    <label class="tf-label">BOS</label>
                    <input class="tf-field" type="number" min="1" max="10" name="new_bos_sensitivity" value="5">
                </div>

                <div>
                    <label class="tf-label">Active</label>
                    <div class="tf-check-wrap">
                        <input class="tf-check" type="checkbox" name="new_is_active" value="1" checked>
                    </div>
                </div>

                <div>
                    <label class="tf-label">&nbsp;</label>
                    <button type="submit" class="tf-dark">Add Timeframe</button>
                </div>
            </div>
        </form>

        <form method="post">
            <input type="hidden" name="action" value="save">

            <div class="tf-table-scroll">
                <div class="tf-inner">
                    <div class="tf-head">
                        <div>Code</div>
                        <div>API</div>
                        <div>Role</div>
                        <div>Weight</div>
                        <div>Sweep</div>
                        <div>BOS</div>
                        <div>On</div>
                        <div></div>
                    </div>

                    <?php foreach ($timeframes as $tf): ?>
                        <div class="tf-row">
                            <div>
                                <input type="hidden" name="id[]" value="<?= e($tf['id']) ?>">
                                <input class="tf-field" type="text" name="code[]" value="<?= e($tf['code'] ?? '') ?>">
                            </div>

                            <div>
                                <input class="tf-field" type="text" name="api_interval[]" value="<?= e($tf['api_interval'] ?? '') ?>">
                            </div>

                            <div>
                                <select class="tf-field" name="role[]">
                                    <?php foreach ($roles as $role): ?>
                                        <option value="<?= e($role) ?>" <?= (($tf['role'] ?? '') === $role) ? 'selected' : '' ?>>
                                            <?= e(ucfirst($role)) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div>
                                <input class="tf-field" type="number" step="0.01" name="weight[]" value="<?= e($tf['weight'] ?? '1.00') ?>">
                            </div>

                            <div>
                                <input class="tf-field" type="number" min="1" max="10" name="sweep_sensitivity[]" value="<?= e($tf['sweep_sensitivity'] ?? '5') ?>">
                            </div>

                            <div>
                                <input class="tf-field" type="number" min="1" max="10" name="bos_sensitivity[]" value="<?= e($tf['bos_sensitivity'] ?? '5') ?>">
                            </div>

                            <div class="tf-check-wrap">
                                <input
                                    class="tf-check"
                                    type="checkbox"
                                    name="is_active[<?= e($tf['id']) ?>]"
                                    value="1"
                                    <?= !empty($tf['is_active']) ? 'checked' : '' ?>
                                >
                            </div>

                            <div>
                                <button
                                    type="submit"
                                    name="delete_id"
                                    value="<?= e($tf['id']) ?>"
                                    onclick="return confirm('Delete timeframe?')"
                                    class="tf-delete"
                                    formnovalidate
                                >
                                    Delete
                                </button>
                            </div>
                        </div>
                    <?php endforeach; ?>

                    <?php if (!$timeframes): ?>
                        <div style="padding: 26px; color: #64748b; text-align: center;">
                            No timeframes found.
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="tf-savebar">
                <div class="tf-note">Sorted from lowest to highest. MN appears after 1W.</div>
                <button type="submit" class="tf-primary">Save Changes</button>
            </div>
        </form>

    </section>

</div>

<?php admin_layout_footer(); ?>
