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

/**
 * faq_id is mandatory
 */
Validator::required($data, ['faq_id']);
$faqId = (int)$data['faq_id'];

/**
 * Check FAQ exists
 */
$stmt = $db->prepare("SELECT id FROM faqs WHERE id = :id");
$stmt->execute(['id' => $faqId]);
if (!$stmt->fetch()) {
    Response::error('FAQ not found', 404);
}

$fields = [];
$params = [
    'id'         => $faqId,
    'updated_by'=> $_SESSION['employee_id']
];

/**
 * Question update → regenerate slug
 */
if (isset($data['question']) && trim($data['question']) !== '') {

    $question = trim($data['question']);
    Validator::minLength($question, 5, 'question');

    $slug = Slug::make($question);

    $stmt = $db->prepare("
        SELECT id FROM faqs
        WHERE slug = :slug AND id != :id
    ");
    $stmt->execute([
        'slug' => $slug,
        'id'   => $faqId
    ]);

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

    $fields[]          = 'question = :question';
    $fields[]          = 'slug = :slug';
    $params['question'] = $question;
    $params['slug']     = $slug;
}

/**
 * Answer update
 */
if (isset($data['answer']) && trim($data['answer']) !== '') {

    $answer = trim($data['answer']);
    Validator::minLength($answer, 10, 'answer');

    $fields[]         = 'answer = :answer';
    $params['answer'] = $answer;
}

/**
 * Status update
 */
if (isset($data['status'])) {

    $allowed = ['Active', 'Inactive', 'Draft'];

    if (!in_array($data['status'], $allowed, true)) {
        Response::error('Invalid status value', 422);
    }

    $fields[]        = 'status = :status';
    $params['status'] = $data['status'];
}

/**
 * Published date update
 */
if (isset($data['published_at']) && trim($data['published_at']) !== '') {

    $fields[]               = 'published_at = :published_at';
    $params['published_at'] = trim($data['published_at']);
}

/**
 * Category update (replace mapping)
 */
$updateCategories = false;

if (isset($data['category_ids'])) {

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

    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);
        }
    }

    $updateCategories = true;
}

/**
 * Nothing to update
 */
if (empty($fields) && !$updateCategories) {
    Response::error('No valid fields provided for update', 422);
}

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

try {

    /**
     * Update FAQ core
     */
    if (!empty($fields)) {

        $sql = "
            UPDATE faqs
            SET " . implode(', ', $fields) . ",
                updated_by = :updated_by,
                updated_at = NOW()
            WHERE id = :id
        ";

        $stmt = $db->prepare($sql);
        $stmt->execute($params);
    }

    /**
     * Replace categories
     */
    if ($updateCategories) {

        $stmt = $db->prepare("
            DELETE FROM faq_category_map
            WHERE faq_id = :faq_id
        ");
        $stmt->execute(['faq_id' => $faqId]);

        $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 update FAQ', 500);
}

Response::success('FAQ updated successfully');
