<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

require_once 'connect.php';
function createSlug($title)
{
    $slug = strtolower($title);
    $slug = preg_replace('/[^a-z0-9\s-]/', '', $slug);
    $slug = preg_replace('/\s+/', '-', $slug);
    $slug = preg_replace('/-+/', '-', $slug);
    $slug = trim($slug, '-');

    return empty($slug) ? 'post' : $slug;
}
try {
    $conn = getDatabaseConnection();

    // Get form data
    $title = $_POST['title'] ?? '';
    $content = $_POST['content'] ?? '';
    $category = $_POST['category'] ?? ''; //default category for the blog
    $categories = isset($_POST['categories']) ? json_decode($_POST['categories'], true) : [];
    $tags = isset($_POST['tags']) ? json_decode($_POST['tags'], true) : [];
    $blog_type = $_POST['blog_type'] ?? '';
    $status = $_POST['status'] ?? '';


    if (empty($_FILES['cover_image']['name']) || $_FILES['cover_image']['error'] !== UPLOAD_ERR_OK) {
        throw new Exception("Cover image is required", 400);
    }

    // Handle file upload
    $target_dir = "uploads/";
    if (!file_exists($target_dir)) {
        if (!mkdir($target_dir, 0755, true)) {
            throw new Exception("Failed to create uploads directory");
        }
    }

    $filename = time() . '_' . basename($_FILES['cover_image']['name']);
    $target_file = $target_dir . $filename;

    // Validate file type
    $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
    $file_type = mime_content_type($_FILES['cover_image']['tmp_name']);
    if (!in_array($file_type, $allowed_types)) {
        throw new Exception("Invalid file type. Only JPG, PNG, and GIF are allowed.");
    }

    if (!move_uploaded_file($_FILES['cover_image']['tmp_name'], $target_file)) {
        throw new Exception("File upload failed");
    }

    $cover_image = $filename;

    $slug = createSlug($title);

    $conn->beginTransaction();

    try {
        // Insert blog data
        $query = "INSERT INTO blogs (title, slug, content, category, blog_type, cover_image, status, created_at) 
                  VALUES (:title, :slug, :content, :category, :blog_type, :cover_image, :status, NOW())";
        $stmt = $conn->prepare($query);
        $stmt->bindParam(':title', $title);
        $stmt->bindParam(':slug', $slug);
        $stmt->bindParam(':content', $content);
        $stmt->bindParam(':category', $category, PDO::PARAM_INT);
        $stmt->bindParam(':blog_type', $blog_type);
        $stmt->bindParam(':cover_image', $cover_image);
        $stmt->bindParam(':status', $status);

        if (!$stmt->execute()) {
            throw new Exception("Failed to insert blog post");
        }

        $blog_id = $conn->lastInsertId();

        // Insert tags if provided
        if (!empty($tags) && is_array($tags)) {
            $placeholders = [];
            $values = [];
            foreach ($tags as $tag_id) {
                $placeholders[] = '(?, ?)';
                $values[] = $blog_id;
                $values[] = $tag_id;
            }

            $tagQuery = "INSERT INTO blog_tags (blog_id, tag_id) VALUES " . implode(', ', $placeholders);
            $tagStmt = $conn->prepare($tagQuery);

            if (!$tagStmt->execute($values)) {
                throw new Exception("Failed to insert tags");
            }
        }
        if (!empty($categories) && is_array($categories)) {
            $placeholders = [];
            $values = [];
            foreach ($categories as $category_id) {
                $placeholders[] = '(?, ?)';
                $values[] = $blog_id;
                $values[] = $category_id;
            }

            $categoryQuery = "INSERT INTO categories_blog (blog_id, category_id) VALUES " . implode(', ', $placeholders);
            $categoryStmt = $conn->prepare($categoryQuery);

            if (!$categoryStmt->execute($values)) {
                throw new Exception("Failed to insert categories");
            }
        }

        $conn->commit();

        echo json_encode([
            "success" => true,
            "message" => "Blog created successfully",
            "blog_id" => $blog_id,
            // "cover_image" => $cover_image 
        ]);
    } catch (Exception $e) {
        $conn->rollBack();
        throw $e;
    }
} catch (PDOException $e) {
    if ($e->getCode() == 23000) {
        http_response_code(400);
        echo json_encode([
            "success" => false,
            "message" => "Change title — a blog with this title already exists!"
        ]);
    } else {
        http_response_code(500);
        echo json_encode([
            "success" => false,
            "message" => "Database error: " . $e->getMessage()
        ]);
    }
} catch (Exception $e) {
    http_response_code($e->getCode() ?: 400);
    echo json_encode([
        "success" => false,
        "message" => $e->getMessage()
    ]);
}
