<?php
session_start();
require 'config/function.php';
require_once __DIR__ . '/config/topup.php';
require_once __DIR__ . '/config/whatsapp.php';

$admin = isset($_SESSION['admin']) ? $_SESSION['admin'] : null;
if (!$admin) {
    header('location: login');
}
$cuk = mysqli_query($call, "SELECT * FROM tb_settings");
$cek_web = mysqli_fetch_array($cuk);
$brand = htmlspecialchars((string)($cek_web['brand'] ?? ''), ENT_QUOTES, 'UTF-8');
$annountcement = htmlspecialchars((string)($cek_web['annountcement'] ?? ''), ENT_QUOTES, 'UTF-8');
$min_topup = htmlspecialchars((string)($cek_web['min_topup'] ?? ''), ENT_QUOTES, 'UTF-8');
$rate_coin = (string)($cek_web['rate_coin'] ?? '7.5');
$min_rate = $rate_coin;
$favicon = trim((string)($cek_web['favicon'] ?? ''));
if ($favicon === '' || !preg_match('#^assets/images/[A-Za-z0-9._/-]+$#', $favicon)) {
    $favicon = 'assets/images/icon.png';
}
function asset_version(string $path): string
{
    $fullPath = __DIR__ . '/' . ltrim($path, '/');

    return is_file($fullPath) ? '?v=' . filemtime($fullPath) : '';
}

function page_url(string $page, array $params = []): string
{
    $query = http_build_query($params);
    if ($page === 'dashboard') {
        return $query !== '' ? './?' . $query : './';
    }

    $path = rawurlencode($page);

    return $query !== '' ? $path . '?' . $query : $path;
}

$faviconVersion = asset_version($favicon);
$pisah = explode('|', $brand);
$judul = trim($pisah[0] ?? '');

$pages = [
    "AddAgent" => 'page/Add-Agent.php',
    "ManagementAgent" => 'page/Management-Agent.php',
    "AgentTransaction" => 'page/Agent-Transaction.php',
    "Member" => 'page/Member.php',
    "MemberTransaction" => 'page/Member-Transaction.php',
    "GameHistory" => 'page/GameHistory.php',
    "Topup" => 'page/Topup.php',
    "Provider" => 'page/Provider.php',
    "Invoice" => 'page/Invoice.php',
    "ControlRtp" => 'page/ControlRtp.php',
    "callRtp" => 'page/callRtp.php',
    "Docs" => 'page/Docs.php',
    "Profile" => 'page/Profile.php',
    "VerifyWhatsapp" => 'page/Verify-Whatsapp.php',
    "dashboard" => 'dashboard.php',
    "ProsesTopup" => 'page/ProsesTopup.php',
    "404" => '404.php',
    "Settings" => 'page/Settings.php',
    "edit_bank" => 'page/edit_bank.php',
    "Blocked" => 'page/blocked.php'
];

$pageTitles = [
    "dashboard" => "Dashboard",
    "AddAgent" => "Add Agent",
    "ManagementAgent" => "Management Agent",
    "AgentTransaction" => "Agent Transaction",
    "Member" => "Member",
    "MemberTransaction" => "Member Transaction",
    "GameHistory" => "Riwayat Game",
    "Topup" => "Topup",
    "Provider" => "Provider",
    "Invoice" => "Invoice",
    "ControlRtp" => "Control RTP",
    "callRtp" => "Call & Rtp",
    "Docs" => "Docs",
    "Profile" => "Profile",
    "VerifyWhatsapp" => "Verifikasi WhatsApp",
    "ProsesTopup" => "Proses Topup Balance",
    "404" => "Error 404",
    "Settings" => "Settings Admin",
    "edit_bank" => "Edit Bank",
    "Blocked" => "Agent Blocked"
];

$page = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_SPECIAL_CHARS);
if (is_null($page) || $page === '') {
    $requestPath = parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH) ?: '';
    $basePath = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/');
    if ($basePath !== '' && $basePath !== '/' && strpos($requestPath, $basePath . '/') === 0) {
        $requestPath = substr($requestPath, strlen($basePath));
    }
    $cleanPage = trim($requestPath, '/');
    if ($cleanPage === 'index' || $cleanPage === 'index.php') {
        $cleanPage = '';
    }
    if ($cleanPage !== '' && strpos($cleanPage, '/') === false) {
        $page = rawurldecode($cleanPage);
    }
}
if (is_null($page) || !preg_match('/^[a-zA-Z0-9_]+$/', $page) || $page === '') {
    $page = 'dashboard';
}
if (!array_key_exists($page, $pages)) {
    $page = '404';
}

$usesDataTables = in_array($page, [
    'AddAgent',
    'ManagementAgent',
    'AgentTransaction',
    'Member',
    'MemberTransaction',
    'GameHistory',
    'Provider',
    'ControlRtp',
    'ProsesTopup'
], true);
$usesDatePicker = $page === 'ProsesTopup';

$requiresWhatsappVerification = false;

if ($admin && ($admin['agent_level'] ?? '') !== 'admin') {
    $requiresWhatsappVerification = wa_agent_requires_verification($call, agent_public_name((array)$admin));

    if ($requiresWhatsappVerification && $page !== 'VerifyWhatsapp') {
        header('Location: ' . page_url('VerifyWhatsapp'));
        exit();
    }
}

