<?php
declare(strict_types=1);

require_once __DIR__ . '/../security/auth_guard_web.php';
require_once __DIR__ . '/../partials/main.php';
require_once __DIR__ . '/../config/database.php';

$pageId = (int)($_GET['id'] ?? 0);
if ($pageId <= 0) {
    die('Invalid page ID');
}

/* Role check */
$db = Database::getInstance();
$stmt = $db->prepare("
    SELECT r.name
    FROM roles r
    JOIN employees e ON e.role_id = r.id
    WHERE e.id = :id
");
$stmt->execute(['id' => $_SESSION['employee_id']]);
$role = $stmt->fetchColumn();
$isAdmin = in_array($role, ['Admin', 'Super Admin'], true);
?>
<!DOCTYPE html>
<html lang="en">
<head>

<?php includeFileWithVariables('../partials/title-meta.php', ['title' => 'Edit Page']); ?>
<link rel="stylesheet" href="<?= ADMIN_BASE_URL ?>assets/libs/quill/quill.snow.css">
<?php include '../partials/head-css.php'; ?>

<style>
.page-featured-thumb{
    height:200px;
    object-fit:contain;
    background:#f8f9fa;
}
</style>
</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'     => 'Edit Page'
]); ?>

<div class="row">

<!-- ================= LEFT ================= -->
<div class="col-xl-8">

<div class="card mb-3">
<div class="card-header d-flex justify-content-between">
<h6>Page Core</h6>
<a href="<?= ADMIN_BASE_URL ?>pages/list.php" class="btn btn-success">← Back</a>
</div>

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

<div class="col-md-6">
<label>Title</label>
<input id="title" class="form-control">
</div>

<div class="col-md-6">
<label>Slug</label>
<input id="slug" class="form-control bg-light" readonly>
</div>

<div class="col-md-4">
<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>

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



<div class="col-md-4">
<label>Approval</label>
<input id="approval_status" class="form-control bg-light" readonly>
</div>

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

<div class="col-12">
<label>Content</label>
<div id="editor" style="height:400px"></div>
</div>

<div class="col-12 text-end">
<button class="btn btn-primary" onclick="updateCore()">Save Core</button>
</div>

<div class="col-12" id="coreMsg"></div>

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

</div>

<!-- ================= RIGHT ================= -->
<div class="col-xl-4">

<?php if ($isAdmin): ?>
<div class="card mb-3">
<div class="card-header"><h6>Update Status</h6></div>
<div class="card-body">

<select id="new_status" class="form-select mb-2">
<option value="Draft">Draft</option>
<option value="Active">Active</option>
<option value="InActive">Inactive</option>
</select>

<button class="btn btn-warning w-100" onclick="updateStatus()">Update Status</button>
<div id="statusMsg" class="mt-2"></div>

</div>
</div>
<?php endif; ?>

<div class="card mb-3">
<div class="card-header"><h6>Featured Image</h6></div>
<div class="card-body">

<div id="imagePreview" class="text-muted text-center mb-2">Loading…</div>

<input type="file" id="image" class="form-control mb-2">
<input id="alt_text" class="form-control mb-2" placeholder="ALT text">
<input id="caption" class="form-control mb-2" placeholder="Caption">

<button class="btn btn-primary w-100" onclick="uploadImage()">Upload</button>
<div id="imgMsg" class="mt-2"></div>

</div>
</div>

<div class="card">
<div class="card-header"><h6>SEO</h6></div>
<div class="card-body">

<input id="meta_title" class="form-control mb-2" placeholder="Meta Title">
<textarea id="meta_description" class="form-control mb-2" placeholder="Meta Description"></textarea>
<input id="meta_keywords" class="form-control mb-2" placeholder="Meta Keywords">
<input id="canonical_url" class="form-control mb-2" placeholder="Canonical URL">
<textarea id="seo_schema" class="form-control mb-2" placeholder="SEO Schema"></textarea>
<textarea id="ai_seo_content" class="form-control mb-2" placeholder="AI SEO Content"></textarea>

<button class="btn btn-success w-100" onclick="updateSeo()">Save SEO</button>
<div id="seoMsg" class="mt-2"></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 ?>";
const APPROOT = "<?= APP_ROOT ?>";
const pageId  = <?= $pageId ?>;
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'});
    loadPage();
});

