<?php
declare(strict_types=1);

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

$categoryId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($categoryId <= 0) {
    header('Location: ' . ADMIN_BASE_URL . 'retail-products/categories.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<?php includeFileWithVariables('../partials/title-meta.php', ['title' => 'Edit Category']); ?>

<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' => 'Catalog',
    'title'     => 'Edit Category'
]); ?>

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

<!-- CATEGORY NAME -->
<div class="col-xl-6">
<label class="form-label">Category Name *</label>
<input id="category_name" class="form-control">
</div>

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

<!-- SHORT DESCRIPTION -->
<div class="col-12">
<label class="form-label">Short Description</label>
<input id="short_description" class="form-control" maxlength="255">
</div>

<!-- DESCRIPTION -->
<div class="col-12">
<label class="form-label">Description *</label>
<div id="editor" style="height:300px"></div>
</div>

<hr>

<!-- SEO -->
<div class="col-xl-6">
<label class="form-label">Meta Title</label>
<input id="meta_title" class="form-control">
</div>

<div class="col-xl-6">
<label class="form-label">Meta Keywords</label>
<input id="meta_keywords" class="form-control">
</div>

<div class="col-12">
<label class="form-label">Meta Description</label>
<textarea id="meta_description" class="form-control" rows="2"></textarea>
</div>

<div class="col-12">
<label class="form-label">AI Summary</label>
<textarea id="ai_summary" class="form-control" rows="2"></textarea>
</div>

<hr>

<!-- IMAGE -->
<div class="col-12">
<label class="form-label">Category Image</label>

<div id="imageList" class="mb-3"></div>

<div class="row g-2">
    <div class="col-md-6">
        <input type="file"
               id="imageUpload"
               class="form-control"
               accept="image/*">
    </div>
    <div class="col-md-6">
        <input type="text"
               id="image_alt"
               class="form-control"
               placeholder="Image alt text (SEO)">
    </div>
</div>
</div>

<!-- ACTIONS -->
<div class="col-12 text-end mt-3">
<button class="btn btn-light" onclick="history.back()">Cancel</button>
<button class="btn btn-primary" onclick="updateCategory()">Save Changes</button>
</div>

<div class="col-12">
<div id="msg"></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 APP_ROOT = "<?= APP_ROOT ?>";
const CATEGORY_ID = <?= $categoryId ?>;

const API_VIEW   = `${ADMIN}api/retail-categories/view.php?id=${CATEGORY_ID}`;
const API_UPDATE = `${ADMIN}api/retail-categories/update.php`;
const API_UPLOAD = `${ADMIN}api/retail-categories/upload-image.php`;
const API_DELETE_IMG = `${ADMIN}api/retail-categories/delete-image.php`;

let quill;

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

/* ================= LOAD CATEGORY ================= */
function loadCategory(){
fetch(API_VIEW, { credentials:'include' })
.then(r => r.json())
.then(res => {

    if (res.status !== 'success') {
        alert(res.message || 'Failed to load category');
        return;
    }

    const d = res.data;

    category_name.value = d.category_name;
    slug.value = d.slug;
    short_description.value = d.short_description || '';
    quill.root.innerHTML = d.description || '';

    meta_title.value = d.meta_title || '';
    meta_keywords.value = d.meta_keywords || '';
    meta_description.value = d.meta_description || '';
    ai_summary.value = d.ai_summary || '';

    image_alt.value = d.image_alt || '';

    renderImage(d);
});
}

/* ================= RENDER IMAGE ================= */
function renderImage(d){
const wrap = document.getElementById('imageList');
wrap.innerHTML = '';

if (!d.image_path) {
    wrap.innerHTML = `<span class="text-muted">No image uploaded</span>`;
    return;
}

wrap.innerHTML = `
<div style="position:relative;display:inline-block">
    <img src="${APP_ROOT}${d.image_path}"
         alt="${d.image_alt || d.category_name}"
         style="width:120px;height:120px;
                object-fit:cover;border-radius:6px">

    <button class="btn btn-sm btn-danger"
            style="position:absolute;top:-6px;right:-6px"
            onclick="deleteImage()">
        ×
    </button>
</div>`;
}

/* ================= UPLOAD IMAGE ================= */
imageUpload.addEventListener('change', () => {

const file = imageUpload.files[0];
if (!file) return;

const fd = new FormData();
fd.append('category_id', CATEGORY_ID);
fd.append('image', file);
fd.append('image_alt', image_alt.value.trim());

fetch(API_UPLOAD, {
    method:'POST',
    credentials:'include',
    body: fd
})
.then(r => r.json())
.then(r => {
    if (r.status === 'success') {
        loadCategory();
        imageUpload.value = '';
    } else {
        alert(r.message);
    }
});
});

/* ================= DELETE IMAGE ================= */
function deleteImage(){
if (!confirm('Delete category image?')) return;

fetch(API_DELETE_IMG, {
    method:'POST',
    credentials:'include',
    headers:{'Content-Type':'application/json'},
    body: JSON.stringify({ category_id: CATEGORY_ID })
})
.then(r => r.json())
.then(r => {
    if (r.status === 'success') loadCategory();
    else alert(r.message);
});
}

/* ================= UPDATE CATEGORY ================= */
function updateCategory(){

const payload = {
    id: CATEGORY_ID, // ✅ FIXED
    category_name: category_name.value.trim(),
    short_description: short_description.value.trim() || null,
    description: quill.root.innerHTML.trim(),
    meta_title: meta_title.value.trim() || null,
    meta_keywords: meta_keywords.value.trim() || null,
    meta_description: meta_description.value.trim() || null,
    ai_summary: ai_summary.value.trim() || null
};

if (!payload.category_name || !payload.description) {
    msg.innerHTML = `<div class="alert alert-danger">
        Required fields missing
    </div>`;
    return;
}

fetch(API_UPDATE,{
    method:'POST',
    credentials:'include',
    headers:{'Content-Type':'application/json'},
    body: JSON.stringify(payload)
})
.then(r => r.json())
.then(r => {

    if (r.status !== 'success') {
        msg.innerHTML = `<div class="alert alert-danger">${r.message}</div>`;
        return;
    }

    const modalHtml = `
<div class="modal fade" id="successModal" tabindex="-1">
<div class="modal-dialog modal-sm modal-dialog-centered">
<div class="modal-content">
<div class="modal-body text-center">
    <h6 class="mb-2">Category Updated</h6>
    <p class="text-muted mb-3">
        Category updated successfully
    </p>
    <button class="btn btn-success w-100" data-bs-dismiss="modal">
        OK
    </button>
</div>
</div>
</div>
</div>`;

    document.body.insertAdjacentHTML('beforeend', modalHtml);
    const modal = new bootstrap.Modal(document.getElementById('successModal'));
    modal.show();

    document.getElementById('successModal')
        .addEventListener('hidden.bs.modal', () => {
            window.location.href = `${ADMIN}retail-products/categories.php`;
        });
});
}
</script>

</body>
</html>