if (!$requiresWhatsappVerification && $page === 'VerifyWhatsapp') {
    header('Location: ' . page_url('dashboard'));
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $brand; ?></title>
    <link rel="stylesheet" href="assets/compiled/css/app.css<?= asset_version('assets/compiled/css/app.css') ?>">
    <link rel="stylesheet" href="assets/compiled/css/app-dark.css<?= asset_version('assets/compiled/css/app-dark.css') ?>">
    <link rel="stylesheet" href="assets/compiled/css/iconly.css<?= asset_version('assets/compiled/css/iconly.css') ?>">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <?php if ($page === '404'): ?>
        <link rel="stylesheet" href="assets/compiled/css/error.css">
    <?php endif; ?>
    <?php if ($usesDataTables): ?>
    <link rel="stylesheet" href="assets/extensions/datatables.net-bs5/css/dataTables.bootstrap5.min.css">
    <?php endif; ?>
    <?php if ($usesDatePicker): ?>
    <link rel="stylesheet" href="assets/vendors/bootstrap-datepicker/bootstrap-datepicker.min.css">
    <?php endif; ?>
    <link rel="stylesheet" href="assets/css/costum/style.css<?= asset_version('assets/css/costum/style.css') ?>">
    <style>
        #sidebar .app-sidebar-modern.sidebar-wrapper{display:block;width:280px}
        .app-navbar-modern{display:block}
        .app-navbar-modern .nav-icon-button{display:inline-flex!important;align-items:center!important;justify-content:center!important;width:46px!important;height:46px!important;min-width:46px!important;border-radius:12px}
        .app-navbar-modern .hamburger-lines,.app-navbar-modern .hamburger-lines:before,.app-navbar-modern .hamburger-lines:after{display:block;width:24px;height:3px;background:#8ab4ff;border-radius:999px;content:"";position:relative}
        .app-navbar-modern .hamburger-lines:before,.app-navbar-modern .hamburger-lines:after{position:absolute;left:0}
        .app-navbar-modern .hamburger-lines:before{top:-8px}
        .app-navbar-modern .hamburger-lines:after{top:8px}
    </style>
    <link rel="shortcut icon" href="<?= htmlspecialchars($favicon . $faviconVersion, ENT_QUOTES, 'UTF-8') ?>" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <?php if ($page === 'Docs'): ?>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css" rel="stylesheet">
    <?php endif; ?>
</head>
<body>
    <script src="assets/static/js/initTheme.js<?= asset_version('assets/static/js/initTheme.js') ?>"></script>
    <div id="app">
        <div id="sidebar">
            <?php include 'sidebar.php'; ?>
        </div>
        <div id="main" class="layout-navbar navbar-fixed">
            <?php include 'navbar.php'; ?>
            <div id="main-content">
                <?php include 'breadcrumb.php'; ?>
                <div class="page-content">
                    <section class="section">
                        <?php
                        include $pages[$page];
                        ?>
                    </section>
                </div>
            </div>
            <?php include 'footer.php'; ?>
        </div>
    </div>

    <div class="modal fade" id="annountcementModalLabel" tabindex="-1" aria-labelledby="annountcementModalTitle" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="annountcementModalTitle">Announcement</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <?php echo $annountcement; ?>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="bestAgentModalLabel" tabindex="-1" aria-labelledby="bestAgentModalTitle" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="bestAgentModalTitle">Best Agent List</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    E1****ls6F | 11.354.370 | wuwu
                    G5***jy0VN | 8.487.301  | svrleo
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <script src="assets/static/js/components/dark.js<?= asset_version('assets/static/js/components/dark.js') ?>"></script>
    <script src="assets/extensions/perfect-scrollbar/perfect-scrollbar.min.js<?= asset_version('assets/extensions/perfect-scrollbar/perfect-scrollbar.min.js') ?>"></script>
    <script src="assets/compiled/js/app.js<?= asset_version('assets/compiled/js/app.js') ?>"></script>
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            setTimeout(function () {
                if (window.sidebar) {
                    return;
                }

                var sidebar = document.getElementById("sidebar");
                if (!sidebar) {
                    return;
                }

                document.querySelectorAll(".burger-btn").forEach(function (button) {
                    button.addEventListener("click", function (event) {
                        event.preventDefault();
                        sidebar.classList.toggle("active");
                    });
                });

                document.querySelectorAll(".sidebar-hide").forEach(function (button) {
                    button.addEventListener("click", function (event) {
                        event.preventDefault();
                        sidebar.classList.remove("active");
                    });
                });
            }, 80);
        });
    </script>
    <script src="assets/extensions/jquery/jquery.min.js"></script>
    <?php if ($usesDataTables): ?>
    <script src="assets/extensions/datatables.net/js/jquery.dataTables.min.js"></script>
    <script src="assets/extensions/datatables.net-bs5/js/dataTables.bootstrap5.min.js"></script>
    <script src="assets/js/data-table.js"></script>
    <?php endif; ?>
    <?php if ($usesDatePicker): ?>
    <script src="assets/vendors/bootstrap-datepicker/bootstrap-datepicker.min.js"></script>
    <?php endif; ?>
    <?php if ($page === 'dashboard'): ?>
    <script src="assets/extensions/chart.js/chart.umd.js"></script>
    <script src="assets/js/chartjs.js"></script>
    <script src="assets/extensions/apexcharts/apexcharts.min.js"></script>
    <script src="assets/js/dashboard.js"></script>
    <?php endif; ?>
    <script src="assets/extensions/sweetalert2/sweetalert2.min.js"></script>
    <?php if ($page === 'Docs'): ?>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/php.min.js"></script>
    <script>hljs.highlightAll();</script>
    <?php endif; ?>
    <?php include 'notification.php'; ?>
    <?php include 'javascript.php'; ?>
</body>
</html>
