<?php
/**
 * Admin - Delete Blog Post
 */
require_once __DIR__ . '/../config.php';
require_admin_login();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect(BASE_URL . 'admin/blog-posts.php', 'error', 'Invalid request');
}

if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
    redirect(BASE_URL . 'admin/blog-posts.php', 'error', 'Invalid security token');
}

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

if (!$post_id) {
    redirect(BASE_URL . 'admin/blog-posts.php', 'error', 'Invalid post ID');
}

try {
    // Check if post exists
    $stmt = db()->prepare("SELECT title FROM blog_posts WHERE id = ?");
    $stmt->execute([$post_id]);
    $post = $stmt->fetch();
    
    if (!$post) {
        redirect(BASE_URL . 'admin/blog-posts.php', 'error', 'Post not found');
    }
    
    // Delete post
    $stmt = db()->prepare("DELETE FROM blog_posts WHERE id = ?");
    $stmt->execute([$post_id]);
    
    // Log activity
    log_activity('blog_post_deleted', "Deleted blog post: {$post['title']}", $_SESSION['admin_id'], 'admin');
    
    redirect(BASE_URL . 'admin/blog-posts.php', 'success', 'Blog post deleted successfully');
    
} catch (PDOException $e) {
    error_log("Delete blog post error: " . $e->getMessage());
    redirect(BASE_URL . 'admin/blog-posts.php', 'error', 'Failed to delete blog post');
}
