<?php
session_start();
require_once "../db.php";

if (!isset($_SESSION['user_id']) || $_SESSION['username'] !== "admin") {
    die("Access denied.");
}

$post_id = intval($_POST['post_id'] ?? 0);

// Fetch file paths first
$stmt = $pdo->prepare("SELECT file_path, thumbnail_path FROM posts WHERE id = ?");
$stmt->execute([$post_id]);
$post = $stmt->fetch(PDO::FETCH_ASSOC);

if ($post) {
    // Delete physical files
    $full = __DIR__ . "/../" . $post['file_path'];
    $thumb = __DIR__ . "/../" . $post['thumbnail_path'];

    if (file_exists($full)) unlink($full);
    if (file_exists($thumb)) unlink($thumb);

    // Delete tags
    $pdo->prepare("DELETE FROM post_tags WHERE post_id = ?")->execute([$post_id]);

    // Delete comments
    $pdo->prepare("DELETE FROM comments WHERE post_id = ?")->execute([$post_id]);

    // Delete ratings
    $pdo->prepare("DELETE FROM ratings WHERE post_id = ?")->execute([$post_id]);

    // Delete post
    $pdo->prepare("DELETE FROM posts WHERE id = ?")->execute([$post_id]);
}

header("Location: ../admin/moderate.php");
exit;