<?php

require_once __DIR__ . '/../config/database.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!function_exists('admin_guard')) {
    function admin_guard()
    {
        if (function_exists('requireAdminLogin')) {
            requireAdminLogin();
            return;
        }

        if (function_exists('require_admin')) {
            require_admin();
            return;
        }

        $isAdmin = !empty($_SESSION['admin_id']) || !empty($_SESSION['is_admin']);

        if (!$isAdmin) {
            header('Location: login.php');
            exit;
        }
    }
}

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

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

if (!function_exists('admin_setting_save')) {
    function admin_setting_save($key, $value)
    {
        $stmt = db()->prepare("
            INSERT INTO system_settings (setting_key, setting_value)
            VALUES (?, ?)
            ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)
        ");
        $stmt->execute([$key, $value]);
    }
}

if (!function_exists('admin_template_get')) {
    function admin_template_get($key, $fallback = '')
    {
        try {
            $stmt = db()->prepare("SELECT body FROM alert_templates WHERE template_key = ? LIMIT 1");
            $stmt->execute([$key]);
            $value = $stmt->fetchColumn();

            return $value !== false ? $value : $fallback;
        } catch (Throwable $e) {
            return $fallback;
        }
    }
}

if (!function_exists('admin_template_save')) {
    function admin_template_save($key, $channel, $body, $subject = null, $isActive = 1)
    {
        $stmt = db()->prepare("
            INSERT INTO alert_templates (template_key, channel, subject, body, is_active)
            VALUES (?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
                channel = VALUES(channel),
                subject = VALUES(subject),
                body = VALUES(body),
                is_active = VALUES(is_active)
        ");
        $stmt->execute([$key, $channel, $subject, $body, $isActive ? 1 : 0]);
    }
}

if (!function_exists('admin_ensure_alert_tables')) {
    function admin_ensure_alert_tables()
    {
        db()->exec("
            CREATE TABLE IF NOT EXISTS system_settings (
                id INT AUTO_INCREMENT PRIMARY KEY,
                setting_key VARCHAR(150) NOT NULL UNIQUE,
                setting_value TEXT NULL,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
        ");

        db()->exec("
            CREATE TABLE IF NOT EXISTS alert_templates (
                id INT AUTO_INCREMENT PRIMARY KEY,
                template_key VARCHAR(100) NOT NULL UNIQUE,
                subject VARCHAR(255) NULL,
                body TEXT NOT NULL,
                channel VARCHAR(30) NOT NULL DEFAULT 'email',
                is_active TINYINT(1) DEFAULT 1,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
        ");

        db()->exec("
            CREATE TABLE IF NOT EXISTS institutional_alerts (
                id INT AUTO_INCREMENT PRIMARY KEY,
                user_id INT NOT NULL,
                setup_key VARCHAR(64) NOT NULL,
                symbol VARCHAR(30) NOT NULL,
                timeframe VARCHAR(20) NOT NULL,
                style VARCHAR(50) NULL,
                side VARCHAR(10) NOT NULL,
                scenario_status VARCHAR(100) NULL,
                entry_price DECIMAL(18,8) NULL,
                entry_low DECIMAL(18,8) NULL,
                entry_high DECIMAL(18,8) NULL,
                stop_loss DECIMAL(18,8) NULL,
                tp1 DECIMAL(18,8) NULL,
                tp2 DECIMAL(18,8) NULL,
                tp3 DECIMAL(18,8) NULL,
                alert_trigger_price DECIMAL(18,8) NULL,
                liquidity_sweep_level DECIMAL(18,8) NULL,
                structure_trigger VARCHAR(120) NULL,
                scenario_snapshot LONGTEXT NULL,
                telegram_enabled TINYINT(1) DEFAULT 0,
                email_enabled TINYINT(1) DEFAULT 0,
                lifecycle_stage VARCHAR(50) DEFAULT 'TRACKING',
                is_active TINYINT(1) DEFAULT 1,
                last_checked_at DATETIME NULL,
                triggered_at DATETIME NULL,
                last_sent_at DATETIME NULL,
                send_count INT DEFAULT 0,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                UNIQUE KEY uniq_user_setup (user_id, setup_key, side)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
        ");

        db()->exec("
            CREATE TABLE IF NOT EXISTS institutional_alert_logs (
                id INT AUTO_INCREMENT PRIMARY KEY,
                alert_id INT NOT NULL,
                user_id INT NOT NULL,
                channel VARCHAR(30) NOT NULL,
                status VARCHAR(30) NOT NULL,
                message TEXT NULL,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                INDEX idx_alert_id (alert_id),
                INDEX idx_user_id (user_id)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
        ");
    }
}

if (!function_exists('admin_layout_header')) {
    function admin_layout_header($title)
    {
        ?>
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title><?= e($title) ?></title>
            <script src="https://cdn.tailwindcss.com"></script>
        </head>
        <body class="bg-slate-100 text-slate-900">
        <header class="bg-slate-950 text-white border-b border-slate-800">
            <div class="max-w-7xl mx-auto px-4 py-5 flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
                <div>
                    <p class="text-xs uppercase tracking-[0.25em] text-blue-300">Institutional Trading Assistant</p>
                    <h1 class="text-2xl font-bold"><?= e($title) ?></h1>
                </div>
                <nav class="flex flex-wrap gap-2 text-sm">
                    <a class="px-3 py-2 rounded-lg bg-white/10 hover:bg-white/20" href="control_panel.php">Control Panel</a>
                    <a class="px-3 py-2 rounded-lg bg-white/10 hover:bg-white/20" href="alert_settings.php">Alert Settings</a>
                    <a class="px-3 py-2 rounded-lg bg-white/10 hover:bg-white/20" href="active_alerts.php">Active Alerts</a>
                    <a class="px-3 py-2 rounded-lg bg-white/10 hover:bg-white/20" href="alert_logs.php">Alert Logs</a>
                    <a class="px-3 py-2 rounded-lg bg-blue-600 hover:bg-blue-700" href="dashboard.php">Dashboard</a>
                </nav>
            </div>
        </header>
        <main class="max-w-7xl mx-auto px-4 py-8">
        <?php
    }
}

if (!function_exists('admin_layout_footer')) {
    function admin_layout_footer()
    {
        ?>
        </main>
        </body>
        </html>
        <?php
    }
}
