<?php
session_start();
require __DIR__ . '/auth.php';
$pageTitle = "Dashboard — Home Time Radio Radio";
require_once __DIR__ . '/../includes/content_store.php';
require_once __DIR__ . '/../includes/comments_lib.php';
include __DIR__ . '/includes/admin_header.php';
$baseDir = realpath(__DIR__ . '/..') ?: (__DIR__ . '/..');
$settings = smurf_read_json(__DIR__ . '/../data/settings.json', []);
$pages = smurf_read_json(__DIR__ . '/../data/pages.json', []);
$news = ht_load_news_items($baseDir);
$events = ht_load_event_items($baseDir);
$djs = smurf_read_json(__DIR__ . '/../data/djs.json', []);
$friends = smurf_read_json(__DIR__ . '/../data/friends.json', []);
$fans = smurf_read_json(__DIR__ . '/../data/fans.json', []);
$contactItems = smurf_parse_blocks(__DIR__ . '/../data/contact_messages.txt');
$appItems = smurf_parse_blocks(__DIR__ . '/../data/applications.txt');
$appMeta = smurf_read_json(__DIR__ . '/../data/application_status.json', []);
if (!is_array($appMeta)) $appMeta = [];
$poll = smurf_read_json(__DIR__ . '/../data/poll.json', ['question'=>'','options'=>[],'show_on_home'=>0]);
$chartState = smurf_read_json(__DIR__ . '/../data/top50_state.json', []);
$commentsBundle = ht_read_comments(__DIR__ . '/../data/comments.txt', __DIR__ . '/../data/comment_replies.json');
$commentItems = is_array($commentsBundle['items_newest'] ?? null) ? $commentsBundle['items_newest'] : [];
$pendingComments = 0;
foreach ($commentItems as $commentItem) { if (empty($commentItem['approved'])) $pendingComments++; }
$pendingApplications = 0;
foreach ($appItems as $item) {
  $key = md5((string)($item['_raw'] ?? json_encode($item)));
  $status = strtolower(trim((string)($appMeta[$key]['status'] ?? 'new')));
  if ($status === '' || $status === 'new') $pendingApplications++;
}
$featuredNews = null;
foreach ($news as $item) { if (!empty($item['published']) && !empty($item['featured_home'])) { $featuredNews = $item; break; } }
$featuredEvent = null;
foreach ($events as $item) { if (!empty($item['published']) && !empty($item['featured_home'])) { $featuredEvent = $item; break; } }
$pollActive = !empty($poll['show_on_home']) && trim((string)($poll['question'] ?? '')) !== '' && !empty($poll['options']) && is_array($poll['options']);
$pollSummary = $pollActive ? 'Live on homepage' : 'Off';
if ($pollActive) { $pollSummary .= ' — ' . trim((string)$poll['question']); }
$currentChartWeek = trim((string)($chartState['current_week_label'] ?? ''));
if ($currentChartWeek === '') $currentChartWeek = 'Current Weekly Chart';
$chatEnabled = !empty($settings['chat_enabled']);
$eventsNav = array_key_exists('events_show_in_nav',$settings) ? !empty($settings['events_show_in_nav']) : true;
$playerNav = !empty($settings['player_show_in_nav']);
$top50Nav = !empty($settings['top50_show_in_nav']);
function dashCard($href,$emoji,$title,$desc,$foot='Open tool'){ echo '<a class="admin-card-link" href="'.htmlspecialchars($href,ENT_QUOTES,'UTF-8').'"><div><div class="card-emoji">'.$emoji.'</div><div class="card-title">'.htmlspecialchars($title,ENT_QUOTES,'UTF-8').'</div><div class="card-desc">'.htmlspecialchars($desc,ENT_QUOTES,'UTF-8').'</div></div><div class="card-foot">'.htmlspecialchars($foot,ENT_QUOTES,'UTF-8').' →</div></a>'; }
function quickStatCard($label,$value,$meta=''){ echo '<div class="admin-stat-card"><h3>'.htmlspecialchars($label,ENT_QUOTES,'UTF-8').'</h3><div class="admin-stat-value">'.htmlspecialchars((string)$value,ENT_QUOTES,'UTF-8').'</div>'.($meta!==''?'<div class="admin-stat-meta">'.htmlspecialchars($meta,ENT_QUOTES,'UTF-8').'</div>':'').'</div>'; }
?>
<section class="admin-hero-grid">
  <section class="admin-card-panel">
    <h3>Welcome back</h3>
    <p class="admin-stat-meta">This upgraded Home Time admin keeps your current tools but makes them easier to find and manage. Use the sidebar to jump between content, community and system tools.</p>
    <div class="admin-stat-grid">
      <div class="admin-stat-card">
        <h3>Custom Pages</h3>
        <div class="admin-stat-value"><?= is_array($pages) ? count($pages) : 0 ?></div>
        <div class="admin-stat-meta">Published and draft pages managed in the builder.</div>
      </div>
      <div class="admin-stat-card">
        <h3>News Items</h3>
        <div class="admin-stat-value"><?= is_array($news) ? count($news) : 0 ?></div>
        <div class="admin-stat-meta">Stories, featured posts and homepage items.</div>
      </div>
      <div class="admin-stat-card">
        <h3>DJs</h3>
        <div class="admin-stat-value"><?= is_array($djs) ? count($djs) : 0 ?></div>
        <div class="admin-stat-meta">Profiles, show details and live highlights.</div>
      </div>
      <div class="admin-stat-card">
        <h3>Community</h3>
        <div class="admin-stat-value"><?= (is_array($friends)?count($friends):0) + (is_array($fans)?count($fans):0) ?></div>
        <div class="admin-stat-meta">Friends + fans entries currently on the site.</div>
      </div>
    </div>
  </section>
  <section class="admin-card-panel">
    <h3>Live toggles snapshot</h3>
    <table class="admin-table">
      <thead><tr><th>Module</th><th>Status</th></tr></thead>
      <tbody>
        <tr><td>Live Chat in Navigation</td><td><?= $chatEnabled ? 'Enabled' : 'Hidden' ?></td></tr>
        <tr><td>Events Link</td><td><?= $eventsNav ? 'Shown' : 'Hidden' ?></td></tr>
        <tr><td>Charts Link</td><td><?= $top50Nav ? 'Shown' : 'Hidden' ?></td></tr>
        <tr><td>Popout Player Link</td><td><?= $playerNav ? 'Shown' : 'Hidden' ?></td></tr>
      </tbody>
    </table>
  </section>
