<?php
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

require_once __DIR__ . '/config/db.php';

$blogId = (int)($_POST['blog_id'] ?? 0);
if ($blogId <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid blog ID']);
    exit;
}

$findStmt = $connection->prepare('SELECT image_path FROM blogs WHERE id = ? LIMIT 1');
if (!$findStmt) {
    echo json_encode(['success' => false, 'message' => 'Failed to prepare select']);
    exit;
}
$findStmt->bind_param('i', $blogId);
$findStmt->execute();
$findResult = $findStmt->get_result();
if (!$findResult || !$findResult->num_rows) {
    $findStmt->close();
    echo json_encode(['success' => false, 'message' => 'Blog post not found']);
    exit;
}
$row = $findResult->fetch_assoc();
$imagePath = (string)($row['image_path'] ?? '');
$findStmt->close();

$deleteStmt = $connection->prepare('DELETE FROM blogs WHERE id = ?');
if (!$deleteStmt) {
    echo json_encode(['success' => false, 'message' => 'Failed to prepare delete']);
    exit;
}
$deleteStmt->bind_param('i', $blogId);
$deleteStmt->execute();
$affected = $deleteStmt->affected_rows;
$deleteStmt->close();

if ($affected <= 0) {
    echo json_encode(['success' => false, 'message' => 'Blog post not found']);
    exit;
}

$fullImagePath = __DIR__ . '/' . ltrim($imagePath, '/');
if ($imagePath !== '' && strpos($imagePath, 'assets/img/blog/') === 0 && file_exists($fullImagePath)) {
    @unlink($fullImagePath);
}

echo json_encode(['success' => true, 'message' => 'Blog post deleted successfully']);
?>
