<?php
declare(strict_types=1);

require_once __DIR__ . '/../../security/auth_guard.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';
require_once __DIR__ . '/../../core/Validator.php';
require_once __DIR__ . '/../../core/Logger.php';

$db = Database::getInstance();
$data = json_decode(file_get_contents('php://input'), true);

/**
 * Required fields
 */
Validator::required($data, [
    'title',
    'content',
    'category_ids',
    'tag_ids'
]);

/**
 * Role check (SEO Manager + Admin)
 */
$stmt = $db->prepare("
    SELECT r.name
    FROM roles r
    JOIN employees e ON e.role_id = r.id
    WHERE e.id = :id
");
$stmt->execute(['id' => $_SESSION['employee_id']]);
$role = $stmt->fetch();

if (!$role || !in_array($role['name'], ['Super Admin', 'Admin', 'SEO Manager'], true)) {
    Response::error('You are not authorized to create blogs', 403);
}

/**
 * Slug generator
 */
function blogSlug(string $title): string
{
    $slug = strtolower($title);
    $slug = preg_replace('/[^a-z0-9]+/', '-', $slug);
    return trim($slug, '-');
}

require_once __DIR__ . '/../../core/Slug.php';
$slug = Slug::make($data['title']);

/**
 * Ensure unique slug
 */
$stmt = $db->prepare("SELECT id FROM blogs WHERE slug = :slug");
$stmt->execute(['slug' => $slug]);
if ($stmt->fetch()) {
    Response::error('Blog with same title already exists', 409);
}

/**
 * Validate categories
 */
foreach ($data['category_ids'] as $catId) {
    $stmt = $db->prepare("
        SELECT id FROM blog_categories
        WHERE id = :id AND status = 'Active'
    ");
    $stmt->execute(['id' => $catId]);
    if (!$stmt->fetch()) {
        Response::error('Invalid blog category', 422);
    }
}

/**
 * Validate tags
 */
foreach ($data['tag_ids'] as $tagId) {
    $stmt = $db->prepare("
        SELECT id FROM blog_tags
        WHERE id = :id AND status = 'Active'
    ");
    $stmt->execute(['id' => $tagId]);
    if (!$stmt->fetch()) {
        Response::error('Invalid blog tag', 422);
    }
}

/**
 * Transaction start
 */
$db->beginTransaction();

try {

    /**
     * Insert blog
     */
    $stmt = $db->prepare("
        INSERT INTO blogs (
            title,
            slug,
            excerpt,
            content,
            author_name,
            status,
            approval_status,
            created_by,
            created_at
        ) VALUES (
            :title,
            :slug,
            :excerpt,
            :content,
            'King Koil India',
            'Draft',
            'Pending',
            :created_by,
            NOW()
        )
    ");

    $stmt->execute([
        'title'      => trim($data['title']),
        'slug'       => $slug,
        'excerpt'    => $data['excerpt'] ?? null,
        'content'    => $data['content'],
        'created_by' => $_SESSION['employee_id']
    ]);

    $blogId = (int)$db->lastInsertId();

    /**
     * Map categories
     */
    $stmt = $db->prepare("
        INSERT INTO blog_category_map (blog_id, category_id)
        VALUES (:blog_id, :category_id)
    ");

    foreach ($data['category_ids'] as $catId) {
        $stmt->execute([
            'blog_id'     => $blogId,
            'category_id' => $catId
        ]);
    }

    /**
     * Map tags
     */
    $stmt = $db->prepare("
        INSERT INTO blog_tag_map (blog_id, tag_id)
        VALUES (:blog_id, :tag_id)
    ");

    foreach ($data['tag_ids'] as $tagId) {
        $stmt->execute([
            'blog_id' => $blogId,
            'tag_id'  => $tagId
        ]);
    }

    $db->commit();

} catch (Throwable $e) {
    $db->rollBack();
    Response::error('Failed to create blog', 500);
}

Logger::auth('Blog created', [
    'blog_id' => $blogId,
    'by'      => $_SESSION['employee_id']
]);

Response::success('Blog created successfully', [
    'blog_id' => $blogId,
    'slug'    => $slug
]);
