<?php
session_start();
require_once __DIR__ . '/../includes/auth_paths.php';

$role = $_SESSION['role'] ?? 'guest';
$username = $_SESSION['username'] ?? 'Admin';
$permissions = $_SESSION['permissions'] ?? [];

if (!in_array($role, ['master', 'admin', 'viewer', 'dj'], true)) {
  header('Location: /login/index.php');
  exit;
}

function ah_dashboard_access(string $role, array $permissions, string $permKey = ''): string {
  if ($role === 'master' || $role === 'admin') return 'full';
  if ($role === 'dj') $role = 'viewer';
  if ($permKey !== '' && isset($permissions[$permKey])) return 'full';
  return 'denied';
}

$cards = [
  ['href'=>'/admin/pages.php','title'=>'Page Builder','desc'=>'Create custom pages with hero sections, CTA buttons and preview blocks.','emoji'=>'🧩','perm'=>'pages'],
  ['href'=>'/admin/navigation.php','title'=>'Navigation','desc'=>'Add links and control the menu structure used by the site builder.','emoji'=>'🧭','perm'=>'navigation'],
  ['href'=>'/admin/news.php','title'=>'Feature News','desc'=>'Create featured news posts with tags, images and homepage-ready stories.','emoji'=>'📰','perm'=>'news'],
  ['href'=>'/admin/events.php','title'=>'Events','desc'=>'Update promotions, giveaways and special station events.','emoji'=>'🎉','perm'=>'events'],
  ['href'=>'/admin/top50.php','title'=>'Top 50','desc'=>'Manage your chart page and station ranking content.','emoji'=>'🎵','perm'=>'top50'],
  ['href'=>'/admin/about.php','title'=>'About Page','desc'=>'Fine tune the station bio and featured front-page copy.','emoji'=>'🌄','perm'=>'about'],
  ['href'=>'/admin/schedule.php','title'=>'Schedule','desc'=>'Refresh the DJ roster and on-air schedule blocks.','emoji'=>'🗓️','perm'=>'schedule'],
  ['href'=>'/admin/djs.php','title'=>'DJs','desc'=>'Manage presenter profiles, show details and artwork.','emoji'=>'🎚️','perm'=>'djs'],
  ['href'=>'/admin/friends.php','title'=>'Friends','desc'=>'Update partner links, sponsor cards and station friends.','emoji'=>'🤝','perm'=>'friends'],
  ['href'=>'/admin/fans.php','title'=>'Fans & Community','desc'=>'Manage fan shoutouts, listener engagement and community content.','emoji'=>'💙','perm'=>'fans'],
  ['href'=>'/admin/requests.php','title'=>'Song Requests','desc'=>'Check incoming requests and keep the listener queue flowing.','emoji'=>'📻','perm'=>'requests'],
  ['href'=>'/admin/comments.php','title'=>'Comments','desc'=>'Approve, reply, delete or clear all comments from one place.','emoji'=>'🗨️','perm'=>'comments'],
  ['href'=>'/admin/chat.php','title'=>'Live Chat','desc'=>'Moderate website chat and keep the station conversation tidy.','emoji'=>'💬','perm'=>'chat'],
  ['href'=>'/admin/player.php','title'=>'Popout Player','desc'=>'Control player visibility and stream-side player settings.','emoji'=>'🪟','perm'=>'player'],
  ['href'=>'/admin/poll.php','title'=>'Poll Manager','desc'=>'Create and update quick listener polls.','emoji'=>'📊','perm'=>'poll'],
  ['href'=>'/admin/contact.php','title'=>'Contact Inbox','desc'=>'Review messages sent in from the site and reply from your own workflow.','emoji'=>'✉️','perm'=>'contact'],
  ['href'=>'/admin/applications.php','title'=>'Join The Team','desc'=>'Read station applications and manage new talent submissions.','emoji'=>'🎙️','perm'=>'applications'],
  ['href'=>'/admin/media.php','title'=>'Media & Branding','desc'=>'Swap images, art and station visuals from one place.','emoji'=>'🖼️','perm'=>'media'],
  ['href'=>'/admin/radiostats.php','title'=>'Radio Stats','desc'=>'View stream and station stats from the built-in tools.','emoji'=>'📡','perm'=>'radiostats'],
  ['href'=>'/admin/westats.php','title'=>'Web Stats','desc'=>'Check web-side traffic and analytics integrations.','emoji'=>'📈','perm'=>'westats'],
  ['href'=>'/admin/backup.php','title'=>'Backup & Restore','desc'=>'Create and restore station backups safely.','emoji'=>'🗄️','perm'=>'backup'],
  ['href'=>'/admin/icecast_backup.php','title'=>'Icecast Backup','desc'=>'Open the backup Icecast server link from the admin dashboard.','emoji'=>'🔊','perm'=>'backup'],
  ['href'=>'/admin/hosting_tools.php','title'=>'Hosting Tools','desc'=>'Quick links and server-side helpers for station management.','emoji'=>'🛠️','perm'=>'westats'],
  ['href'=>'/admin/users.php','title'=>'User Manager','desc'=>'Create admins and DJs, reset passwords and control permissions.','emoji'=>'👥','perm'=>'users'],
];

