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

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

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

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

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

<!-- BLOG TITLE -->
<div class="col-xl-6">
<label class="form-label">
    Blog Title <span class="text-danger">*</span>
</label>
<input id="title"
       class="form-control"
       placeholder="Enter blog title">
</div>

<!-- SLUG (READ ONLY) -->
<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">
    Blog Categories <span class="text-danger">*</span>
</label>
<select id="categories" class="form-select" multiple></select>
</div>

<!-- TAGS -->
<div class="col-xl-6">
<label class="form-label">
    Blog Tags <span class="text-danger">*</span>
</label>
<select id="tags" class="form-select" multiple></select>
</div>

<!-- EXCERPT -->
<div class="col-12">
<label class="form-label">Blog Excerpt</label>
<textarea id="excerpt"
          rows="3"
          class="form-control"
          placeholder="Short summary (optional)"></textarea>
</div>

<!-- CONTENT -->
<div class="col-12">
<label class="form-label">
    Blog Content <span class="text-danger">*</span>
</label>
<div id="editor" style="height:400px"></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="createBlog()">Create Blog</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, tagChoice;

/* ================= CSRF ================= */
fetch(`${ADMIN}security/csrf.php`)
.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 });
    tagChoice = new Choices('#tags', { removeItemButton: true });

    loadCategories();
    loadTags();
});

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

/* ================= LOAD CATEGORIES ================= */
async function loadCategories(){
    const r = await fetch(`${ADMIN}api/blogs/categories/list.php?context=backend`)
                    .then(r=>r.json());

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

/* ================= LOAD TAGS ================= */
async function loadTags(){
    const r = await fetch(`${ADMIN}api/blogs/tags/list.php?context=backend`)
                    .then(r=>r.json());

    r.data.forEach(t => {
        tagChoice.setChoices([
            { value: t.id, label: t.name }
        ], 'value', 'label', false);
    });
}

/* ================= CREATE BLOG ================= */
function createBlog(){

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

    const payload = {
        title: title.value.trim(),
        excerpt: excerpt.value.trim() || null,
        content: quill.root.innerHTML.trim(),
        category_ids: categoryChoice.getValue(true),
        tag_ids: tagChoice.getValue(true)
    };

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

    fetch(`${ADMIN}api/blogs/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">
                Blog successfully created
            </div>`;

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

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

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

</body>
</html>
