<?php
declare(strict_types=1);

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

$faqId = (int)($_GET['id'] ?? 0);
if ($faqId <= 0) {
    die('Invalid FAQ 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();

if (!in_array($role, ['Super Admin','Admin','SEO Manager','Manager'], true)) {
    die('Unauthorized');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php includeFileWithVariables('../partials/title-meta.php', ['title' => 'Edit FAQ']); ?>
<link rel="stylesheet" href="<?= ADMIN_BASE_URL ?>assets/libs/quill/quill.snow.css">
<?php include '../partials/head-css.php'; ?>

<style>
.faq-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 FAQ'
]); ?>

<div class="row">

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

<div class="card">
<div class="card-header d-flex justify-content-between">
    <h4>FAQ Core Details</h4>
    <a href="<?= ADMIN_BASE_URL ?>faq/list.php" class="btn btn-success">
        ← Back to FAQ List
    </a>
</div>

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

<div class="col-12">
<label class="form-label">Question</label>
<input id="question" class="form-control">
</div>

<div class="col-12">
<label class="form-label">Slug</label>
<input id="slug" class="form-control">
</div>

<div class="col-12">
<label class="form-label">Categories</label>
<select id="categories" class="form-select" multiple size="6"></select>
</div>

<div class="col-12">
<label class="form-label">Answer</label>
<div id="editor" style="height:300px"></div>
</div>

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

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

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

</div>

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

<!-- PUBLISH -->
<div class="card mb-3">
<div class="card-header"><h5>Publish Settings</h5></div>
<div class="card-body">

<label class="form-label">Published At</label>
<input type="datetime-local" id="published_at" class="form-control mb-2">

<button class="btn btn-warning w-100" onclick="updatePublish()">
    Update Publish Date
</button>

<div id="publishMsg" class="mt-2"></div>
</div>
</div>

<!-- IMAGE -->
<div class="card mb-3">
<div class="card-header"><h5>Featured Image</h5></div>
<div class="card-body">

<div id="imgMsg" class="mb-2"></div>
<div id="imageList" class="mb-3"></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 / Replace Image
</button>
</div>
</div>

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

<input id="meta_title" class="form-control mb-2" placeholder="Meta Title">
<input id="meta_keywords" class="form-control mb-2" placeholder="Meta Keywords">
<textarea id="meta_description" class="form-control mb-2" placeholder="Meta Description"></textarea>
<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()">Update 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 faqId = <?= $faqId ?>;

let CSRF_TOKEN = null;
let quill;
let slugLocked = false;

const show = (id,type,msg)=>{
    document.getElementById(id).innerHTML =
    `<div class="alert alert-${type}">${msg}</div>`;
};

const reload = () => setTimeout(()=>location.reload(),900);

/* 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'});
    await loadCategories();
    loadFaq();
});

/* LOAD CATEGORIES */
async function loadCategories(){
    const r = await fetch(`${ADMIN}api/faqs/categories/list.php`).then(r=>r.json());
    categories.innerHTML='';
    r.data.forEach(c=>categories.add(new Option(c.name,c.id)));
}

/* LOAD FAQ */
async function loadFaq(){
    const r = await fetch(`${ADMIN}api/faqs/view.php?id=${faqId}`).then(r=>r.json());
    const f = r.data.faq;

    question.value = f.question;
    slug.value = f.slug;
    quill.root.innerHTML = f.answer || '<p></p>';

    r.data.categories.forEach(c=>{
        [...categories.options].forEach(o=>o.value==c.id && (o.selected=true));
    });

    if (f.published_at) {
        published_at.value = f.published_at.replace(' ','T').slice(0,16);
    }

    renderImage(f.featured_image,f.featured_image_alt,f.featured_image_caption);

    if (r.data.seo){
        meta_title.value = r.data.seo.meta_title ?? '';
        meta_keywords.value = r.data.seo.meta_keywords ?? '';
        meta_description.value = r.data.seo.meta_description ?? '';
        seo_schema.value = r.data.seo.seo_schema ?? '';
        ai_seo_content.value = r.data.seo.ai_seo_content ?? '';
    }
}

/* IMAGE RENDER */
function renderImage(path,alt='',cap=''){
    if(!path){
        imageList.innerHTML=`<div class="text-muted text-center">No image</div>`;
        return;
    }
    imageList.innerHTML=`
<img src="${APPROOT}${path.replace(/^\/+/,'')}"
class="img-fluid faq-featured-thumb mb-2">
<div class="small"><strong>ALT:</strong> ${alt||'-'}</div>
<div class="small"><strong>Caption:</strong> ${cap||'-'}</div>`;
}

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

/* CORE UPDATE */
function updateCore(){
fetch(`${ADMIN}api/faqs/update.php`,{
method:'POST',
headers:{'Content-Type':'application/json','X-CSRF-TOKEN':CSRF_TOKEN},
body:JSON.stringify({
faq_id:faqId,
question:question.value,
answer:quill.root.innerHTML,
category_ids:[...categories.selectedOptions].map(o=>o.value)
})
}).then(r=>r.json()).then(r=>{
show('coreMsg',r.status==='success'?'success':'danger',r.message);
if(r.status==='success') reload();
});
}

/* PUBLISH */
function updatePublish(){
fetch(`${ADMIN}api/faqs/update.php`,{
method:'POST',
headers:{'Content-Type':'application/json','X-CSRF-TOKEN':CSRF_TOKEN},
body:JSON.stringify({
faq_id:faqId,
status:'Active',
published_at:published_at.value.replace('T',' ')
})
}).then(r=>r.json()).then(r=>{
show('publishMsg',r.status==='success'?'success':'danger',r.message);
if(r.status==='success') reload();
});
}

/* IMAGE UPLOAD */
function uploadImage(){
if(!image.files.length){
show('imgMsg','danger','Select image');return;
}
const fd=new FormData();
fd.append('faq_id',faqId);
fd.append('image',image.files[0]);
fd.append('alt_text',alt_text.value);
fd.append('caption',caption.value);

fetch(`${ADMIN}api/faqs/upload-image.php`,{
method:'POST',
headers:{'X-CSRF-TOKEN':CSRF_TOKEN},
body:fd
}).then(r=>r.json()).then(r=>{
show('imgMsg',r.status==='success'?'success':'danger',r.message);
if(r.status==='success') reload();
});
}

/* SEO */
function updateSeo(){
fetch(`${ADMIN}api/faqs/update-seo.php`,{
method:'POST',
headers:{'Content-Type':'application/json','X-CSRF-TOKEN':CSRF_TOKEN},
body:JSON.stringify({
faq_id:faqId,
meta_title:meta_title.value,
meta_keywords:meta_keywords.value,
meta_description:meta_description.value,
seo_schema:seo_schema.value,
ai_seo_content:ai_seo_content.value
})
}).then(r=>r.json()).then(r=>{
show('seoMsg',r.status==='success'?'success':'danger',r.message);
if(r.status==='success') reload();
});
}
</script>

</body>
</html>