</section>

<section class="content-card mt-3">
  <h2 class="admin-title">Quick Stats</h2>
  <div class="admin-stat-grid">
    <?php quickStatCard('Pending Comments', (string)$pendingComments, 'Comments waiting for approval'); ?>
    <?php quickStatCard('Pending Applications', (string)$pendingApplications, 'Join the Team applications still marked new'); ?>
    <?php quickStatCard('Featured News', $featuredNews ? (string)($featuredNews['title'] ?? 'Set') : 'None set', $featuredNews ? 'Currently pinned to homepage' : 'No homepage featured news'); ?>
    <?php quickStatCard('Featured Event', $featuredEvent ? (string)($featuredEvent['title'] ?? 'Set') : 'None set', $featuredEvent ? 'Currently pinned to homepage' : 'No homepage featured event'); ?>
    <?php quickStatCard('Current Poll Status', $pollActive ? 'Active' : 'Off', $pollSummary); ?>
    <?php quickStatCard('Current Chart Week', $currentChartWeek, !empty($chartState['last_reset_at']) ? ('Started ' . (string)$chartState['last_reset_at']) : 'Chart week ready'); ?>
  </div>
</section>

<section class="content-card mt-3">
  <h2 class="admin-title">Content Studio</h2>
  <div class="admin-grid-v2">
    <?php dashCard('/admin/pages.php','🧩','Page Builder','Create custom pages with hero images, summaries, CTA buttons and preview.'); ?>
    <?php dashCard('/admin/news.php','📰','News','Post updates, feature homepage stories and manage article images.'); ?>
    <?php dashCard('/admin/events.php','🎉','Events','Build promotions, contests and event landing pages.'); ?>
    <?php dashCard('/admin/top50.php','🎵','Charts','Manage your weekly charts and stream-fed ranking data.'); ?>
    <?php dashCard('/admin/schedule.php','📅','Schedule','Visual schedule editor powering live DJ automation.'); ?>
    <?php dashCard('/admin/about.php','ℹ️','About','Edit your station bio and front-page story.'); ?>
    <?php dashCard('/admin/media.php','🖼️','Media Library','Upload artwork and copy image paths for reuse.'); ?>
    <?php dashCard('/admin/navigation.php','🧭','Navigation','Add extra external links and tidy the navigation.'); ?>
  </div>
</section>

<section class="content-card mt-3">
  <h2 class="admin-title">Community & Radio Tools</h2>
  <div class="admin-grid-v2">
    <?php dashCard('/admin/djs.php','🎙️','DJs','Manage presenter profiles, images and bios.'); ?>
    <?php dashCard('/admin/friends.php','🤝','Friends','Maintain partner/sponsor style cards with images and links.'); ?>
    <?php dashCard('/admin/fans.php','⭐','Fans','Highlight supporters, descriptions and top-fan badges.'); ?>
    <?php dashCard('/admin/contact.php','📨','Contact Messages','Review and clear messages from the public contact form.'); ?>
    <?php dashCard('/admin/applications.php','📝','Join the Team','Review presenter and volunteer applications sent from the site.'); ?>
    <?php dashCard('/admin/requests.php','🎶','Requests','Track request workflow, statuses and DJ notes.'); ?>
    <?php dashCard('/admin/comments.php','💬','Comments','Approve, reply and moderate homepage discussion.'); ?>
    <?php dashCard('/admin/chat.php','🗨️','Live Chat','Moderate room messages, toggles and DJ-side posting.'); ?>
    <?php dashCard('/admin/player.php','🪟','Popout Player','Control player visibility and stream settings.'); ?>
    <?php dashCard('/admin/radiostats.php','📡','Radio Stats','Monitor Icecast stats, now playing and listeners.'); ?>
  </div>
</section>

<section class="content-card mt-3">
  <h2 class="admin-title">System & Safety</h2>
  <div class="admin-grid-v2">
    <?php dashCard('/admin/users.php','👤','User Management','Edit roles, passwords and page permissions from checkbox grants.'); ?>
    <?php dashCard('/admin/backup.php','🧰','Backup / Restore','Download data backups or restore from zip.'); ?>
    <?php dashCard('/admin/poll.php','📊','Poll Manager','Control the homepage poll, options and vote reset tools.'); ?>
    <?php dashCard('/admin/westats.php','📈','Web Stats','Review Cloudflare and local traffic reporting.'); ?>
    <?php dashCard('http://cr3.broadcasturself.com:65001/status.xsl','📶','Icecast Status','Open the broadcaster control status page in a new tab.','Open external'); ?>
  </div>
</section>
<div class="admin-dashboard-footer-spacer" style="height:6px;"></div>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
