<?php
require_once '../includes/config.php';
requireAdmin();

$msg = '';
$msgType = 'success';

// ── List of all student-facing pages (key => label) ──────────────────
// key eka header.php eke renderHeader('Title', 'KEY') widihatama match wenna oni
$pages = [
    'dashboard'    => 'Dashboard',
    'subjects'     => 'Subjects',
    'tasks'        => 'Tasks',
    'notes'        => 'Notes & Flashcards',
    'goals'        => 'Goals',
    'marks'        => 'Marks & Results',
    'timetable'    => 'Timetable',
    'reminders'    => 'Reminders',
    'class-hours'  => 'Class Hours',
    'study-log'    => 'Study Log',
    'past-papers'  => 'Past Papers',
    'resources'    => 'Study Resources',
    'progress'     => 'Progress',
    'analysis'     => 'Analysis',
    'ai-analysis'  => 'AI Analysis',
    'ai-tips'      => 'AI Tips',
    'heatmap'      => 'Study Heatmap',
    'leaderboard'  => 'Leaderboard',
    'report'       => 'Report',
    'chat'         => 'Chat',
    'campus'       => 'Campus Explorer',
    'music'        => 'Music Player',
    'achievements' => 'Achievements',
    'notifications'=> 'Notifications',
    'profile'      => 'Profile',
    'settings'     => 'Settings',
];

// Make sure the table exists (in case the SQL migration wasn't run manually)
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS page_availability (
        id INT AUTO_INCREMENT PRIMARY KEY,
        page_key VARCHAR(50) NOT NULL,
        page_label VARCHAR(100) NOT NULL,
        is_unavailable TINYINT(1) NOT NULL DEFAULT 0,
        message VARCHAR(255) DEFAULT NULL,
        updated_by INT DEFAULT NULL,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_page_key (page_key)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
} catch (Exception $e) { /* ignore, will surface below if truly broken */ }

// ── Handle POST ────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'toggle_page') {
        $key = sanitize($_POST['page_key'] ?? '');
        if (isset($pages[$key])) {
            $current = $pdo->prepare("SELECT is_unavailable FROM page_availability WHERE page_key = ?");
            $current->execute([$key]);
            $cur = $current->fetchColumn();
            $new = ($cur === '1' || $cur === 1) ? 0 : 1;
            $stmt = $pdo->prepare("INSERT INTO page_availability (page_key, page_label, is_unavailable)
                VALUES (?, ?, ?)
                ON DUPLICATE KEY UPDATE is_unavailable = ?, updated_by = ?, updated_at = NOW()");
            $stmt->execute([$key, $pages[$key], $new, $new, $_SESSION['admin_id'] ?? null]);
            $msg = $new === 1
                ? "🚧 \"{$pages[$key]}\" marked as Unavailable. Students will see the popup."
                : "✅ \"{$pages[$key]}\" is Available again.";
        }
    }

    if ($action === 'save_message') {
        $key = sanitize($_POST['page_key'] ?? '');
        $message = sanitize($_POST['message'] ?? '');
        if (isset($pages[$key])) {
            $stmt = $pdo->prepare("INSERT INTO page_availability (page_key, page_label, is_unavailable, message)
                VALUES (?, ?, 0, ?)
                ON DUPLICATE KEY UPDATE message = ?, updated_by = ?, updated_at = NOW()");
            $stmt->execute([$key, $pages[$key], $message, $message, $_SESSION['admin_id'] ?? null]);
            $msg = "💬 Message saved for \"{$pages[$key]}\".";
        }
    }

    if ($action === 'disable_all') {
        $pdo->exec("UPDATE page_availability SET is_unavailable = 0");
        $msg = '✅ All pages set back to Available.';
    }
}

// ── Load current status for all pages ─────────────────────────────
$rows = $pdo->query("SELECT page_key, is_unavailable, message FROM page_availability")->fetchAll(PDO::FETCH_ASSOC);
$status = [];
foreach ($rows as $r) {
    $status[$r['page_key']] = $r;
}

