<?php
declare(strict_types=1);

require_once __DIR__ . '/../security/auth_guard.php';
require_once __DIR__ . '/../partials/main.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>

<?php includeFileWithVariables('../partials/title-meta.php', ['title' => 'Create FAQ']); ?>

<link rel="stylesheet" href="<?= ADMIN_BASE_URL ?>assets/libs/quill/quill.snow.css">
<link rel="stylesheet" href="<?= ADMIN_BASE_URL ?>assets/libs/choices.js/public/assets/styles/choices.min.css">
<?php include '../partials/head-css.php'; ?>

</head>

<body>
<div id="layout-wrapper">

<?php include '../partials/header.php'; ?>
<?php include '../partials/sidebar.php'; ?>
<?php include '../partials/horizontal.php'; ?>

<main class="app-wrapper">
<div class="container-fluid">

<?php includeFileWithVariables('../partials/page-title.php', [
    'title_sub' => 'CMS',
    'title'     => 'Create FAQ'
]); ?>

<div class="row">
<div class="col-12">

<div class="card">
<div class="card-header">
    <h6 class="card-title">New FAQ</h6>
</div>

<div class="card-body">
<div class="row g-4">

<!-- QUESTION -->
<div class="col-xl-6">
<label class="form-label">
    Question <span class="text-danger">*</span>
</label>
<input id="question"
       class="form-control"
       placeholder="Enter FAQ question">
</div>

<!-- SLUG -->
<div class="col-xl-6">
<label class="form-label">Slug (Auto Generated)</label>
<input id="slug"
       class="form-control bg-light"
       readonly
       placeholder="slug-will-appear-here">
</div>

<!-- CATEGORIES -->
<div class="col-xl-6">
<label class="form-label">
    FAQ Categories <span class="text-danger">*</span>
</label>
<select id="categories" class="form-select" multiple></select>
</div>

<!-- ANSWER -->
<div class="col-12">
<label class="form-label">
    Answer <span class="text-danger">*</span>
</label>
<div id="editor" style="height:300px"></div>
</div>

<!-- ACTIONS -->
<div class="col-12 text-end mt-3">
<button class="btn btn-light" onclick="resetForm()">Reset</button>
<button class="btn btn-primary" onclick="createFaq()">Create FAQ</button>
</div>

<!-- MESSAGE -->
<div class="col-12">
<div id="msg"></div>
</div>

</div>
</div>
</div>

</div>
</div>
</main>

<?php include '../partials/footer.php'; ?>
</div>

<?php include '../partials/vendor-scripts.php'; ?>
<script src="<?= ADMIN_BASE_URL ?>assets/libs/quill/quill.js"></script>
<script src="<?= ADMIN_BASE_URL ?>assets/libs/choices.js/public/assets/scripts/choices.min.js"></script>

<script>
/* ================= GLOBALS ================= */
const ADMIN = "<?= ADMIN_BASE_URL ?>";
let CSRF_TOKEN = null;
let quill;
let categoryChoice;

/* ================= CSRF ================= */
fetch(`${ADMIN}security/csrf.php`, { credentials: 'include' })
.then(r => r.json())
.then(j => CSRF_TOKEN = j.data.csrf_token);

/* ================= INIT ================= */
document.addEventListener('DOMContentLoaded', async () => {

    quill = new Quill('#editor', { theme: 'snow' });

    categoryChoice = new Choices('#categories', {
        removeItemButton: true,
        shouldSort: false
    });

    loadCategories();
});

/* ================= SLUG ================= */
question.addEventListener('input', () => {
    slug.value = question.value.toLowerCase()
        .replace(/[^a-z0-9]+/g, '-')
        .replace(/^-|-$/g, '');
});

/* ================= LOAD CATEGORIES ================= */
async function loadCategories() {

    const res = await fetch(
        `${ADMIN}api/faqs/categories/list.php?context=backend`,
        { credentials: 'include' }
    ).then(r => r.json());

    if (res.status !== 'success') return;

    res.data.forEach(c => {
        categoryChoice.setChoices([
            { value: c.id, label: c.name }
        ], 'value', 'label', false);
    });
}

/* ================= CREATE FAQ ================= */
function createFaq() {

    if (!CSRF_TOKEN) {
        msg.innerHTML = `<div class="alert alert-danger">
            Security token not ready
        </div>`;
        return;
    }

    const payload = {
        question: question.value.trim(),
        answer: quill.root.innerHTML.trim(),
        category_ids: categoryChoice.getValue(true)
    };

    if (
        !payload.question ||
        !payload.answer ||
        !payload.category_ids.length
    ) {
        msg.innerHTML = `<div class="alert alert-danger">
            Please fill all required fields
        </div>`;
        return;
    }

    fetch(`${ADMIN}api/faqs/create.php`, {
        method: 'POST',
        credentials: 'include',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': CSRF_TOKEN
        },
        body: JSON.stringify(payload)
    })
    .then(r => r.json())
    .then(r => {

        if (r.status === 'success') {

            msg.innerHTML = `<div class="alert alert-success">
                FAQ created successfully
            </div>`;

            setTimeout(() => {
                window.location.href = `${ADMIN}faq/list.php`;
            }, 1200);

        } else {
            msg.innerHTML = `<div class="alert alert-danger">
                ${r.message || 'Failed to create FAQ'}
            </div>`;
        }
    })
    .catch(() => {
        msg.innerHTML = `<div class="alert alert-danger">
            Server error. Please try again.
        </div>`;
    });
}

/* ================= RESET ================= */
function resetForm() {
    question.value = '';
    slug.value = '';
    quill.root.innerHTML = '';
    categoryChoice.removeActiveItems();
    msg.innerHTML = '';
}
</script>

</body>
</html>
