<?php

// Enable error display but hide deprecation warnings
error_reporting(E_ALL & ~E_DEPRECATED);
ini_set('display_errors', 1);

// Start from admin directory context
session_start();
require '../../config.php';
require '../functions.php';

if (!isset($_SESSION['user_email'])){
    die("Not authenticated");
}

$connect = connect();
if(!$connect){
    die("Database connection failed");
}

$check_access = check_access($connect);

if ($check_access['user_role'] != 1 && $check_access['user_role'] != 2){
    die("Access denied");
}

$post_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($post_id <= 0) {
    die("Invalid post ID");
}

// Get blog post (including drafts for preview)
$stmt = $connect->prepare("SELECT bp.*, bc.blog_cat_name, bc.blog_cat_slug, u.user_name 
                           FROM blog_posts bp
                           LEFT JOIN blog_categories bc ON bp.post_category = bc.blog_cat_id
                           LEFT JOIN users u ON bp.post_author = u.user_id
                           WHERE bp.post_id = :id");
$stmt->execute([':id' => $post_id]);
$post = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$post) {
    die("Post not found");
}

// Get related posts
$relatedPosts = [];
if ($post['post_category']) {
    $stmt = $connect->prepare("SELECT * FROM blog_posts 
                               WHERE post_category = :cat AND post_id != :id
                               ORDER BY published_at DESC LIMIT 3");
    $stmt->execute([':cat' => $post['post_category'], ':id' => $post['post_id']]);
    $relatedPosts = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Redirect to live post URL with preview banner
$previewUrl = SITE_URL . '/Post/' . $post['post_slug'] . '?preview=1&preview_id=' . $post_id;
header('Location: ' . $previewUrl);
exit;
?>
