<?php

/**

 * EduTrack Blog — Admin dashboard.

 * Tabs: Posts (CRUD) | Topics (CRUD) | Generate | Log

 */



require_once __DIR__ . '/config.php';

require_once __DIR__ . '/includes/db.php';



session_start();



// ── Auth ──────────────────────────────────────────────────────────────────────

$error = '';

if (isset($_POST['admin_password'])) {

    if ($_POST['admin_password'] === BLOG_ADMIN_PASSWORD) {

        $_SESSION['blog_admin'] = true;

    } else {

        $error = 'Incorrect password.';

    }

}

if (isset($_GET['logout'])) {

    unset($_SESSION['blog_admin']);

    header('Location: admin.php');

    exit;

}

$authed = !empty($_SESSION['blog_admin']);



// ── API: fetch single post for edit modal ─────────────────────────────────────

if ($authed && ($_GET['api'] ?? '') === 'post' && isset($_GET['id'])) {

    $id = (int) $_GET['id'];

    $st = blog_db()->prepare(

        'SELECT id, title, meta_description, category, status, tags, excerpt, html_content

         FROM blog_posts WHERE id = ? LIMIT 1'

    );

    $st->bind_param('i', $id);

    $st->execute();

    $row = $st->get_result()->fetch_assoc();

    $st->close();

    header('Content-Type: application/json');

    echo json_encode($row ?: ['error' => 'Not found']);

    exit;

}



// ── Actions (authenticated) ────────────────────────────────────────────────────

$flash = '';

if ($authed && isset($_POST['action'])) {

    require_once __DIR__ . '/includes/generator.php';

    $action = $_POST['action'];



    // ── Generate post (auto-pick or specific topic) ───────────────────────────

    if ($action === 'generate') {

        $topic_id = isset($_POST['topic_id']) && (int) $_POST['topic_id'] > 0

            ? (int) $_POST['topic_id']

            : null;

        try {

            $slug  = generate_and_save_post($topic_id);

            $flash = "success|Post published: <a href=\"post.php?slug=" . urlencode($slug) . "\" target=\"_blank\"><strong>{$slug}</strong></a>";

        } catch (Throwable $e) {

            $flash = "danger|Generation failed: " . htmlspecialchars($e->getMessage());

        }

    }



    // ── Edit post ─────────────────────────────────────────────────────────────

    elseif ($action === 'edit_post' && isset($_POST['post_id'])) {

        $pid      = (int) $_POST['post_id'];

        $title    = trim((string) ($_POST['title']            ?? ''));

        $meta     = trim((string) ($_POST['meta_description'] ?? ''));

        $cat      = trim((string) ($_POST['category']         ?? ''));

        $tags     = trim((string) ($_POST['tags']             ?? ''));

        $excerpt  = trim((string) ($_POST['excerpt']          ?? ''));

        $html     = (string) ($_POST['html_content'] ?? '');

        $status   = in_array($_POST['status'] ?? '', ['published','draft','archived'])

                    ? $_POST['status'] : 'draft';



        if ($title === '') {

            $flash = "danger|Title cannot be empty.";

        } else {

            $st = blog_db()->prepare(

                'UPDATE blog_posts

                 SET title=?, meta_description=?, category=?, tags=?, excerpt=?,

                     html_content=?, status=?, updated_at=NOW()

                 WHERE id=?'

            );

            $st->bind_param('sssssssi', $title, $meta, $cat, $tags, $excerpt, $html, $status, $pid);

            $st->execute();

            $st->close();

            $flash = "success|Post #{$pid} updated successfully.";

        }

    }



    // ── Set status ────────────────────────────────────────────────────────────

    elseif ($action === 'set_status' && isset($_POST['post_id'], $_POST['status'])) {

        $pid    = (int) $_POST['post_id'];

        $status = in_array($_POST['status'], ['published','draft','archived']) ? $_POST['status'] : 'draft';

        $st     = blog_db()->prepare('UPDATE blog_posts SET status=? WHERE id=?');

        $st->bind_param('si', $status, $pid);

        $st->execute();

        $st->close();

        $flash = "success|Post #{$pid} set to <strong>{$status}</strong>.";

    }



    // ── Delete post ───────────────────────────────────────────────────────────

    elseif ($action === 'delete' && isset($_POST['post_id'])) {

        $pid = (int) $_POST['post_id'];

        $st  = blog_db()->prepare('DELETE FROM blog_posts WHERE id=?');

        $st->bind_param('i', $pid);

        $st->execute();

        $st->close();

        $flash = "warning|Post #{$pid} deleted.";

    }



    // ── Add topic ─────────────────────────────────────────────────────────────

    elseif ($action === 'add_topic') {

        $text     = trim((string) ($_POST['topic_text'] ?? ''));

        $max_uses = max(1, (int) ($_POST['max_uses'] ?? 2));

        if ($text === '') {

            $flash = "danger|Topic text cannot be empty.";

        } else {

            $st = blog_db()->prepare(

                'INSERT INTO blog_topics (topic_text, max_uses) VALUES (?, ?)'

            );

            $st->bind_param('si', $text, $max_uses);

            $st->execute();

            $new_id = blog_db()->insert_id;

            $st->close();

            $flash = "success|Topic #{$new_id} added.";

        }

    }



    // ── Delete topic ──────────────────────────────────────────────────────────

    elseif ($action === 'delete_topic' && isset($_POST['topic_id'])) {

        $tid = (int) $_POST['topic_id'];

        $st  = blog_db()->prepare('DELETE FROM blog_topics WHERE id=?');

        $st->bind_param('i', $tid);

        $st->execute();

        $st->close();

        $flash = "warning|Topic #{$tid} deleted.";

    }



    // ── Toggle topic active ───────────────────────────────────────────────────

    elseif ($action === 'toggle_topic' && isset($_POST['topic_id'])) {

        $tid = (int) $_POST['topic_id'];

        $st  = blog_db()->prepare(

            'UPDATE blog_topics SET is_active = 1 - is_active WHERE id=?'

        );

        $st->bind_param('i', $tid);

        $st->execute();

        $st->close();

        $flash = "success|Topic #{$tid} toggled.";

    }



    // ── Reset topic use counts ────────────────────────────────────────────────

    elseif ($action === 'reset_counts') {

        blog_db()->query("UPDATE blog_topics SET use_count = 0");

        $flash = "success|All topic use counts reset to 0.";

    }

}



