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

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

// Get POST data
$blog_id = isset($_POST['blog_id']) ? intval($_POST['blog_id']) : 0;

// Validate input
if ($blog_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid blog ID']);
    exit;
}

// Read blog-grid-sidebar.html file
$blog_file = __DIR__ . '/blog-grid-sidebar.html';

if (!file_exists($blog_file)) {
    echo json_encode(['success' => false, 'message' => 'Blog file not found']);
    exit;
}

$html_content = file_get_contents($blog_file);

// Extract all blog posts to find the one to delete
// Use a simpler, more flexible regex that matches the entire blog post div
if (preg_match_all('/<div\s+class="col-xl-6">.*?<\/div>\s*<\/div>\s*<\/div>/s', $html_content, $matches)) {
    
    if ($blog_id > count($matches[0])) {
        echo json_encode(['success' => false, 'message' => 'Blog post not found']);
        exit;
    }
    
    // Get the blog post HTML
    $blog_post_html = $matches[0][$blog_id - 1];
    
    // Extract image path from the blog post HTML
    $image_path = '';
    if (preg_match('/<img\s+src="([^"]+)"[^>]*>/s', $blog_post_html, $img_matches)) {
        $image_path = $img_matches[1];
    }
    
    // Delete the image file
    if (!empty($image_path)) {
        $full_image_path = __DIR__ . '/' . $image_path;
        if (file_exists($full_image_path)) {
            @unlink($full_image_path);
        }
    }
    
    // Remove the blog post HTML
    $html_content = str_replace($blog_post_html, '', $html_content);
    
    // Write updated content back to file
    if (file_put_contents($blog_file, $html_content)) {
        echo json_encode(['success' => true, 'message' => 'Blog post deleted successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to update blog file']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to parse blog posts']);
}
?>
