<?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 Category']); ?>

<link rel="stylesheet" href="<?= ADMIN_BASE_URL ?>assets/libs/quill/quill.snow.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' => 'Catalog',
    'title'     => 'Create Category'
]); ?>

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

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

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

<!-- CATEGORY NAME -->
<div class="col-xl-6">
<label class="form-label">
    Category Name <span class="text-danger">*</span>
</label>
<input id="category_name"
       class="form-control"
       placeholder="Enter category name">
</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>

<!-- SHORT DESCRIPTION -->
<div class="col-12">
<label class="form-label">Short Description</label>
<input id="short_description"
       class="form-control"
       maxlength="255"
       placeholder="Short summary (max 255 characters)">
</div>

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

<hr class="my-3">

<!-- SEO -->
<div class="col-xl-6">
<label class="form-label">Meta Title</label>
<input id="meta_title" class="form-control">
</div>

<div class="col-xl-6">
<label class="form-label">Meta Keywords</label>
<input id="meta_keywords" class="form-control">
</div>

<div class="col-12">
<label class="form-label">Meta Description</label>
<textarea id="meta_description" class="form-control" rows="2"></textarea>
</div>

<!-- AI SUMMARY -->
<div class="col-12">
<label class="form-label">AI Summary</label>
<textarea id="ai_summary" class="form-control" rows="2"></textarea>
</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="createCategory()">Create Category</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>
/* ================= GLOBALS ================= */
const ADMIN = "<?= ADMIN_BASE_URL ?>";
let CSRF_TOKEN = null;
let quill;

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

/* ================= INIT ================= */
document.addEventListener('DOMContentLoaded', () => {
    quill = new Quill('#editor', { theme: 'snow' });
});

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

/* ================= CREATE ================= */
function createCategory() {

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

    const payload = {
        category_name: category_name.value.trim(),
        short_description: short_description.value.trim() || null,
        description: quill.root.innerHTML.trim(),
        meta_title: meta_title.value.trim() || null,
        meta_description: meta_description.value.trim() || null,
        meta_keywords: meta_keywords.value.trim() || null,
        ai_summary: ai_summary.value.trim() || null
    };

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

    fetch(`${ADMIN}api/retail-categories/create.php`, {
        method: 'POST',
        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">
                Category created successfully
            </div>`;

            setTimeout(() => {
                window.location.href = `${ADMIN}retail-products/categories.php`;
            }, 1200);

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

/* ================= RESET ================= */
function resetForm() {
    category_name.value = '';
    slug.value = '';
    short_description.value = '';
    meta_title.value = '';
    meta_description.value = '';
    meta_keywords.value = '';
    ai_summary.value = '';
    quill.root.innerHTML = '';
    msg.innerHTML = '';
}
</script>

</body>
</html>