// ── Fetch data (authenticated) ─────────────────────────────────────────────────

$posts  = [];

$topics = [];

if ($authed) {

    $conn = blog_db();



    $res = $conn->query(

        'SELECT id, title, slug, category, status, view_count, published_at, reading_time_minutes

         FROM blog_posts ORDER BY created_at DESC LIMIT 100'

    );

    if ($res) $posts = $res->fetch_all(MYSQLI_ASSOC);



    $total_pub   = (int) ($conn->query('SELECT COUNT(*) c FROM blog_posts WHERE status="published"')->fetch_assoc()['c'] ?? 0);

    $total_draft = (int) ($conn->query('SELECT COUNT(*) c FROM blog_posts WHERE status="draft"')->fetch_assoc()['c'] ?? 0);

    $total_views = (int) ($conn->query('SELECT COALESCE(SUM(view_count),0) c FROM blog_posts WHERE status="published"')->fetch_assoc()['c'] ?? 0);



    $res = $conn->query(

        'SELECT id, topic_text, use_count, max_uses, is_active, last_used_at, created_at

         FROM blog_topics ORDER BY id ASC'

    );

    if ($res) $topics = $res->fetch_all(MYSQLI_ASSOC);



    $available_topics = array_filter($topics, fn($t) => $t['is_active'] && $t['use_count'] < $t['max_uses']);



    $log_lines = [];

    $log_file  = __DIR__ . '/logs/cron.log';

    if (file_exists($log_file)) {

        $log_lines = array_slice(file($log_file, FILE_IGNORE_NEW_LINES), -50);

    }

}



[$flash_type, $flash_msg] = $flash ? explode('|', $flash, 2) : ['', ''];



// Which tab to show after redirect (persist via query param)

$active_tab = in_array($_GET['tab'] ?? '', ['posts','topics','generate','log'])

    ? $_GET['tab'] : 'posts';

