<?php include __DIR__ . '/bootstrap.php'; ?>

<?php
// DEBUG BAR
$__cfg_dbg = @parse_ini_file(__DIR__ . '/../config.ini');
if (!empty($__cfg_dbg['debug'])) {
    $__sess = [
        'name'     => session_name(),
        'id'       => session_id(),
        'loggedin' => isset($_SESSION['loggedin']) ? (int)$_SESSION['loggedin'] : 0,
        'user'     => $_SESSION['name'] ?? ''
    ];
    echo "<div style=\"position:fixed;z-index:99999;bottom:0;left:0;right:0;background:#111;color:#0f0;font:12px monospace;padding:6px 10px;border-top:1px solid #090\">";
    echo "BASE=" . htmlspecialchars(app_base_path() ?: '/', ENT_QUOTES, 'UTF-8');
    echo " | SESSION_NAME=" . htmlspecialchars($__sess['name'], ENT_QUOTES, 'UTF-8');
    echo " | ID=" . htmlspecialchars($__sess['id'], ENT_QUOTES, 'UTF-8');
    echo " | LOGGEDIN=" . (int)$__sess['loggedin'];
    echo " | USER=" . htmlspecialchars($__sess['user'], ENT_QUOTES, 'UTF-8');
    echo " | cookie_path=" . htmlspecialchars(ini_get('session.cookie_path'), ENT_QUOTES, 'UTF-8');
    echo "</div>";
}
?>

<?php
ini_set('display_errors', 0);

include __DIR__ . '/functions.php';
include __DIR__ . '/json_utils.php';

// get req count
$count = $db->getRecordCount('actreq');
$displayCount = ($count !== '' && $count > 99) ? '99+' : $count;
$badgeHtml = ($count === '') ? '' : '<span class="badge badge-danger" 
    style="background:red; color:white; border-radius:50%; padding:4px 8px; font-size:12px; margin-left:5px;">' . $displayCount . '</span>';

// dynamic branding/settings
$superusername = getmodsbyid('1') ?? 'superadmin';
$superpassword = getmodsbyid('2') ?? 'superadmin';
$weblink       = getmodsbyid('3') ?? 'https://t.me/RTXshowcase';
$brandname     = getmodsbyid('4') ?? 'RTX Rebrands';

$icon32x32 = getmodsbyid('8')  ?? 'img/ficon/favicon-32x32.png';
$icon16x16 = getmodsbyid('9')  ?? 'img/ficon/favicon-16x16.png';
$iconaplle = getmodsbyid('10') ?? 'img/ficon/apple-touch-icon.png';
$iconmain  = getmodsbyid('11') ?? 'img/ficon/site.webmanifest';

// ensure session exists (bootstrap should have started it)
if (session_status() === PHP_SESSION_NONE) { /* noop */ }

// read logged-in user
$log_check = $db->select('user', '*', 'id = :id', '', [':id' => 1]);
$loggedinuser = !empty($log_check) ? $log_check[0]['username'] : null;

// logout handler
if (isset($_REQUEST['logout'])) {
    session_destroy();
    setcookie("auth", "");
    redirect('index.php');
}

// idle timeout
$time = $_SERVER['REQUEST_TIME'];
$timeout_duration = 900;
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY']) > $timeout_duration) {
    session_unset();
    session_destroy();
}
$_SESSION['LAST_ACTIVITY'] = $time;

// helpers
function sanitize($data) {
    $data = trim($data);
    $data = htmlspecialchars($data, ENT_QUOTES);
    $data = SQLite3::escapeString($data);
    return $data;
}

function adminisking() {
    global $superusername;
    if (($_SESSION['name'] ?? '') === $superusername) {
        return $_SESSION['name'] . ' 🔒';
    } else {
        return ($_SESSION['name'] ?? '') . ' 🔥';
    }
}

// role flags
$currentUser     = $_SESSION['name']        ?? '';
$currentPassword = $_SESSION['passwordxyz'] ?? null;

