<?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 data
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 post_locations ON posts.post_location = post_locations.id
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';

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

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

// ----------------------
// PAGE META
// ----------------------
$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);

// ✅ FIXED canonical
$canonicalUrl = "https://thrillsense.com" . $correctPath;

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

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

// Related (FIXED: added 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 != 5
        AND status = 'published'
        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);
}

// Structured data
$structuredData = [
    "@context" => "https://schema.org",
    "@type" => "Article",
    "headline" => $post['title'],
    "image" => "https://thrillsense.com" . $featuredImage,
    "author" => ["@type" => "Person", "name" => $authorName],
    "publisher" => [
        "@type" => "Organization",
        "name" => "ThrillSense",
        "logo" => [
            "@type" => "ImageObject",
            "url" => "https://thrillsense.com/assets/logo.png"
        ]
    ],
    "datePublished" => date('c', strtotime($post['created_at'])),
    "dateModified" => date('c', strtotime($post['updated_at'] ?? $post['created_at']))
];

$extra_head .= "
<script type=\"application/ld+json\">" . json_encode($structuredData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "</script>
";

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

<main>

<!-- HERO -->
<section class="hero position-relative" style="height: 60vh; overflow: hidden;">
  <img src="<?= htmlspecialchars($featuredImage) ?>" 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 News</h4>

        <?php foreach ($latestSidebar as $item): ?>
          <?php $itemType = $typeMap[$item['post_location']] ?? 'article'; ?>
          <a href="/<?= $itemType ?>/<?= $item['slug'] ?>" class="sidebar-card d-flex mb-3 text-decoration-none">
            <div class="ms-2">
              <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 Articles</h4>

        <?php foreach ($relatedPosts as $item): ?>
          <?php $itemType = $typeMap[$item['post_location']] ?? 'article'; ?>
          <a href="/<?= $itemType ?>/<?= $item['slug'] ?>" class="sidebar-card d-flex mb-3 text-decoration-none">
            <div class="ms-3">
              <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'; ?>