<?php

/**

 * Blog setup — creates/migrates tables and seeds topics.

 * Safe to run multiple times (idempotent).

 * Access: https://yourdomain.com/blog/setup.php?token=oric-blog-cron-b94f2c1e9a37

 */



require_once __DIR__ . '/config.php';

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



$token = trim($_GET['token'] ?? '');

if ($token !== BLOG_CRON_TOKEN) {

    http_response_code(403);

    exit('Forbidden. Provide the correct ?token= parameter.');

}



$messages = [];



try {

    $conn = blog_db();



    // ── 1. blog_posts ─────────────────────────────────────────────────────────

    $conn->query("

    CREATE TABLE IF NOT EXISTS blog_posts (

      id                    INT AUTO_INCREMENT PRIMARY KEY,

      title                 VARCHAR(255) NOT NULL,

      slug                  VARCHAR(255) NOT NULL UNIQUE,

      meta_description      VARCHAR(255),

      category              VARCHAR(100),

      tags                  VARCHAR(500),

      excerpt               TEXT,

      html_content          LONGTEXT NOT NULL,

      reading_time_minutes  INT DEFAULT 5,

      status                ENUM('published','draft','archived') DEFAULT 'draft',

      topic_source          TEXT,

      topic_id              INT NULL,

      view_count            INT DEFAULT 0,

      published_at          DATETIME,

      created_at            DATETIME DEFAULT CURRENT_TIMESTAMP,

      updated_at            DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

      INDEX idx_status      (status),

      INDEX idx_category    (category),

      INDEX idx_published   (published_at),

      INDEX idx_slug        (slug)

    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

    ");

    $messages[] = ['ok', '<strong>blog_posts</strong> table created (or already exists).'];



    // ── 2. Add topic_id column if not present ─────────────────────────────────

    $conn->query("ALTER TABLE blog_posts ADD COLUMN IF NOT EXISTS topic_id INT NULL");

    $messages[] = ['ok', '<code>topic_id</code> column on <strong>blog_posts</strong> ensured.'];



    // ── 3. blog_topics ────────────────────────────────────────────────────────

    $conn->query("

    CREATE TABLE IF NOT EXISTS blog_topics (

      id           INT AUTO_INCREMENT PRIMARY KEY,

      topic_text   TEXT NOT NULL,

      use_count    INT DEFAULT 0,

      max_uses     INT DEFAULT 2,

      is_active    TINYINT(1) DEFAULT 1,

      last_used_at DATETIME NULL,

      created_at   DATETIME DEFAULT CURRENT_TIMESTAMP

    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

    ");

    $messages[] = ['ok', '<strong>blog_topics</strong> table created (or already exists).'];



    // ── 4. Seed topics from BLOG_TOPICS constant if table is empty ─────────────

    $n_res   = $conn->query('SELECT COUNT(*) AS n FROM blog_topics');

    $n_count = (int) ($n_res ? $n_res->fetch_assoc()['n'] : 0);



    if ($n_count === 0) {

        $stmt   = $conn->prepare('INSERT INTO blog_topics (topic_text) VALUES (?)');

        $seeded = 0;

        foreach (BLOG_TOPICS as $topic) {

            $stmt->bind_param('s', $topic);

            $stmt->execute();

            $seeded++;

        }

        $stmt->close();

        $messages[] = ['ok', "Seeded <strong>{$seeded} topics</strong> from the BLOG_TOPICS constant."];

    } else {

        $messages[] = ['info', "blog_topics already has <strong>{$n_count} topics</strong> — seed skipped."];

    }



} catch (Throwable $e) {

    $messages[] = ['error', 'Fatal: ' . htmlspecialchars($e->getMessage())];

}

?>

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <title>Blog Setup — EduTrack</title>

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

</head>

<body class="bg-light p-4">

<div class="container" style="max-width:600px">

  <h4 class="mb-4">EduTrack Blog Setup</h4>

  <?php foreach ($messages as [$type, $msg]): ?>

    <?php $cls = $type === 'ok' ? 'success' : ($type === 'error' ? 'danger' : 'info') ?>

    <div class="alert alert-<?= $cls ?>"><?= $msg ?></div>

  <?php endforeach ?>

  <p class="text-muted small">

    <a href="index.php">View blog</a> ·

    <a href="admin.php">Open admin</a> ·

    Delete or rename <code>setup.php</code> after running.

  </p>

</div>

</body>

</html>

