<?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/Slug.php';


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

/**
 * Required fields
 */
Validator::required($data, [
    'question',
    'answer',
    'category_ids'
]);

if (!is_array($data['category_ids']) || empty($data['category_ids'])) {
    Response::error('category_ids must be a non-empty array', 422);
}

$question = trim($data['question']);
$answer   = trim($data['answer']);

/**
 * Generate slug (FIXED, CENTRALIZED)
 */
$slug = Slug::make($question);

/**
 * Ensure unique slug
 */
$stmt = $db->prepare("SELECT id FROM faqs WHERE slug = :slug");
$stmt->execute(['slug' => $slug]);

if ($stmt->fetch()) {
    Response::error('FAQ with similar question already exists', 409);
}

/**
 * Validate categories
 */
foreach ($data['category_ids'] as $catId) {
    Validator::int($catId, 'category_id');

    $stmt = $db->prepare("
        SELECT id FROM faq_categories
        WHERE id = :id AND status = 'Active'
    ");
    $stmt->execute(['id' => $catId]);

    if (!$stmt->fetch()) {
        Response::error('Invalid FAQ category', 422);
    }
}

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

try {

    /**
     * Insert FAQ
     */
    $stmt = $db->prepare("
        INSERT INTO faqs (
            question,
            slug,
            answer,
            status,
            approval_status,
            created_by,
            created_at
        ) VALUES (
            :question,
            :slug,
            :answer,
            'Draft',
            'Pending',
            :created_by,
            NOW()
        )
    ");

    $stmt->execute([
        'question'   => $question,
        'slug'       => $slug,
        'answer'     => $answer,
        'created_by' => $_SESSION['employee_id']
    ]);

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

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

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

    $db->commit();

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

Response::success('FAQ created successfully', [
    'faq_id' => $faqId,
    'slug'   => $slug
]);
