<?php
declare(strict_types=1);

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

$blogId = (int)($_GET['id'] ?? 0);
if ($blogId <= 0) {
    die('Invalid blog 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 Blog']); ?>
<link rel="stylesheet" href="<?= ADMIN_BASE_URL ?>assets/libs/quill/quill.snow.css">
<?php include '../partials/head-css.php'; ?>

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

<div class="row">

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

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

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

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

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

<div class="col-12">
<label class="form-label">Excerpt</label>
<input id="excerpt" class="form-control">
</div>

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

<div class="col-md-6">
<label class="form-label">Tags</label>
<select id="tags" class="form-select" multiple size="6"></select>
</div>

<div class="col-12">
<label class="form-label">Blog 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 Blog Details
</button>
</div>

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

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

</div>

<!-- ================= RIGHT ================= -->
<div class="col-xl-4">
<!-- PUBLISH SETTINGS -->
<div class="card mt-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="updatePublishDate()">
    Update Publish Date
</button>

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

</div>
</div>



<!-- FEATURED IMAGE (SINGLE, LIST STYLE) -->
<div class="card mt-3">
<div class="card-header"><h5>Featured Image</h5></div>
<div class="card-body">

<div id="imgMsg" class="mb-2"></div>

<div class="row g-2" id="imageList"></div><br>
<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 mb-3" onclick="uploadImage()">
    Upload / Replace Featured Image
</button>


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

<label class="form-label">Meta Title</label>
<input id="meta_title" class="form-control mb-2">

<label class="form-label">Meta Keywords</label>
<input id="meta_keywords" class="form-control mb-2">

<label class="form-label">Meta Description</label>
<textarea id="meta_description" class="form-control mb-2"></textarea>

<label class="form-label">SEO Schema</label>
<textarea id="seo_schema" class="form-control mb-2"></textarea>

<label class="form-label">AI SEO Content</label>
<textarea id="ai_seo_content" class="form-control mb-2"></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>
/* ================= GLOBALS ================= */
const ADMIN   = "<?= ADMIN_BASE_URL ?>";
const APPROOT = "<?= APP_ROOT ?>/";
const blogId  = <?= $blogId ?>;
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 reloadAfterSuccess = (delay = 900) =>
    setTimeout(() => location.reload(), delay);

/* ================= 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 Promise.all([loadCategories(), loadTags()]);
    loadBlog();
});

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

async function loadTags(){
    const r = await fetch(`${ADMIN}api/blogs/tags/list.php?context=backend`).then(r=>r.json());
    tags.innerHTML='';
    r.data.forEach(t=>tags.add(new Option(t.name,t.id)));
}

/* ================= IMAGE RENDER ================= */
function renderFeaturedImage(path, alt='', caption=''){
    imageList.innerHTML = '';

    if (!path) {
        imageList.innerHTML = `
            <div class="col-12 text-muted text-center border rounded p-3">
                No featured image uploaded
            </div>`;
        return;
    }

    const url = APPROOT + path.replace(/^\/+/, '');

    imageList.innerHTML = `
        <div class="col-12 border rounded p-2">
            <img src="${url}"
                 class="img-fluid w-100 mb-2 blog-featured-thumb">

            <div class="small"><strong>ALT:</strong> ${alt || '-'}</div>
            <div class="small"><strong>Caption:</strong> ${caption || '-'}</div>

            <span class="badge bg-success">Featured</span>
        </div>`;
}

/* ================= LOAD BLOG ================= */
async function loadBlog(){
    const r = await fetch(`${ADMIN}api/blogs/view.php?context=backend&id=${blogId}`).then(r=>r.json());
    const b = r.data.blog;

    title.value   = b.title;
    slug.value    = b.slug;
    excerpt.value = b.excerpt ?? '';
    quill.root.innerHTML = b.content || '<p></p>';

    renderFeaturedImage(
        b.featured_image ?? null,
        b.featured_image_alt ?? '',
        b.featured_image_caption ?? ''
    );

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

    r.data.tags.forEach(t =>
        [...tags.options].forEach(o => o.value == t.id && (o.selected = true))
    );

    if (b.published_at) {
        // Convert MySQL datetime → datetime-local format
        published_at.value = b.published_at.replace(' ', 'T').slice(0,16);
    };

    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 ?? '';
    }
}

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

/* ================= CORE UPDATE ================= */
function updateCore(){
    if (!CSRF_TOKEN) {
        show('coreMsg','danger','Security token not ready');
        return;
    }

    fetch(`${ADMIN}api/blogs/update.php?context=backend`,{
        method:'POST',
        headers:{'Content-Type':'application/json','X-CSRF-TOKEN':CSRF_TOKEN},
        body:JSON.stringify({
            blog_id: blogId,
            title: title.value.trim(),
            slug: slug.value.trim(),
            excerpt: excerpt.value.trim(),
            content: quill.root.innerHTML.trim() || '<p></p>',
            category_ids: [...categories.selectedOptions].map(o=>o.value),
            tag_ids: [...tags.selectedOptions].map(o=>o.value)
        })
    })
    .then(r=>r.json())
    .then(r=>{
        show('coreMsg', r.status==='success'?'success':'danger', r.message);
        if (r.status === 'success') reloadAfterSuccess();
    });
}

/* ================= SEO UPDATE ================= */
function updateSeo(){
fetch(`${ADMIN}api/blogs/update-seo.php?context=backend`,{
method:'POST',
headers:{'Content-Type':'application/json','X-CSRF-TOKEN':CSRF_TOKEN},
body:JSON.stringify({
blog_id: blogId,
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') reloadAfterSuccess();
});
}

/* ================= IMAGE UPLOAD ================= */
function uploadImage(){
if(!image.files.length){
show('imgMsg','danger','Select an image');
return;
}

const fd=new FormData();
fd.append('blog_id',blogId);
fd.append('image',image.files[0]);
fd.append('alt_text',alt_text.value);
fd.append('caption',caption.value);

fetch(`${ADMIN}api/blogs/upload-featured-image.php?context=backend`,{
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' && r.data?.image_path) {
    renderFeaturedImage(r.data.image_path, alt_text.value, caption.value);
    reloadAfterSuccess();
}
});
}
/* ================= Publish Date ================= */

function updatePublishDate(){

    if (!CSRF_TOKEN) {
        show('publishMsg','danger','Security token not ready');
        return;
    }

    if (!published_at.value) {
        show('publishMsg','danger','Please select publish date');
        return;
    }

    fetch(`${ADMIN}api/blogs/update.php?context=backend`,{
        method: 'POST',
        headers:{
            'Content-Type':'application/json',
            'X-CSRF-TOKEN': CSRF_TOKEN
        },
        body: JSON.stringify({
            blog_id: blogId,
            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') reloadAfterSuccess();
    });
}

</script>
</body>
</html>