$isSuperAdmin = ($currentUser === $superusername) || ($currentPassword === $superpassword);
$isAdmin      = ($currentUser === 'admin');
?>
<!-- header.php -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title><?php echo $brandname; ?></title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <meta content="" name="keywords">
    <meta content="" name="description">

    <!-- Favicon -->
    <link rel="apple-touch-icon" sizes="180x180" href="<?php echo $iconaplle ?>">
    <link rel="icon" type="image/png" sizes="32x32" href="<?php echo $icon32x32 ?>">
    <link rel="icon" type="image/png" sizes="16x16" href="<?php echo $icon16x16 ?>">
    <link rel="manifest" href="<?php echo $iconmain ?>">

    <!-- Google Web Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600&family=Roboto:wght@500;700&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Limelight&family=Monoton&family=Montserrat:ital,wght@0,100..900;1,100..900&family=Notable&display=swap" rel="stylesheet">

    <!-- Icon Font Stylesheet -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.4.1/font/bootstrap-icons.css" rel="stylesheet">

    <!-- Libraries Stylesheet -->
    <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet">
    <link href="lib/tempusdominus/css/tempusdominus-bootstrap-4.min.css" rel="stylesheet" />

    <!-- Customized Bootstrap Stylesheet -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- Template Stylesheet -->
    <link href="css/style.css" rel="stylesheet">
