<?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);
$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 ($blogId <= 0 || $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");

$currentImage = '';
$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;
}
$current = $findResult->fetch_assoc();
$currentImage = (string)($current['image_path'] ?? '');
$findStmt->close();

$newImage = $currentImage;
if (isset($_FILES['image']) && (int)($_FILES['image']['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_OK) {
    $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;
    }

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

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

$updateStmt = $connection->prepare('UPDATE blogs SET title = ?, category = ?, author = ?, day = ?, month = ?, image_path = ? WHERE id = ?');
if (!$updateStmt) {
    echo json_encode(['success' => false, 'message' => 'Failed to prepare update']);
    exit;
}
$updateStmt->bind_param('ssssssi', $title, $category, $author, $day, $month, $newImage, $blogId);
$ok = $updateStmt->execute();
$updateStmt->close();

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

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