<?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
$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']) : '';

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

// Handle image upload
$image_path = '';
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;
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to upload image']);
        exit;
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Image upload is required']);
    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);

// Create new blog post HTML with proper formatting
$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;

// Find the insertion point - before the col-xxl-4 div
// Look for the pattern where blog grid ends and sidebar column begins
if (preg_match('/(.*?<div\s+class="row">.*?)(\s*<\/div>\s*<\/div>\s*<div\s+class="col-xxl-4)/s', $html_content, $matches)) {
    // Insert new blog post before the closing divs
    $html_content = $matches[1] . "\n" . $new_blog_post . $matches[2];
    
    // Write updated content back to file
    if (file_put_contents($blog_file, $html_content)) {
        echo json_encode(['success' => true, 'message' => 'Blog post added successfully']);
    } else {
        // Clean up uploaded image on failure
        @unlink($upload_path);
        echo json_encode(['success' => false, 'message' => 'Failed to update blog file']);
    }
} else {
    // Clean up uploaded image on failure
    @unlink($upload_path);
    echo json_encode(['success' => false, 'message' => 'Failed to locate blog post section']);
}
?>