require_once 'includes/header.php';
renderAdminHeader('Page Control', 'page-control');
?>
<style>
.pc-intro { color:var(--text-muted); font-size:14px; margin-bottom:18px; max-width:720px; line-height:1.6; }
.pc-grid { display:grid; grid-template-columns:repeat(auto-fill, minmax(300px,1fr)); gap:14px; }
.pc-card { background:var(--surface); border:1px solid var(--border); border-radius:12px; padding:16px 18px; }
.pc-card.is-off { border-color:rgba(239,68,68,0.4); background:rgba(239,68,68,0.05); }
.pc-top { display:flex; align-items:center; justify-content:space-between; margin-bottom:8px; }
.pc-name { font-size:14px; font-weight:600; color:var(--text-primary); }
.pc-key { font-size:11px; color:var(--text-muted); margin-top:2px; }
.badge-on { background:rgba(16,185,129,0.15); color:#10b981; padding:3px 10px; border-radius:12px; font-size:11px; font-weight:600; white-space:nowrap; }
.badge-off { background:rgba(239,68,68,0.15); color:#ef4444; padding:3px 10px; border-radius:12px; font-size:11px; font-weight:600; white-space:nowrap; }
.pc-msg-row { display:flex; gap:8px; margin-top:10px; }
.pc-msg-row input { flex:1; background:var(--bg); border:1px solid var(--border); border-radius:8px; padding:7px 10px; color:var(--text-primary); font-size:12px; }
.pc-btn-row { display:flex; gap:8px; margin-top:10px; }
.pc-toggle-btn { flex:1; border:none; border-radius:8px; padding:8px 10px; font-size:12px; font-weight:600; cursor:pointer; }
.pc-toggle-btn.mark-off { background:rgba(239,68,68,0.15); color:#ef4444; }
.pc-toggle-btn.mark-on { background:rgba(16,185,129,0.15); color:#10b981; }
.pc-save-btn { background:rgba(99,102,241,0.15); color:#818cf8; border:none; border-radius:8px; padding:7px 12px; font-size:12px; font-weight:600; cursor:pointer; }
.alert-msg { padding:10px 16px; border-radius:8px; margin-bottom:16px; font-size:14px; }
.alert-success { background:rgba(16,185,129,0.1); border:1px solid rgba(16,185,129,0.3); color:#10b981; }
</style>

<?php if($msg): ?>
<div class="alert-msg alert-<?= $msgType === 'error' ? 'error' : 'success' ?>"><?= htmlspecialchars($msg) ?></div>
<?php endif; ?>

<p class="pc-intro">
  Mark any student-facing page as <strong>Unavailable</strong> to show a "Currently Unavailable" popup to students
  when they open it (admins always keep access). Optionally set a custom message per page.
</p>

<form method="POST" style="margin-bottom:18px">
  <input type="hidden" name="action" value="disable_all">
  <button class="btn btn-secondary" type="submit" onclick="return confirm('Set ALL pages back to Available?')">✅ Set All Pages Available</button>
</form>

<div class="pc-grid">
<?php foreach ($pages as $key => $label):
    $isOff = isset($status[$key]) && (int)$status[$key]['is_unavailable'] === 1;
    $message = $status[$key]['message'] ?? '';
?>
  <div class="pc-card <?= $isOff ? 'is-off' : '' ?>">
    <div class="pc-top">
      <div>
        <div class="pc-name"><?= htmlspecialchars($label) ?></div>
        <div class="pc-key"><?= htmlspecialchars($key) ?></div>
      </div>
      <span class="<?= $isOff ? 'badge-off' : 'badge-on' ?>"><?= $isOff ? 'UNAVAILABLE' : 'AVAILABLE' ?></span>
    </div>

    <form method="POST">
      <input type="hidden" name="action" value="toggle_page">
      <input type="hidden" name="page_key" value="<?= htmlspecialchars($key) ?>">
      <div class="pc-btn-row">
        <button class="pc-toggle-btn <?= $isOff ? 'mark-on' : 'mark-off' ?>" type="submit">
          <?= $isOff ? '✅ Mark Available' : '🚧 Mark Unavailable' ?>
        </button>
      </div>
    </form>

    <form method="POST">
      <input type="hidden" name="action" value="save_message">
      <input type="hidden" name="page_key" value="<?= htmlspecialchars($key) ?>">
      <div class="pc-msg-row">
        <input type="text" name="message" maxlength="255" placeholder="Custom popup message (optional)" value="<?= htmlspecialchars($message) ?>">
        <button class="pc-save-btn" type="submit">💾</button>
      </div>
    </form>
  </div>
<?php endforeach; ?>
</div>

<?php require_once 'includes/footer.php'; renderAdminFooter(); ?>
