<?php
/**
 * EduTrack Blog — single post view.
 */

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

$conn = blog_db();
$slug = trim($_GET['slug'] ?? '');

if ($slug === '') {
    header('Location: ' . BLOG_BASE_URL . '/index.php');
    exit;
}

$stmt = $conn->prepare(
    'SELECT * FROM blog_posts WHERE slug = ? AND status = "published" LIMIT 1'
);
$stmt->bind_param('s', $slug);
$stmt->execute();
$post = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$post) {
    http_response_code(404);
    header('Location: ' . BLOG_BASE_URL . '/index.php');
    exit;
}

// Increment view count
$conn->query("UPDATE blog_posts SET view_count = view_count + 1 WHERE slug = '" . $conn->real_escape_string($slug) . "'");

// Related posts (same category, excluding current)
$rel_stmt = $conn->prepare(
    'SELECT slug, title, reading_time_minutes, published_at FROM blog_posts
     WHERE status="published" AND category=? AND slug != ? ORDER BY published_at DESC LIMIT 3'
);
$rel_stmt->bind_param('ss', $post['category'], $slug);
$rel_stmt->execute();
$related = $rel_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$rel_stmt->close();

$pub_date    = $post['published_at'] ? date('d M Y', strtotime($post['published_at'])) : '';
$pub_iso     = $post['published_at'] ? date('c', strtotime($post['published_at'])) : '';
$upd_iso     = $post['updated_at']   ? date('c', strtotime($post['updated_at']))   : $pub_iso;
$tags_arr    = array_filter(array_map('trim', explode(',', $post['tags'] ?? '')));
$post_url    = BLOG_BASE_URL . '/post.php?slug=' . urlencode($slug);
$share_tw    = 'https://twitter.com/intent/tweet?text=' . urlencode($post['title']) . '&url=' . urlencode($post_url);
$share_li    = 'https://www.linkedin.com/sharing/share-offsite/?url=' . urlencode($post_url);
$share_wa    = 'https://wa.me/?text=' . urlencode($post['title'] . ' ' . $post_url);

