<?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';

$title = trim((string)($_POST['title'] ?? ''));
$category = trim((string)($_POST['category'] ?? ''));
$author = trim((string)($_POST['author'] ?? ''));
$day = trim((string)($_POST['day'] ?? ''));
$month = trim((string)($_POST['month'] ?? ''));

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

$connection->query("CREATE TABLE IF NOT EXISTS blogs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    category VARCHAR(120) NOT NULL,
    author VARCHAR(120) NOT NULL,
    day VARCHAR(10) NOT NULL,
    month VARCHAR(30) NOT NULL,
    image_path VARCHAR(500) NOT NULL,
    content TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

if (!isset($_FILES['image']) || (int)($_FILES['image']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
    echo json_encode(['success' => false, 'message' => 'Image upload is required']);
    exit;
}

$file = $_FILES['image'];
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
$mimeType = (string)($file['type'] ?? '');
$fileSize = (int)($file['size'] ?? 0);

if (!in_array($mimeType, $allowedTypes, true)) {
    echo json_encode(['success' => false, 'message' => 'Invalid file type. Only JPEG, PNG, GIF, and WebP are allowed']);
    exit;
}

if ($fileSize <= 0 || $fileSize > 5 * 1024 * 1024) {
    echo json_encode(['success' => false, 'message' => 'File size exceeds 5MB limit']);
    exit;
}

$ext = strtolower((string)pathinfo((string)($file['name'] ?? ''), PATHINFO_EXTENSION));
if ($ext === '') {
    $ext = 'jpg';
}

$uploadDir = __DIR__ . '/assets/img/blog/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

$filename = 'blog-' . time() . '-' . bin2hex(random_bytes(4)) . '.' . $ext;
$targetPath = $uploadDir . $filename;

if (!move_uploaded_file((string)$file['tmp_name'], $targetPath)) {
    echo json_encode(['success' => false, 'message' => 'Failed to upload image']);
    exit;
}

$imagePath = 'assets/img/blog/' . $filename;

$stmt = $connection->prepare('INSERT INTO blogs (title, category, author, day, month, image_path, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())');
if (!$stmt) {
    @unlink($targetPath);
    echo json_encode(['success' => false, 'message' => 'Failed to prepare insert']);
    exit;
}

$stmt->bind_param('ssssss', $title, $category, $author, $day, $month, $imagePath);
$ok = $stmt->execute();
$stmt->close();

if (!$ok) {
    @unlink($targetPath);
    echo json_encode(['success' => false, 'message' => 'Failed to save blog post']);
    exit;
}

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