foreach ($cards as &$card) {
  $card['access'] = ah_dashboard_access($role, is_array($permissions) ? $permissions : [], $card['perm']);
}
unset($card);

$config = ah_load_auth_config();
$users = ah_load_users();
$userCount = is_array($users) ? count($users) : 0;
$pageData = json_decode((string)@file_get_contents(__DIR__ . '/../data/pages.json'), true);
$pageCount = is_array($pageData) ? count($pageData) : 0;
$chatData = json_decode((string)@file_get_contents(__DIR__ . '/../data/chat.json'), true);
$chatCount = is_array($chatData) ? count($chatData) : 0;
$requestData = json_decode((string)@file_get_contents(__DIR__ . '/../data/requests.json'), true);
$requestCount = is_array($requestData) ? count($requestData) : 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Admin Dashboard | Almost Heaven Radio</title>
  <link rel="stylesheet" href="/css/style.css?v=2" />
  <link rel="stylesheet" href="/admin/assets/admin-v2.css?v=2" />
</head>
<body class="page-admin">

  <?php include('../header.php'); ?>
  <?php include('../menu.php'); ?>

  <main class="main-container admin-v2-shell">
    <div class="admin-v2-topbar">
      <div>
        <span class="admin-eyebrow">Almost Heaven Control Room</span>
        <h1 class="admin-title-glow">Welcome back, <?= htmlspecialchars($username) ?></h1>
        <p class="admin-lead">Almost Heaven keeps its own wording and style, now backed by the stronger shared station toolset with a richer admin look and a cleaner workflow.</p>
      </div>
      <div class="admin-chip-row">
        <span class="admin-chip">Role: <?= htmlspecialchars($role) ?></span>
        <a class="admin-btn ghost" href="/login/logout.php">Logout</a>
      </div>
    </div>

    <section class="admin-hero-banner">
      <div class="admin-hero-grid">
        <div class="admin-hero-copy">
          <span class="hero-mini">Mountain soul. Modern control.</span>
          <h2>Admin with more punch, less clutter.</h2>
          <p>Dead cards like the old auth tile are gone from the dashboard. This layout only shows the tools you actually need while you build out the live station.</p>
        </div>
        <div class="admin-hero-side">
          <div class="admin-stat-grid">
            <div class="admin-stat-card"><h3>Pages</h3><div class="admin-stat-value"><?= (int)$pageCount ?></div><div class="admin-stat-meta">Builder-ready pages</div></div>
            <div class="admin-stat-card"><h3>Users</h3><div class="admin-stat-value"><?= (int)$userCount ?></div><div class="admin-stat-meta">External auth accounts</div></div>
            <div class="admin-stat-card"><h3>Requests</h3><div class="admin-stat-value"><?= (int)$requestCount ?></div><div class="admin-stat-meta">Saved listener requests</div></div>
            <div class="admin-stat-card"><h3>Chat Items</h3><div class="admin-stat-value"><?= (int)$chatCount ?></div><div class="admin-stat-meta">Community messages stored</div></div>
          </div>
        </div>
      </div>
    </section>

    <section class="admin-card-panel" style="margin-bottom:18px;">
      <h3>Quick actions</h3>
      <div class="page-action-row">
        <a class="admin-btn" href="/admin/pages.php">Open Page Builder</a>
        <a class="admin-btn" href="/admin/users.php">Manage Users</a>
        <a class="admin-btn" href="/admin/schedule.php">Update Schedule</a>
        <a class="admin-btn" href="/admin/contact.php">View Contact Messages</a>
      </div>
    </section>

    <section class="admin-grid-v2">
      <?php foreach ($cards as $card): ?>
        <?php if ($card['access'] === 'full'): ?>
          <a href="<?= htmlspecialchars($card['href']) ?>" class="admin-card-link">
            <div>
              <div class="card-emoji"><?= $card['emoji'] ?></div>
              <div class="card-title"><?= htmlspecialchars($card['title']) ?></div>
              <div class="card-desc"><?= htmlspecialchars($card['desc']) ?></div>
            </div>
            <div class="card-foot">Open tool →</div>
          </a>
        <?php elseif ($card['access'] === 'view'): ?>
          <div class="admin-card-link" style="opacity:.7; cursor:not-allowed;">
            <div>
              <div class="card-emoji"><?= $card['emoji'] ?></div>
              <div class="card-title"><?= htmlspecialchars($card['title']) ?></div>
              <div class="card-desc"><?= htmlspecialchars($card['desc']) ?></div>
            </div>
            <div class="card-foot">View-only access</div>
          </div>
        <?php endif; ?>
      <?php endforeach; ?>
    </section>
  </main>

  <?php include('../footer.php'); ?>

</body>
</html>