// JSON-LD schemas
$article_ld = json_encode([
    '@context'         => 'https://schema.org',
    '@type'            => 'Article',
    'headline'         => $post['title'],
    'description'      => $post['meta_description'] ?? '',
    'author'           => ['@type' => 'Organization', 'name' => BLOG_AUTHOR],
    'publisher'        => ['@type' => 'Organization', 'name' => BLOG_AUTHOR,
                           'logo'  => ['@type' => 'ImageObject', 'url' => 'https://edutrack.oricnetwork.com/assets/logo.png']],
    'datePublished'    => $pub_iso,
    'dateModified'     => $upd_iso,
    'url'              => $post_url,
    'mainEntityOfPage' => $post_url,
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

// Build FAQPage schema from HTML — extract h3 + p pairs inside .blog-faq
$faq_ld      = '';
$faq_matches = [];
if (preg_match('/<section[^>]*class="blog-faq"[^>]*>(.*?)<\/section>/si', $post['html_content'], $sec)) {
    preg_match_all('/<h3>(.*?)<\/h3>\s*<p>(.*?)<\/p>/si', $sec[1], $faq_matches);
}
if (!empty($faq_matches[1])) {
    $faqs = [];
    foreach ($faq_matches[1] as $i => $q) {
        $faqs[] = [
            '@type'          => 'Question',
            'name'           => strip_tags($q),
            'acceptedAnswer' => ['@type' => 'Answer', 'text' => strip_tags($faq_matches[2][$i])],
        ];
    }
    $faq_ld = json_encode([
        '@context'   => 'https://schema.org',
        '@type'      => 'FAQPage',
        'mainEntity' => $faqs,
    ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}

$breadcrumb_ld = json_encode([
    '@context'        => 'https://schema.org',
    '@type'           => 'BreadcrumbList',
    'itemListElement' => [
        ['@type' => 'ListItem', 'position' => 1, 'name' => 'Home',         'item' => 'https://edutrack.oricnetwork.com'],
        ['@type' => 'ListItem', 'position' => 2, 'name' => 'Blog',         'item' => BLOG_BASE_URL . '/index.php'],
        ['@type' => 'ListItem', 'position' => 3, 'name' => $post['title'], 'item' => $post_url],
    ],
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?= htmlspecialchars($post['title']) ?> — <?= BLOG_SITE_NAME ?></title>
  <meta name="description" content="<?= htmlspecialchars($post['meta_description'] ?? '') ?>">
  <link rel="canonical" href="<?= $post_url ?>">
  <link rel="alternate" type="application/rss+xml" title="<?= BLOG_SITE_NAME ?>" href="<?= BLOG_BASE_URL ?>/rss.php">
  <!-- Open Graph -->
  <meta property="og:title"       content="<?= htmlspecialchars($post['title']) ?>">
  <meta property="og:description" content="<?= htmlspecialchars($post['meta_description'] ?? '') ?>">
  <meta property="og:type"        content="article">
  <meta property="og:url"         content="<?= $post_url ?>">
  <meta property="article:published_time" content="<?= $pub_iso ?>">
  <meta property="article:modified_time"  content="<?= $upd_iso ?>">
  <!-- Twitter Card -->
  <meta name="twitter:card"        content="summary">
  <meta name="twitter:title"       content="<?= htmlspecialchars($post['title']) ?>">
  <meta name="twitter:description" content="<?= htmlspecialchars($post['meta_description'] ?? '') ?>">
  <!-- Bootstrap -->
  <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">
  <!-- JSON-LD -->
  <script type="application/ld+json"><?= $article_ld ?></script>
  <?php if ($faq_ld): ?>
  <script type="application/ld+json"><?= $faq_ld ?></script>
  <?php endif ?>
  <script type="application/ld+json"><?= $breadcrumb_ld ?></script>
</head>
<body class="blog-body">

<!-- NAV -->
<nav class="blog-nav">
  <div class="container d-flex align-items-center justify-content-between py-3">
    <a class="blog-brand" href="<?= BLOG_BASE_URL ?>/index.php">
      <span class="brand-dot"></span> EduTrack Blog
    </a>
    <a href="<?= CTA_PRIMARY_URL ?>" class="btn btn-sm btn-primary px-3" target="_blank">Get EduTrack Free</a>
  </div>
</nav>

<!-- BREADCRUMB -->
<div class="container pt-3 pb-1">
  <nav aria-label="breadcrumb">
    <ol class="breadcrumb small">
      <li class="breadcrumb-item"><a href="https://edutrack.oricnetwork.com" target="_blank">EduTrack</a></li>
      <li class="breadcrumb-item"><a href="<?= BLOG_BASE_URL ?>/index.php">Blog</a></li>
      <?php if ($post['category']): ?>
      <li class="breadcrumb-item">
        <a href="<?= BLOG_BASE_URL ?>/index.php?cat=<?= urlencode($post['category']) ?>">
          <?= htmlspecialchars($post['category']) ?>
        </a>
      </li>
      <?php endif ?>
      <li class="breadcrumb-item active" aria-current="page"><?= htmlspecialchars(substr($post['title'], 0, 50)) ?>...</li>
    </ol>
  </nav>
</div>

<!-- ARTICLE -->
<main class="container py-4">
  <div class="row justify-content-center">
    <div class="col-lg-8">
      <article class="blog-article">

        <!-- Header -->
        <header class="article-header mb-4">
          <?php if ($post['category']): ?>
            <a href="<?= BLOG_BASE_URL ?>/index.php?cat=<?= urlencode($post['category']) ?>"
               class="post-category mb-2 d-inline-block">
              <?= htmlspecialchars($post['category']) ?>
            </a>
          <?php endif ?>
          <h1 class="article-title"><?= htmlspecialchars($post['title']) ?></h1>
          <div class="article-meta d-flex flex-wrap align-items-center gap-3 mt-3">
            <span><i class="fas fa-user-circle me-1"></i><?= BLOG_AUTHOR ?></span>
            <span><i class="far fa-calendar me-1"></i><?= $pub_date ?></span>
            <span><i class="far fa-clock me-1"></i><?= (int)$post['reading_time_minutes'] ?> min read</span>
            <span><i class="far fa-eye me-1"></i><?= number_format((int)($post['view_count'] ?? 0)) ?> views</span>
          </div>
        </header>

        <!-- Body -->
        <div class="article-body">
          <?= $post['html_content'] ?>
        </div>

        <!-- Tags -->
        <?php if (!empty($tags_arr)): ?>
        <div class="article-tags mt-5">
          <?php foreach ($tags_arr as $tag): ?>
            <span class="tag-pill"><?= htmlspecialchars($tag) ?></span>
          <?php endforeach ?>
        </div>
        <?php endif ?>

        <!-- Share -->
        <div class="share-bar mt-4 d-flex align-items-center gap-3 flex-wrap">
          <span class="fw-semibold small">Share:</span>
          <a href="<?= $share_tw ?>" target="_blank" rel="noopener" class="share-btn share-twitter">
            <i class="fab fa-x-twitter"></i> X / Twitter
          </a>
          <a href="<?= $share_li ?>" target="_blank" rel="noopener" class="share-btn share-linkedin">
            <i class="fab fa-linkedin"></i> LinkedIn
          </a>
          <a href="<?= $share_wa ?>" target="_blank" rel="noopener" class="share-btn share-whatsapp">
            <i class="fab fa-whatsapp"></i> WhatsApp
          </a>
        </div>

      </article>

      <!-- End CTA -->
      <div class="blog-cta-end text-center py-5 mt-4">
        <h3>Modernise your school with EduTrack</h3>
        <p class="text-muted mb-4">School management software built for Ghana. Fees, attendance, reports, and more — all in one place.</p>
        <a href="<?= CTA_PRIMARY_URL ?>" class="btn btn-primary btn-lg px-5 me-2" target="_blank"><?= CTA_PRIMARY_TEXT ?></a>
        <a href="<?= CTA_WHATSAPP_URL ?>" class="btn btn-outline-success btn-lg px-4" target="_blank">
          <i class="fab fa-whatsapp me-1"></i><?= CTA_WHATSAPP_TEXT ?>
        </a>
      </div>

    </div><!-- /col -->

    <!-- Sidebar -->
    <div class="col-lg-4 d-none d-lg-block">
      <aside class="blog-sidebar ps-lg-4">

        <!-- About card -->
        <div class="sidebar-card mb-4">
          <h5 class="sidebar-heading">About EduTrack</h5>
          <p class="small text-muted">School management software designed for Ghanaian schools. Manage fees, attendance, reports, staff, and parents from one dashboard.</p>
          <a href="<?= CTA_PRIMARY_URL ?>" class="btn btn-primary btn-sm w-100" target="_blank">Start Free Trial</a>
        </div>

        <!-- Related posts -->
        <?php if (!empty($related)): ?>
        <div class="sidebar-card mb-4">
          <h5 class="sidebar-heading">Related Articles</h5>
          <?php foreach ($related as $r): ?>
            <a href="<?= BLOG_BASE_URL ?>/post.php?slug=<?= urlencode($r['slug']) ?>" class="related-post">
              <span><?= htmlspecialchars($r['title']) ?></span>
              <small class="text-muted d-block mt-1"><i class="far fa-clock me-1"></i><?= (int)$r['reading_time_minutes'] ?> min</small>
            </a>
          <?php endforeach ?>
        </div>
        <?php endif ?>

        <!-- WhatsApp CTA -->
        <div class="sidebar-card sidebar-wa">
          <i class="fab fa-whatsapp fa-2x mb-2"></i>
          <p class="small mb-2">Have questions? Chat with the EduTrack team on WhatsApp.</p>
          <a href="<?= CTA_WHATSAPP_URL ?>" class="btn btn-success btn-sm w-100" target="_blank">Chat Now</a>
        </div>

      </aside>
    </div>
  </div>
</main>

<!-- FOOTER CTA -->
<section class="footer-cta py-5 text-center">
  <div class="container">
    <h3>Ready to modernise your school?</h3>
    <p class="text-muted mb-4">Join hundreds of Ghanaian schools using EduTrack to save time and reduce admin work.</p>
    <a href="<?= CTA_PRIMARY_URL ?>" class="btn btn-primary btn-lg px-5 me-2" target="_blank"><?= CTA_PRIMARY_TEXT ?></a>
    <a href="<?= CTA_WHATSAPP_URL ?>" class="btn btn-outline-success btn-lg px-4" target="_blank">
      <i class="fab fa-whatsapp me-1"></i><?= CTA_WHATSAPP_TEXT ?>
    </a>
  </div>
</section>

<footer class="blog-footer text-center py-4">
  <div class="container">
    <p class="mb-1 small">&copy; <?= date('Y') ?> <a href="https://oricnetwork.com" target="_blank">ORIC Network Limited</a> &middot; All rights reserved.</p>
    <p class="small text-muted mb-0">
      <a href="<?= BLOG_BASE_URL ?>/sitemap.php">Sitemap</a> &middot;
      <a href="<?= BLOG_BASE_URL ?>/rss.php">RSS</a> &middot;
      <a href="https://edutrack.oricnetwork.com" target="_blank">EduTrack Home</a>
    </p>
  </div>
</footer>

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