?>

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Blog Admin — EduTrack</title>

  <meta name="robots" content="noindex,nofollow">

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

  <link rel="stylesheet" href="assets/blog.css">

  <style>

    .topic-text { max-width: 480px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

    .use-badge  { font-size: .75rem; font-weight: 600; }

    #editHtmlContent { font-family: monospace; font-size: .8rem; }

    .nav-tabs .nav-link { color: #6b7280; }

    .nav-tabs .nav-link.active { color: #1e1b4b; font-weight: 600; }

  </style>

</head>

<body class="bg-light">



<?php if (!$authed): ?>

<!-- ── LOGIN ──────────────────────────────────────────────────────────────── -->

<div class="min-vh-100 d-flex align-items-center justify-content-center">

  <div class="card shadow-sm" style="width:360px;border-radius:14px;">

    <div class="card-body p-4">

      <div class="text-center mb-4">

        <div style="width:48px;height:48px;border-radius:12px;background:linear-gradient(135deg,#6366f1,#8b5cf6);display:inline-flex;align-items:center;justify-content:center;">

          <i class="fas fa-pen-nib text-white"></i>

        </div>

        <h5 class="fw-bold mt-3 mb-1">Blog Admin</h5>

        <p class="text-muted small">EduTrack · ORIC Network</p>

      </div>

      <?php if ($error): ?>

        <div class="alert alert-danger py-2 small"><?= htmlspecialchars($error) ?></div>

      <?php endif ?>

      <form method="post">

        <div class="mb-3">

          <input type="password" name="admin_password" class="form-control" placeholder="Admin password" autofocus required>

        </div>

        <button type="submit" class="btn btn-primary w-100">Sign In</button>

      </form>

    </div>

  </div>

</div>



<?php else: ?>

<!-- ── DASHBOARD ──────────────────────────────────────────────────────────── -->

<nav class="navbar navbar-dark" style="background:linear-gradient(135deg,#1e1b4b,#312e81);">

  <div class="container-fluid">

    <span class="navbar-brand"><i class="fas fa-pen-nib me-2"></i>Blog Admin</span>

    <div class="d-flex gap-2">

      <a href="<?= BLOG_BASE_URL ?>/index.php" class="btn btn-outline-light btn-sm" target="_blank">

        <i class="fas fa-external-link-alt me-1"></i>View Blog

      </a>

      <a href="admin.php?logout=1" class="btn btn-outline-light btn-sm">

        <i class="fas fa-sign-out-alt me-1"></i>Logout

      </a>

    </div>

  </div>

</nav>



<div class="container py-4">



  <?php if ($flash_msg): ?>

    <div class="alert alert-<?= $flash_type ?> alert-dismissible fade show" role="alert">

      <?= $flash_msg ?>

      <button type="button" class="btn-close" data-bs-dismiss="alert"></button>

    </div>

  <?php endif ?>



  <!-- Stats row -->

  <div class="row g-3 mb-4">

    <div class="col-sm-3">

      <div class="card border-0 shadow-sm text-center py-3">

        <div class="fs-2 fw-bold text-primary"><?= $total_pub ?></div>

        <div class="small text-muted">Published</div>

      </div>

    </div>

    <div class="col-sm-3">

      <div class="card border-0 shadow-sm text-center py-3">

        <div class="fs-2 fw-bold text-warning"><?= $total_draft ?></div>

        <div class="small text-muted">Drafts</div>

      </div>

    </div>

    <div class="col-sm-3">

      <div class="card border-0 shadow-sm text-center py-3">

        <div class="fs-2 fw-bold text-success"><?= number_format($total_views) ?></div>

        <div class="small text-muted">Total Views</div>

      </div>

    </div>

    <div class="col-sm-3">

      <div class="card border-0 shadow-sm text-center py-3">

        <div class="fs-2 fw-bold text-info"><?= count($available_topics) ?> / <?= count($topics) ?></div>

        <div class="small text-muted">Topics Available</div>

      </div>

    </div>

  </div>



  <!-- Tabs -->

  <ul class="nav nav-tabs mb-4" id="adminTabs">

    <li class="nav-item">

      <a class="nav-link <?= $active_tab === 'posts'    ? 'active' : '' ?>" href="?tab=posts">

        <i class="fas fa-newspaper me-1"></i>Posts <span class="badge bg-secondary ms-1"><?= count($posts) ?></span>

      </a>

    </li>

    <li class="nav-item">

      <a class="nav-link <?= $active_tab === 'topics'   ? 'active' : '' ?>" href="?tab=topics">

        <i class="fas fa-tags me-1"></i>Topics <span class="badge bg-secondary ms-1"><?= count($topics) ?></span>

      </a>

    </li>

    <li class="nav-item">

      <a class="nav-link <?= $active_tab === 'generate' ? 'active' : '' ?>" href="?tab=generate">

        <i class="fas fa-robot me-1"></i>Generate

      </a>

    </li>

    <li class="nav-item">

      <a class="nav-link <?= $active_tab === 'log'      ? 'active' : '' ?>" href="?tab=log">

        <i class="fas fa-terminal me-1"></i>Log

      </a>

    </li>

  </ul>



  <!-- ════════════════════ TAB: POSTS ════════════════════ -->

  <?php if ($active_tab === 'posts'): ?>

  <div class="card border-0 shadow-sm">

    <div class="card-header bg-white py-3 d-flex justify-content-between align-items-center">

      <span class="fw-semibold">All Posts</span>

      <a href="?tab=generate" class="btn btn-primary btn-sm">

        <i class="fas fa-plus me-1"></i>Generate New

      </a>

    </div>

    <div class="table-responsive">

      <table class="table table-hover align-middle mb-0">

        <thead class="table-light">

          <tr>

            <th style="width:40px">#</th>

            <th>Title</th>

            <th>Category</th>

            <th>Status</th>

            <th>Views</th>

            <th>Published</th>

            <th>Actions</th>

          </tr>

        </thead>

        <tbody>

        <?php if (empty($posts)): ?>

          <tr><td colspan="7" class="text-center text-muted py-4">No posts yet. Go to Generate tab to create your first post.</td></tr>

        <?php endif ?>

        <?php foreach ($posts as $p): ?>

          <tr>

            <td class="text-muted small"><?= $p['id'] ?></td>

            <td>

              <a href="<?= BLOG_BASE_URL ?>/post.php?slug=<?= urlencode($p['slug']) ?>" target="_blank" class="fw-semibold text-decoration-none">

                <?= htmlspecialchars(mb_strimwidth($p['title'], 0, 65, '…')) ?>

              </a>

              <div class="text-muted small font-monospace"><?= htmlspecialchars($p['slug']) ?></div>

            </td>

            <td><span class="badge bg-secondary"><?= htmlspecialchars($p['category'] ?? '') ?></span></td>

            <td>

              <?php $sc = ['published'=>'success','draft'=>'warning','archived'=>'secondary'][$p['status']] ?? 'secondary' ?>

              <span class="badge bg-<?= $sc ?>"><?= $p['status'] ?></span>

            </td>

            <td><?= number_format((int) $p['view_count']) ?></td>

            <td class="small text-muted"><?= $p['published_at'] ? date('d M Y', strtotime($p['published_at'])) : '—' ?></td>

            <td>

              <div class="d-flex gap-1">

                <!-- Edit -->

                <button type="button" class="btn btn-outline-primary btn-sm"

                        onclick="openEditModal(<?= $p['id'] ?>)" title="Edit post">

                  <i class="fas fa-pen"></i>

                </button>

                <!-- Toggle status -->

                <form method="post" class="d-inline" action="?tab=posts">

                  <input type="hidden" name="action"  value="set_status">

                  <input type="hidden" name="post_id" value="<?= $p['id'] ?>">

                  <input type="hidden" name="status"  value="<?= $p['status'] === 'published' ? 'draft' : 'published' ?>">

                  <button type="submit" class="btn btn-outline-secondary btn-sm"

                          title="<?= $p['status'] === 'published' ? 'Unpublish' : 'Publish' ?>">

                    <i class="fas <?= $p['status'] === 'published' ? 'fa-eye-slash' : 'fa-eye' ?>"></i>

                  </button>

                </form>

                <!-- Delete -->

                <form method="post" class="d-inline" action="?tab=posts"

                      onsubmit="return confirm('Permanently delete this post?')">

                  <input type="hidden" name="action"  value="delete">

                  <input type="hidden" name="post_id" value="<?= $p['id'] ?>">

                  <button type="submit" class="btn btn-outline-danger btn-sm" title="Delete">

                    <i class="fas fa-trash"></i>

                  </button>

                </form>

              </div>

            </td>

          </tr>

        <?php endforeach ?>

        </tbody>

      </table>

    </div>

  </div>

  <?php endif ?>



  <!-- ════════════════════ TAB: TOPICS ════════════════════ -->

  <?php if ($active_tab === 'topics'): ?>

  <div class="row g-4">



    <!-- Topic list -->

    <div class="col-12">

      <div class="card border-0 shadow-sm">

        <div class="card-header bg-white py-3 d-flex justify-content-between align-items-center">

          <span class="fw-semibold">All Topics</span>

          <form method="post" action="?tab=topics"

                onsubmit="return confirm('Reset all topic use counts to 0?')">

            <input type="hidden" name="action" value="reset_counts">

            <button type="submit" class="btn btn-outline-secondary btn-sm">

              <i class="fas fa-undo me-1"></i>Reset All Counts

            </button>

          </form>

        </div>

        <div class="table-responsive">

          <table class="table table-hover align-middle mb-0 small">

            <thead class="table-light">

              <tr>

                <th style="width:40px">#</th>

                <th>Topic</th>

                <th>Uses</th>

                <th>Status</th>

                <th>Last Used</th>

                <th>Actions</th>

              </tr>

            </thead>

            <tbody>

            <?php if (empty($topics)): ?>

              <tr><td colspan="6" class="text-center text-muted py-4">

                No topics yet. Add one below or <a href="setup.php?token=<?= BLOG_CRON_TOKEN ?>">run setup</a> to seed from defaults.

              </td></tr>

            <?php endif ?>

            <?php foreach ($topics as $t):

                $uses_pct = $t['max_uses'] > 0 ? round(($t['use_count'] / $t['max_uses']) * 100) : 100;

                $uses_cls = $t['use_count'] >= $t['max_uses'] ? 'danger' : ($uses_pct >= 50 ? 'warning' : 'success');

            ?>

              <tr class="<?= !$t['is_active'] ? 'table-secondary opacity-50' : '' ?>">

                <td class="text-muted"><?= $t['id'] ?></td>

                <td>

                  <div class="topic-text" title="<?= htmlspecialchars($t['topic_text']) ?>">

                    <?= htmlspecialchars($t['topic_text']) ?>

                  </div>

                </td>

                <td>

                  <span class="badge bg-<?= $uses_cls ?> use-badge">

                    <?= $t['use_count'] ?> / <?= $t['max_uses'] ?>

                  </span>

                </td>

                <td>

                  <?php if ($t['is_active'] && $t['use_count'] < $t['max_uses']): ?>

                    <span class="badge bg-success">Available</span>

                  <?php elseif ($t['is_active']): ?>

                    <span class="badge bg-warning text-dark">Exhausted</span>

                  <?php else: ?>

                    <span class="badge bg-secondary">Inactive</span>

                  <?php endif ?>

                </td>

                <td class="text-muted">

                  <?= $t['last_used_at'] ? date('d M Y', strtotime($t['last_used_at'])) : '—' ?>

                </td>

                <td>

                  <div class="d-flex gap-1">

                    <!-- Generate post for this topic -->

                    <form method="post" action="?tab=posts"

                          onsubmit="this.querySelector('button').disabled=true;this.querySelector('button').innerHTML='<i class=\'fas fa-spinner fa-spin\'></i>';">

                      <input type="hidden" name="action"   value="generate">

                      <input type="hidden" name="topic_id" value="<?= $t['id'] ?>">

                      <button type="submit" class="btn btn-outline-primary btn-sm" title="Generate post for this topic">

                        <i class="fas fa-robot"></i>

                      </button>

                    </form>

                    <!-- Toggle active -->

                    <form method="post" action="?tab=topics">

                      <input type="hidden" name="action"   value="toggle_topic">

                      <input type="hidden" name="topic_id" value="<?= $t['id'] ?>">

                      <button type="submit" class="btn btn-outline-secondary btn-sm"

                              title="<?= $t['is_active'] ? 'Deactivate' : 'Activate' ?>">

                        <i class="fas <?= $t['is_active'] ? 'fa-toggle-on' : 'fa-toggle-off' ?>"></i>

                      </button>

                    </form>

                    <!-- Delete -->

                    <form method="post" action="?tab=topics"

                          onsubmit="return confirm('Delete this topic? This cannot be undone.')">

                      <input type="hidden" name="action"   value="delete_topic">

                      <input type="hidden" name="topic_id" value="<?= $t['id'] ?>">

                      <button type="submit" class="btn btn-outline-danger btn-sm" title="Delete">

                        <i class="fas fa-trash"></i>

                      </button>

                    </form>

                  </div>

                </td>

              </tr>

            <?php endforeach ?>

            </tbody>

          </table>

        </div>

      </div>

    </div>



    <!-- Add topic form -->

    <div class="col-md-7">

      <div class="card border-0 shadow-sm">

        <div class="card-header bg-white py-3 fw-semibold">

          <i class="fas fa-plus-circle me-2 text-primary"></i>Add New Topic

        </div>

        <div class="card-body">

          <form method="post" action="?tab=topics">

            <input type="hidden" name="action" value="add_topic">

            <div class="mb-3">

              <label class="form-label fw-semibold">Topic prompt <span class="text-danger">*</span></label>

              <textarea name="topic_text" class="form-control" rows="3" required

                placeholder="e.g. How to use WhatsApp to communicate with parents in Ghanaian schools"></textarea>

              <div class="form-text">Write it as a topic prompt for the AI — specific and Ghana/Africa-relevant.</div>

            </div>

            <div class="mb-3">

              <label class="form-label fw-semibold">Max uses</label>

              <input type="number" name="max_uses" class="form-control" value="2" min="1" max="10" style="width:100px">

              <div class="form-text">How many posts can be generated from this topic before it's exhausted (default: 2).</div>

            </div>

            <button type="submit" class="btn btn-primary">

              <i class="fas fa-plus me-1"></i>Add Topic

            </button>

          </form>

        </div>

      </div>

    </div>



  </div>

  <?php endif ?>



  <!-- ════════════════════ TAB: GENERATE ════════════════════ -->

  <?php if ($active_tab === 'generate'): ?>

  <div class="row g-4">



    <!-- Auto-generate -->

    <div class="col-md-6">

      <div class="card border-0 shadow-sm h-100">

        <div class="card-body p-4">

          <h5 class="fw-bold mb-1">

            <i class="fas fa-magic me-2 text-primary"></i>Auto-Generate

          </h5>

          <p class="text-muted small mb-3">

            Automatically picks the next available topic (fewest uses first) and publishes immediately.

            <strong><?= count($available_topics) ?></strong> topic<?= count($available_topics) !== 1 ? 's' : '' ?> available.

          </p>

          <form method="post" action="?tab=posts"

                onsubmit="this.querySelector('button').disabled=true; this.querySelector('button').innerHTML='<i class=\'fas fa-spinner fa-spin me-1\'></i>Generating...';">

            <input type="hidden" name="action" value="generate">

            <button type="submit" class="btn btn-primary">

              <i class="fas fa-robot me-1"></i>Generate &amp; Publish Post

            </button>

          </form>

          <?php if (count($available_topics) === 0): ?>

            <div class="alert alert-warning mt-3 small mb-0">

              All topics are exhausted. Use "Reset All Counts" in the Topics tab, or add new topics.

            </div>

          <?php endif ?>

        </div>

      </div>

    </div>



    <!-- Generate from specific topic -->

    <div class="col-md-6">

      <div class="card border-0 shadow-sm h-100">

        <div class="card-body p-4">

          <h5 class="fw-bold mb-1">

            <i class="fas fa-bullseye me-2 text-success"></i>Generate from Specific Topic

          </h5>

          <p class="text-muted small mb-3">Choose a specific topic from the list below.</p>

          <form method="post" action="?tab=posts"

                onsubmit="if(!document.getElementById('topicSelect').value){alert('Please select a topic.');return false;} this.querySelector('[type=submit]').disabled=true; this.querySelector('[type=submit]').innerHTML='<i class=\'fas fa-spinner fa-spin me-1\'></i>Generating...';">

            <input type="hidden" name="action" value="generate">

            <div class="mb-3">

              <select name="topic_id" id="topicSelect" class="form-select" required>

                <option value="">— Select a topic —</option>

                <?php foreach ($topics as $t): ?>

                  <?php if (!$t['is_active']) continue; ?>

                  <option value="<?= $t['id'] ?>">

                    [<?= $t['use_count'] ?>/<?= $t['max_uses'] ?>]

                    <?= htmlspecialchars(mb_strimwidth($t['topic_text'], 0, 80, '…')) ?>

                  </option>

                <?php endforeach ?>

              </select>

            </div>

            <button type="submit" class="btn btn-success">

              <i class="fas fa-robot me-1"></i>Generate This Topic

            </button>

          </form>

        </div>

      </div>

    </div>



    <!-- Cron setup -->

    <div class="col-12">

      <div class="card border-0 shadow-sm">

        <div class="card-body p-4">

          <h6 class="fw-bold"><i class="fas fa-clock me-2"></i>Cron Setup (Namecheap cPanel)</h6>

          <p class="small text-muted mb-2">Add in cPanel → Cron Jobs (Mon, Tue, Thu, Fri at 7am):</p>

          <pre class="bg-light p-3 rounded small">0 7 * * 1,2,4,5 curl -s "<?= BLOG_BASE_URL ?>/cron.php?token=<?= BLOG_CRON_TOKEN ?>" > /dev/null</pre>

          <p class="small text-muted mt-2 mb-0">

            <strong>Sitemap for Google Search Console:</strong>

            <code><?= BLOG_BASE_URL ?>/sitemap.php</code>

          </p>

        </div>

      </div>

    </div>



  </div>

  <?php endif ?>



  <!-- ════════════════════ TAB: LOG ════════════════════ -->

  <?php if ($active_tab === 'log'): ?>

  <div class="card border-0 shadow-sm">

    <div class="card-header bg-white fw-semibold py-3 d-flex justify-content-between align-items-center">

      <span><i class="fas fa-terminal me-2"></i>Cron Log (last 50 lines)</span>

      <span class="small text-muted font-monospace">blog/logs/cron.log</span>

    </div>

    <div class="card-body p-0">

      <pre class="p-3 mb-0 small bg-dark text-success" style="max-height:500px;overflow-y:auto;border-radius:0 0 8px 8px;"><?php

        if (empty($log_lines)) {

            echo 'No log entries yet. Run the cron or generate a post above.';

        } else {

            foreach (array_reverse($log_lines) as $line) {

                echo htmlspecialchars($line) . "\n";

            }

        }

      ?></pre>

    </div>

  </div>

  <?php endif ?>



</div><!-- /container -->



<!-- ════════════════════ EDIT POST MODAL ════════════════════ -->

<div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">

  <div class="modal-dialog modal-xl modal-dialog-scrollable">

    <div class="modal-content">

      <div class="modal-header">

        <h5 class="modal-title fw-bold" id="editModalLabel">

          <i class="fas fa-pen me-2 text-primary"></i>Edit Post <span id="editModalId" class="text-muted small"></span>

        </h5>

        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>

      </div>

      <form method="post" action="?tab=posts" id="editForm">

        <div class="modal-body">

          <input type="hidden" name="action"  value="edit_post">

          <input type="hidden" name="post_id" id="editPostId">



          <div id="editLoadingSpinner" class="text-center py-5">

            <div class="spinner-border text-primary" role="status"></div>

            <p class="mt-2 text-muted small">Loading post data…</p>

          </div>



          <div id="editFormFields" style="display:none">

            <div class="row g-3">

              <div class="col-12">

                <label class="form-label fw-semibold">Title <span class="text-danger">*</span></label>

                <input type="text" name="title" id="editTitle" class="form-control" maxlength="255" required>

                <div class="form-text">Max 70 characters recommended for SEO.</div>

              </div>

              <div class="col-md-8">

                <label class="form-label fw-semibold">Meta Description</label>

                <textarea name="meta_description" id="editMeta" class="form-control" rows="2" maxlength="255"></textarea>

                <div class="form-text">140–160 characters for Google preview.</div>

              </div>

              <div class="col-md-4">

                <label class="form-label fw-semibold">Category</label>

                <select name="category" id="editCategory" class="form-select">

                  <option value="School Management">School Management</option>

                  <option value="Fees &amp; Payments">Fees &amp; Payments</option>

                  <option value="Attendance">Attendance</option>

                  <option value="Reports">Reports</option>

                  <option value="Staff">Staff</option>

                  <option value="Canteen">Canteen</option>

                  <option value="Parent Portal">Parent Portal</option>

                  <option value="Technology">Technology</option>

                  <option value="Ghana Education">Ghana Education</option>

                </select>

              </div>

              <div class="col-md-8">

                <label class="form-label fw-semibold">Tags <span class="text-muted small">(comma-separated)</span></label>

                <input type="text" name="tags" id="editTags" class="form-control" placeholder="fees, ghana, school management">

              </div>

              <div class="col-md-4">

                <label class="form-label fw-semibold">Status</label>

                <select name="status" id="editStatus" class="form-select">

                  <option value="published">Published</option>

                  <option value="draft">Draft</option>

                  <option value="archived">Archived</option>

                </select>

              </div>

              <div class="col-12">

                <label class="form-label fw-semibold">Excerpt</label>

                <textarea name="excerpt" id="editExcerpt" class="form-control" rows="2"></textarea>

              </div>

              <div class="col-12">

                <label class="form-label fw-semibold">HTML Content</label>

                <textarea name="html_content" id="editHtmlContent" class="form-control" rows="18"

                          placeholder="Full article HTML…"></textarea>

                <div class="form-text">Raw HTML — starts from the first &lt;h2&gt;. No &lt;html&gt;/&lt;body&gt; tags.</div>

              </div>

            </div>

          </div>

        </div>

        <div class="modal-footer">

          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>

          <button type="submit" class="btn btn-primary" id="editSaveBtn">

            <i class="fas fa-save me-1"></i>Save Changes

          </button>

        </div>

      </form>

    </div>

  </div>

</div>



<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>

function openEditModal(postId) {

  const modal      = new bootstrap.Modal(document.getElementById('editModal'));

  const spinner    = document.getElementById('editLoadingSpinner');

  const fields     = document.getElementById('editFormFields');

  const saveBtn    = document.getElementById('editSaveBtn');



  // Reset modal state

  document.getElementById('editModalId').textContent = '#' + postId;

  document.getElementById('editPostId').value = postId;

  spinner.style.display = '';

  fields.style.display  = 'none';

  saveBtn.disabled      = true;



  modal.show();



  fetch('admin.php?api=post&id=' + postId)

    .then(r => r.json())

    .then(data => {

      if (data.error) {

        spinner.innerHTML = '<div class="alert alert-danger">Failed to load post data.</div>';

        return;

      }

      document.getElementById('editTitle').value       = data.title        || '';

      document.getElementById('editMeta').value        = data.meta_description || '';

      document.getElementById('editTags').value        = data.tags         || '';

      document.getElementById('editExcerpt').value     = data.excerpt      || '';

      document.getElementById('editHtmlContent').value = data.html_content || '';



      // Set category select

      const catSel = document.getElementById('editCategory');

      for (let o of catSel.options) {

        o.selected = (o.value === data.category);

      }



      // Set status select

      const stSel = document.getElementById('editStatus');

      for (let o of stSel.options) {

        o.selected = (o.value === data.status);

      }



      spinner.style.display = 'none';

      fields.style.display  = '';

      saveBtn.disabled      = false;

    })

    .catch(() => {

      spinner.innerHTML = '<div class="alert alert-danger">Network error loading post.</div>';

    });

}

</script>



<?php endif ?>

</body>

</html>

