<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($pdo)) {
    $configPath = __DIR__ . '/../config.php';
    if (file_exists($configPath)) {
        require_once $configPath;
    }
}

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

if (!function_exists('app_setting')) {
    function app_setting(PDO $pdo, string $key, string $default = ''): string {
        try {
            $stmt = $pdo->prepare("SELECT setting_value FROM app_settings WHERE setting_key = ? LIMIT 1");
            $stmt->execute([$key]);
            $value = $stmt->fetchColumn();
            return ($value !== false && $value !== null && $value !== '') ? (string)$value : $default;
        } catch (Throwable $e) {
            return $default;
        }
    }
}

if (!function_exists('access_label')) {
    function access_label(string $level): string {
        $labels = [
            'guest' => 'Guest',
            'member' => 'Member',
            'training' => 'Training',
            'leader' => 'Leader',
            'premium' => 'Premium',
            'admin' => 'Admin',
            'founder' => 'Founder'
        ];

        $level = strtolower(trim($level));
        return $labels[$level] ?? ucfirst($level ?: 'Member');
    }
}

$isLoggedIn = !empty($_SESSION['user_id']);
$isAdmin = (($_SESSION['role'] ?? '') === 'admin');

$appName = isset($pdo) ? app_setting($pdo, 'app_name', 'My Yielded Vessels') : 'My Yielded Vessels';
$loginLogo = isset($pdo) ? app_setting($pdo, 'login_logo_path', '/men_v14/images/iamyielded.jpg') : '/men_v14/images/iamyielded.jpg';

$themeBackground = isset($pdo) ? app_setting($pdo, 'theme_background', '#10180f') : '#10180f';
$themeForeground = isset($pdo) ? app_setting($pdo, 'theme_foreground', '#f2f8ed') : '#f2f8ed';
$themeAccent = isset($pdo) ? app_setting($pdo, 'theme_color', '#a3b18a') : '#a3b18a';
$themeSecondary = isset($pdo) ? app_setting($pdo, 'theme_accent', '#588157') : '#588157';
$themePanel = isset($pdo) ? app_setting($pdo, 'theme_panel', '#1b2a1a') : '#1b2a1a';

$menuHome = isset($pdo) ? app_setting($pdo, 'menu_home', 'Home') : 'Home';
$menuDirectory = isset($pdo) ? app_setting($pdo, 'menu_directory', 'Directory') : 'Directory';
$menuRotation = isset($pdo) ? app_setting($pdo, 'menu_rotation', 'Prayer Rotation') : 'Prayer Rotation';
$menuPrayer = isset($pdo) ? app_setting($pdo, 'menu_prayer', 'Prayer Guide') : 'Prayer Guide';
$menuAssignments = isset($pdo) ? app_setting($pdo, 'menu_assignments', 'Assignments') : 'Assignments';
$menuProfile = isset($pdo) ? app_setting($pdo, 'menu_profile', 'Profile') : 'Profile';
$menuAdmin = isset($pdo) ? app_setting($pdo, 'menu_admin', 'Admin') : 'Admin';
$menuLogout = isset($pdo) ? app_setting($pdo, 'menu_logout', 'Logout') : 'Logout';

$username = $_SESSION['username'] ?? 'member';
$userAccessLevel = 'member';

if ($isLoggedIn && isset($pdo)) {
    try {
        $stmt = $pdo->prepare("SELECT access_level FROM users WHERE id = ? LIMIT 1");
        $stmt->execute([$_SESSION['user_id']]);
        $foundAccess = $stmt->fetchColumn();

        if ($foundAccess !== false && $foundAccess !== null && $foundAccess !== '') {
            $userAccessLevel = (string)$foundAccess;
        }
    } catch (Throwable $e) {
        $userAccessLevel = 'member';
    }
}

$pageTitleFinal = isset($pageTitle) && $pageTitle !== '' ? $pageTitle . ' - ' . $appName : $appName;
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?php echo h($pageTitleFinal); ?></title>
  <link rel="stylesheet" href="css/styles.css?v=152">
  <link rel="stylesheet" href="assets/css/styles.css?v=152">
  <style>
    :root {
      --bg: <?php echo h($themeBackground); ?>;
      --text: <?php echo h($themeForeground); ?>;
      --panel: <?php echo h($themePanel); ?>;
      --accent: <?php echo h($themeAccent); ?>;
      --purple: <?php echo h($themeSecondary); ?>;
    }

    body {
      background: var(--bg) !important;
      color: var(--text) !important;
    }

    .topbar,
    .panel,
    .card,
    .login-card {
      background-color: var(--panel);
    }

    .btn-primary,
    button.btn-primary,
    .topbar a:hover {
      background: linear-gradient(135deg, var(--purple), var(--accent));
    }

    a,
    .muted strong {
      color: var(--accent);
    }

    .access-pill {
      display: inline-flex;
      align-items: center;
      gap: .35rem;
      padding: .45rem .75rem;
      border-radius: 999px;
      border: 1px solid rgba(255,255,255,.18);
      background: rgba(255,255,255,.08);
      color: var(--text);
      font-size: .9rem;
      font-weight: 700;
      white-space: nowrap;
    }

    .access-pill span {
      color: var(--accent);
    }
  </style>
</head>
<body>

<header class="topbar">
  <div class="container topbar-inner">
    <a href="dashboard.php" class="brand">
      <img src="<?php echo h($loginLogo); ?>?v=152" alt="<?php echo h($appName); ?>" class="brand-logo">
    </a>

    <?php if ($isLoggedIn): ?>
      <button class="menu-toggle" type="button" onclick="document.body.classList.toggle('menu-open')">Menu</button>

      <nav class="main-menu">
        <a href="dashboard.php"><?php echo h($menuHome); ?></a>
        <a href="directory.php"><?php echo h($menuDirectory); ?></a>
        <a href="rotation.php"><?php echo h($menuRotation); ?></a>
        <a href="prayer.php"><?php echo h($menuPrayer); ?></a>
        <a href="assignments.php"><?php echo h($menuAssignments); ?></a>
        <?php if ($isAdmin): ?>
          <a href="admin.php"><?php echo h($menuAdmin); ?></a>
        <?php endif; ?>
        <a href="profile.php"><?php echo h($menuProfile); ?></a>
        <a href="logout.php"><?php echo h($menuLogout); ?></a>
      </nav>

      <div class="access-pill">
        <?php echo h($username); ?> <span>• <?php echo h(access_label($userAccessLevel)); ?></span>
      </div>
    <?php endif; ?>
  </div>
</header>
