<?php
require_once __DIR__ . '/config.php';

$extra_head = '<link rel="stylesheet" href="/styles/blog.css">';

// ----------------------
// GET SLUG
// ----------------------
$slug = $_GET['slug'] ?? '';

if (!$slug) {
    http_response_code(404);
    echo "<h1>404 Not Found</h1>";
    exit;
}

// ----------------------
// FETCH POST + AUTHOR
// ----------------------
try {
    $stmt = $pdo->prepare("
        SELECT 
            posts.*, 
            admin_users.username AS author_name,
            admin_users.display_name,
            admin_users.bio,
            admin_users.profile_image
        FROM posts 
        LEFT JOIN admin_users ON posts.created_by = admin_users.id 
        WHERE posts.slug = ?
    ");
    $stmt->execute([$slug]);
    $post = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$post) {
        http_response_code(404);
        echo "<h1>Post not found</h1>";
        exit;
    }
    
    // ----------------------
// TRACK PAGE VIEW
// ----------------------
$viewStmt = $pdo->prepare("
    INSERT INTO page_views (post_id)
    VALUES (?)
");

$viewStmt->execute([$post['id']]);
    
} catch (PDOException $e) {
    die("Database error: " . htmlspecialchars($e->getMessage()));
}

// ----------------------
// FORCE CORRECT URL (KEY FIX)
// ----------------------
$type = strtolower(trim($post['post_location']));
$correctPath = '/' . $type . '/' . $post['slug'];

$currentPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

if ($currentPath !== $correctPath) {
    header("Location: $correctPath", true, 301);
    exit;
}

// ----------------------
// AUTHOR DATA
// ----------------------
$authorUsername = $post['author_name'] ?? 'Admin';

$authorName = !empty($post['display_name']) 
    ? $post['display_name'] 
    : $authorUsername;

$authorBio = $post['bio'] ?? '';

$authorImage = (!empty($post['profile_image']) && file_exists(__DIR__ . '/' . $post['profile_image']))
    ? '/' . ltrim($post['profile_image'], '/')
    : '/uploads/authors/blank.png';

// ----------------------
// SEO + PAGE DATA
// ----------------------
$featuredImage = !empty($post['image_path']) 
    ? '/' . ltrim($post['image_path'], '/') 
    : '/assets/hero.jpg';

$pageTitle = "ThrillSense | " . $post['title'];

$plainText = trim(preg_replace('/\s+/', ' ', strip_tags($post['content'] ?? '')));

if (!empty($post['meta_description'])) {
    $metaDescription = trim($post['meta_description']);
} else {
    $metaDescription = substr($plainText, 0, 155);
    $metaDescription = preg_replace('/\s+\S*$/', '', $metaDescription);
}

$wordCount = str_word_count($plainText);
$readingTime = ceil($wordCount / 200);

// Canonical
$canonicalUrl = "https://thrillsense.com" . $correctPath;

// ----------------------
// SIDEBAR DATA
// ----------------------

// Latest (FIXED: include post_location)
$latestStmt = $pdo->prepare("
    SELECT slug, title, image_path, created_at, post_location
    FROM posts 
    WHERE slug != ?
    AND post_location != 'tickets'
    ORDER BY created_at DESC 
    LIMIT 3
");
$latestStmt->execute([$post['slug']]);
$latestSidebar = $latestStmt->fetchAll(PDO::FETCH_ASSOC);

// Related (FIXED: include post_location)
$relatedPosts = [];

if (!empty($post['tags'])) {
    $tagsArray = array_map('trim', explode(',', $post['tags']));

    $conditions = [];
    foreach ($tagsArray as $tag) {
        $conditions[] = "tags LIKE ?";
    }

    $sql = "
        SELECT slug, title, image_path, created_at, post_location
        FROM posts
        WHERE slug != ?
        AND post_location != 'tickets'
        AND (" . implode(' OR ', $conditions) . ")
        ORDER BY created_at DESC
        LIMIT 3
    ";

    $params = array_merge(
        [$post['slug']],
        array_map(fn($t) => "%$t%", $tagsArray)
    );

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $relatedPosts = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

require_once __DIR__ . '/includes/header.php';
?>

<main>

<!-- HERO -->
<section class="hero position-relative" style="height: 60vh; overflow: hidden;">
  <img src="<?= htmlspecialchars($featuredImage) ?>" alt="<?= htmlspecialchars($post['title']) ?>" class="hero-bg" />

  <div class="hero-content text-white px-3">
    <h1 class="display-4 fw-bold"><?= htmlspecialchars($post['title']) ?></h1>

<p class="mt-2 text-white info-by">

  Published <?= date('F j, Y', strtotime($post['created_at'])) ?>

  <?php if (
      !empty($post['updated_at']) &&
      strtotime($post['updated_at']) > strtotime($post['created_at'])
  ): ?>

    • Updated <?= date('F j, Y', strtotime($post['updated_at'])) ?>

  <?php endif; ?>

  • <?= $readingTime ?> min read

</p>
  </div>
</section>

<!-- CONTENT + SIDEBAR -->
<section class="container py-5">
  <div class="row">

    <!-- MAIN -->
    <div class="col-lg-9">
      <article class="post-content">
        <?= $post['content'] ?>
      </article>
    </div>

    <!-- SIDEBAR -->
    <div class="col-lg-3 sidebar-col">

      <!-- AUTHOR -->
      <div class="sidebar-section mb-4 author-box">
        <h4 class="sidebar-title">Written by:</h4>

        <div class="d-flex align-items-start gap-3">
          <img src="<?= htmlspecialchars($authorImage) ?>" class="author-avatar" alt="<?= htmlspecialchars($authorName) ?>">

          <div>
            <h6 class="mb-1"><?= htmlspecialchars($authorName) ?></h6>

            <?php if (!empty($authorBio)): ?>
              <p class="author-bio mb-0">
                <?= htmlspecialchars($authorBio) ?>
              </p>
            <?php endif; ?>
          </div>
        </div>
      </div>

      <!-- LATEST -->
      <div class="sidebar-section mb-5">
        <h4 class="sidebar-title">Latest</h4>

        <?php foreach ($latestSidebar as $item): ?>
          <?php $itemType = strtolower(trim($item['post_location'])); ?>
          <a href="/<?= $itemType ?>/<?= $item['slug'] ?>" class="sidebar-card d-flex mb-3 text-decoration-none">
            <div>
              <p class="sidebar-date"><?= date('M j, Y', strtotime($item['created_at'])) ?></p>
              <h6><?= htmlspecialchars($item['title']) ?></h6>
            </div>
          </a>
        <?php endforeach; ?>
      </div>

      <!-- RELATED -->
      <?php if (!empty($relatedPosts)): ?>
      <div class="sidebar-section">
        <h4 class="sidebar-title">Related Guides</h4>

        <?php foreach ($relatedPosts as $item): ?>
          <?php $itemType = strtolower(trim($item['post_location'])); ?>
          <a href="/<?= $itemType ?>/<?= $item['slug'] ?>" class="sidebar-card d-flex mb-3 text-decoration-none">
            <div>
              <p class="sidebar-date"><?= date('M j, Y', strtotime($item['created_at'])) ?></p>
              <h6><?= htmlspecialchars($item['title']) ?></h6>
            </div>
          </a>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>

    </div>

  </div>
</section>

</main>

<?php include 'includes/footer.php'; ?>