<?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;
$title = isset($_POST['title']) ? trim($_POST['title']) : '';
$category = isset($_POST['category']) ? trim($_POST['category']) : '';
$author = isset($_POST['author']) ? trim($_POST['author']) : '';
$day = isset($_POST['day']) ? trim($_POST['day']) : '';
$month = isset($_POST['month']) ? trim($_POST['month']) : '';
$old_image = isset($_POST['old_image']) ? trim($_POST['old_image']) : '';

// Validate input
if ($blog_id <= 0 || empty($title) || empty($category) || empty($author) || empty($day) || empty($month)) {
    echo json_encode(['success' => false, 'message' => 'All fields are required']);
    exit;
}

// Handle image upload (optional for edit)
$image_path = $old_image;

if (isset($_FILES['image']) && $_FILES['image']['error'] == UPLOAD_ERR_OK) {
    $file = $_FILES['image'];
    $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    $max_size = 5 * 1024 * 1024; // 5MB
    
    // Validate file type
    if (!in_array($file['type'], $allowed_types)) {
        echo json_encode(['success' => false, 'message' => 'Invalid file type. Only JPEG, PNG, GIF, and WebP are allowed']);
        exit;
    }
    
    // Validate file size
    if ($file['size'] > $max_size) {
        echo json_encode(['success' => false, 'message' => 'File size exceeds 5MB limit']);
        exit;
    }
    
    // Generate unique filename
    $file_ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    $filename = 'blog-grid-' . time() . '-' . rand(1000, 9999) . '.' . $file_ext;
    $upload_dir = __DIR__ . '/assets/img/blog/';
    
    // Create directory if it doesn't exist
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }
    
    $upload_path = $upload_dir . $filename;
    
    // Move uploaded file
    if (move_uploaded_file($file['tmp_name'], $upload_path)) {
        $image_path = 'assets/img/blog/' . $filename;
        
        // Delete old image if it exists
        if (!empty($old_image)) {
            $old_path = __DIR__ . '/' . $old_image;
            if (file_exists($old_path)) {
                @unlink($old_path);
            }
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to upload image']);
        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 update
// 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 old blog post HTML
    $old_blog_post = $matches[0][$blog_id - 1];
    
    // Create updated blog post HTML
    $new_blog_post = <<<HTML
<div class="col-xl-6">
                            <div class="th-blog blog-single has-post-thumbnail single-grid">
                                <div class="blog-img global-img"><a href="blog-details.html"><img src="$image_path" alt="Blog Image"></a></div>
                                <div class="blog-content">
                                    <div class="blog-meta"><a href="blog.html">$category</a> <a class="author" href="blog.html">by $author</a></div>
                                    <h2 class="box-title"><a href="blog-details.html">$title</a></h2>
                                    <div class="btn-group justify-content-between"><a href="contact.html" class="th-btn th-border">Read More</a>
                                        <div class="blog-date"><span class="date">$day</span> <span class="month">$month</span></div>
                                    </div>
                                </div>
                            </div>
                        </div>
HTML;
    
    // Replace the old post with new one
    $html_content = str_replace($old_blog_post, $new_blog_post, $html_content);
    
    // Write updated content back to file
    if (file_put_contents($blog_file, $html_content)) {
        echo json_encode(['success' => true, 'message' => 'Blog post updated successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to update blog file']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to locate blog posts']);
}
?>