</head>
<style>
.version { font-size: .75rem; color:#6c757d; vertical-align:bottom; position:relative; top:6px; }
.bytx { font-size:.90rem; color:#EC2E2E; vertical-align:middle; }
</style>

<body>
<div class="container-fluid position-relative d-flex p-0">
    <!-- Spinner Start -->
    <div id="spinner"
         class="show bg-dark position-fixed translate-middle w-100 vh-100 top-50 start-50 d-flex align-items-center justify-content-center">
        <div class="spinner-border text-primary" style="width:3rem;height:3rem;" role="status">
            <span class="sr-only">Loading...</span>
        </div>
    </div>
    <!-- Spinner End -->

    <!-- Sidebar Start -->
    <div class="sidebar pe-4 pb-3">
        <nav class="navbar bg-secondary navbar-dark">
            <a href="index.php" class="navbar-brand mx-4 mb-2">
                <div class="d-flex flex-column">
                    <div class="d-flex align-items-center">
                        <h3 class="text-primary mb-0"><i class="fa fa-cubes me-2"></i> YouTivi</h3>
                        <span class="version ms-2">v 1.20</span>
                    </div>
                    <span class="bytx mt-0 mb-0">S E T T I N G S</span>
                </div>
            </a>

            <div class="navbar-nav w-100">

                <!-- Super Admin link: ONLY for superadmin -->
                <?php if ($isSuperAdmin): ?>
                    <a href="admin.php"
                       class="nav-item nav-link <?php echo basename($_SERVER['PHP_SELF']) === 'admin.php' ? 'active' : ''; ?>">
                        <i class="fa fa-globe me-2"></i>🔒 Super Admin
                    </a>
                <?php endif; ?>

                <a href="main.php"
                   class="nav-item nav-link <?php echo basename($_SERVER['PHP_SELF']) === 'main.php' ? 'active' : ''; ?>">
                    <i class="fa fa-globe me-2"></i>DNS Settings
                </a>

                <a href="user_manage.php"
                   class="nav-item nav-link <?php echo basename($_SERVER['PHP_SELF']) === 'user_manage.php' ? 'active' : ''; ?>">
                    <i class="fa fa-user me-2"></i>MAC Users
                </a>

                <a href="mac_manage.php"
                   class="nav-item nav-link <?php echo basename($_SERVER['PHP_SELF']) === 'mac_manage.php' ? 'active' : ''; ?>">
                    <i class="fa fa-id-card me-2"></i>MAC Settings
                </a>

                <a href="parent_pin.php"
                   class="nav-item nav-link <?php echo basename($_SERVER['PHP_SELF']) === 'parent_pin.php' ? 'active' : ''; ?>">
                    <i class="fa fa-key me-2"></i>Parental PIN
                </a>

                <a href="demo_plist.php"
                   class="nav-item nav-link <?php echo basename($_SERVER['PHP_SELF']) === 'demo_plist.php' ? 'active' : ''; ?>">
                    <i class="fa fa-chain-broken me-2"></i>Demo
                </a>

                <a href="activation_request.php"
                   class="nav-item nav-link <?php echo basename($_SERVER['PHP_SELF']) === 'activation_request.php' ? 'active' : ''; ?>">
                    <i class="fa fa-paper-plane me-2"></i>
                    Requests <?php echo $badgeHtml; ?>
                </a>

                <a href="noti_settings.php"
                   class="nav-item nav-link <?php echo basename($_SERVER['PHP_SELF']) === 'noti_settings.php' ? 'active' : ''; ?>">
                    <i class="fa fa-commenting me-2"></i>Notification
                </a>

                <a href="intro_settings.php"
                   class="nav-item nav-link <?php echo basename($_SERVER['PHP_SELF']) === 'intro_settings.php' ? 'active' : ''; ?>">
                    <i class="fa fa-video-camera me-2"></i>Intro Settings
                </a>

                <a href="hot_sports.php"
                   class="nav-item nav-link <?php echo basename($_SERVER['PHP_SELF']) === 'hot_sports.php' ? 'active' : ''; ?>">
                    <i class="fa fa-futbol-o me-2"></i>Hot Leagues
                </a>

                <a href="sport_api.php"
                   class="nav-item nav-link <?php echo basename($_SERVER['PHP_SELF']) === 'sport_api.php' ? 'active' : ''; ?>">
                    <i class="fa fa-futbol-o me-2"></i>Sports API Key
                </a>

                <a href="dev_option.php"
                   class="nav-item nav-link <?php echo basename($_SERVER['PHP_SELF']) === 'dev_option.php' ? 'active' : ''; ?>">
                    <i class="fa fa-sliders me-2"></i>Advance Option
                </a>

                <a href="user.php"
                   class="nav-item nav-link <?php echo basename($_SERVER['PHP_SELF']) === 'user.php' ? 'active' : ''; ?>">
                    <i class="fa fa-user me-2"></i>Credentials
                </a>

                <!-- Captcha Settings: visible to BOTH superadmin and admin, placed at bottom -->
                <?php if ($isSuperAdmin || $isAdmin): ?>
                    <a href="admin_captcha.php"
                       class="nav-item nav-link <?php echo basename($_SERVER['PHP_SELF']) === 'admin_captcha.php' ? 'active' : ''; ?>">
                        <i class="fa fa-shield me-2"></i>Captcha Settings
                    </a>
                <?php endif; ?>

            </div>
        </nav>
    </div>
    <!-- Sidebar End -->

    <!-- Content Start -->
    <div class="content">

        <!-- Navbar Start -->
        <nav class="navbar navbar-expand bg-secondary navbar-dark sticky-top px-4 py-0">
            <a href="index.php" class="navbar-brand d-flex d-lg-none me-4">
                <h2 class="text-primary mb-0"><i class="fa fa-cubes"></i></h2>
            </a>
            <a href="#" class="sidebar-toggler flex-shrink-0">
                <i class="fa fa-bars"></i>
            </a>
            <div class="navbar-nav align-items-center ms-auto">
                <div class="nav-item dropdown">
                    <a href="#" class="nav-link dropdown-toggle" data-bs-toggle="dropdown">
                        <img class="rounded-circle me-lg-2" src="img/rtx_bg.png" alt=""
                             style="width:40px;height:40px;">
                        <span class="d-none d-lg-inline-flex"><?php echo adminisking(); ?></span>
                    </a>
                    <div class="dropdown-menu dropdown-menu-end bg-secondary border-0 rounded-0 rounded-bottom m-0">
                        <a href="<?php echo $weblink; ?>" class="dropdown-item"><?php echo $brandname; ?></a>
                        <a href="<?= basename($_SERVER["SCRIPT_NAME"]) . '?logout' ?>" class="dropdown-item">Log Out</a>
                    </div>
                </div>
            </div>
        </nav>
        <!-- Navbar End -->