/* LOAD PAGE */
async function loadPage(){
    const r = await fetch(
        `${ADMIN}api/pages/view.php?id=${pageId}&context=backend`,
        {credentials:'include'}
    ).then(r=>r.json());

    const p = r.data.page;

    title.value = p.title;
    slug.value = p.slug;
    page_type.value = p.page_type;
    template.value = p.template;
    status.value = p.status;
    approval_status.value = p.approval_status;
    short_description.value = p.short_description ?? '';
    quill.root.innerHTML = p.content ?? '<p></p>';

    new_status.value = p.status;

    meta_title.value = p.meta_title ?? '';
    meta_description.value = p.meta_description ?? '';
    meta_keywords.value = p.meta_keywords ?? '';
    canonical_url.value = p.canonical_url ?? '';
    seo_schema.value = p.seo_schema ?? '';
    ai_seo_content.value = p.ai_seo_content ?? '';

    if (r.data.images.featured) {
        imagePreview.innerHTML =
            `<img src="${APPROOT}${r.data.images.featured}"
                 class="img-fluid page-featured-thumb">`;
    }
}

/* CORE UPDATE – REFRESH */
function updateCore(){
fetch(`${ADMIN}api/pages/update.php`,{
method:'POST',
headers:{'Content-Type':'application/json','X-CSRF-TOKEN':CSRF_TOKEN},
credentials:'include',
body:JSON.stringify({
page_id:pageId,
title:title.value,
content:quill.root.innerHTML,
short_description:short_description.value,
template:template.value,
page_type:page_type.value
})
}).then(r=>r.json()).then(r=>{
coreMsg.innerHTML=`<div class="alert alert-${r.status==='success'?'success':'danger'}">${r.message}</div>`;
if(r.status==='success') setTimeout(()=>location.reload(),800);
});
}

/* STATUS UPDATE – REFRESH PAGE DATA */
function updateStatus(){
fetch(`${ADMIN}api/pages/update-status.php`,{
method:'POST',
headers:{'Content-Type':'application/json','X-CSRF-TOKEN':CSRF_TOKEN},
credentials:'include',
body:JSON.stringify({
page_id:pageId,
status:new_status.value
})
}).then(r=>r.json()).then(r=>{
statusMsg.innerHTML=`<div class="alert alert-${r.status==='success'?'success':'danger'}">${r.message}</div>`;
if(r.status==='success') loadPage();
});
}

/* SEO UPDATE – REFRESH */
function updateSeo(){
fetch(`${ADMIN}api/pages/update-seo.php`,{
method:'POST',
headers:{'Content-Type':'application/json','X-CSRF-TOKEN':CSRF_TOKEN},
credentials:'include',
body:JSON.stringify({
page_id:pageId,
meta_title:meta_title.value,
meta_description:meta_description.value,
meta_keywords:meta_keywords.value,
canonical_url:canonical_url.value,
seo_schema:seo_schema.value,
ai_seo_content:ai_seo_content.value
})
}).then(r=>r.json()).then(r=>{
seoMsg.innerHTML=`<div class="alert alert-${r.status==='success'?'success':'danger'}">${r.message}</div>`;
if(r.status==='success') setTimeout(()=>location.reload(),800);
});
}

/* IMAGE UPLOAD – REFRESH */
function uploadImage(){
if(!image.files.length){
imgMsg.innerHTML='<div class="alert alert-danger">Select image</div>';
return;
}
const fd=new FormData();
fd.append('page_id',pageId);
fd.append('image',image.files[0]);
fd.append('image_type','featured');
fd.append('alt_text',alt_text.value);
fd.append('caption',caption.value);

fetch(`${ADMIN}api/pages/upload-image.php`,{
method:'POST',
headers:{'X-CSRF-TOKEN':CSRF_TOKEN},
credentials:'include',
body:fd
}).then(r=>r.json()).then(r=>{
imgMsg.innerHTML=`<div class="alert alert-${r.status==='success'?'success':'danger'}">${r.message}</div>`;
if(r.status==='success') setTimeout(()=>location.reload(),800);
});
}
</script>
</body>
</html>
