<?php
declare(strict_types=1);

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

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

<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' => 'CMS',
    'title'     => 'Create Page'
]); ?>

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

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

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

<!-- PAGE TITLE -->
<div class="col-md-6">
<label class="form-label">
    Page Title <span class="text-danger">*</span>
</label>
<input id="title" class="form-control" placeholder="Enter page title">
</div>

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

<!-- PAGE TYPE -->
<div class="col-md-4">
<label class="form-label">Page Type</label>
<select id="page_type" class="form-select">
<option value="static">Static</option>
<option value="landing">Landing</option>
<option value="policy">Policy</option>
<option value="system">System</option>
</select>
</div>

<!-- TEMPLATE -->
<div class="col-md-4">
<label class="form-label">Template</label>
<input id="template" class="form-control" value="default">
</div>

<!-- SHOW IN MENU -->
<div class="col-md-4">
<label class="form-label">Show in Menu</label>
<select id="show_in_menu" class="form-select">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
</div>

<!-- MENU TITLE -->
<div class="col-md-6">
<label class="form-label">Menu Title</label>
<input id="menu_title" class="form-control" placeholder="Optional">
</div>

<!-- MENU ORDER -->
<div class="col-md-3">
<label class="form-label">Menu Order</label>
<input id="menu_order" type="number" class="form-control">
</div>

<!-- PARENT PAGE -->
<div class="col-md-3">
<label class="form-label">Parent Page ID</label>
<input id="parent_page_id" type="number" class="form-control">
</div>

<!-- SHORT DESCRIPTION -->
<div class="col-12">
<label class="form-label">Short Description</label>
<textarea id="short_description" rows="3" class="form-control"></textarea>
</div>

<!-- CONTENT -->
<div class="col-12">
<label class="form-label">
    Page Content <span class="text-danger">*</span>
</label>
<div id="editor" style="height:400px"></div>
</div>

<!-- FLAGS -->
<div class="col-md-3">
<label class="form-label">System Page</label>
<select id="is_system_page" class="form-select">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
</div>

<div class="col-md-3">
<label class="form-label">Indexable</label>
<select id="is_indexable" class="form-select">
<option value="1">Yes</option>
<option value="0">No</option>
</select>
</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="createPage()">Create Page</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>
const ADMIN = "<?= ADMIN_BASE_URL ?>";
let CSRF_TOKEN = null;
let quill;

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

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

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

/* CREATE PAGE */
function createPage(){

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

    const payload = {
        title: title.value.trim(),
        content: quill.root.innerHTML.trim(),
        page_type: page_type.value,
        template: template.value,
        short_description: short_description.value.trim() || null,
        show_in_menu: parseInt(show_in_menu.value),
        menu_title: menu_title.value.trim() || null,
        menu_order: menu_order.value || null,
        parent_page_id: parent_page_id.value || null,
        is_system_page: parseInt(is_system_page.value),
        is_indexable: parseInt(is_indexable.value)
    };

    if (!payload.title || !payload.content) {
        msg.innerHTML = `<div class="alert alert-danger">
            Title and Content are required
        </div>`;
        return;
    }

    fetch(`${ADMIN}api/pages/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">
                Page created successfully
            </div>`;
            setTimeout(()=>{
                window.location.href = `${ADMIN}pages/list.php`;
            },1200);
        } else {
            msg.innerHTML = `<div class="alert alert-danger">${r.message}</div>`;
        }
    })
    .catch(()=>{
        msg.innerHTML = `<div class="alert alert-danger">
            Server error. Please try again.
        </div>`;
    });
}

/* RESET */
function resetForm(){
    title.value='';
    slug.value='';
    short_description.value='';
    quill.root.innerHTML='';
    menu_title.value='';
    menu_order.value='';
    parent_page_id.value='';
    msg.innerHTML='';
}
</script>

</body>
</html>
