<?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 Retail Product']); ?>

<link rel="stylesheet" href="<?= ADMIN_BASE_URL ?>assets/libs/quill/quill.snow.css">
<link rel="stylesheet" href="<?= ADMIN_BASE_URL ?>assets/libs/choices.js/public/assets/styles/choices.min.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'     => 'Create Retail Product'
]); ?>

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

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

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

<!-- PRODUCT NAME -->
<div class="col-xl-6">
<label class="form-label">Product Name <span class="text-danger">*</span></label>
<input id="product_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>

<!-- CATEGORY -->
<div class="col-xl-6">
<label class="form-label">Product Category <span class="text-danger">*</span></label>
<select id="categories" class="form-select" multiple></select>
</div>

<!-- PRIMARY SLEEP -->
<div class="col-xl-3">
<label class="form-label">Primary Sleep Type</label>
<select id="primary_sleep_id" class="form-select">
<option value="">-- Select --</option>
<option value="1">Super Soft</option>
<option value="2">Soft</option>
<option value="3">Medium Soft</option>
<option value="4">Medium Firm</option>
<option value="5">Firm</option>
<option value="6">Extra Firm</option>
</select>
</div>

<!-- SECONDARY SLEEP -->
<div class="col-xl-3">
<label class="form-label">Secondary Sleep Type</label>
<select id="secondary_sleep_id" class="form-select">
<option value="">-- Select --</option>
<option value="1">Super Soft</option>
<option value="2">Soft</option>
<option value="3">Medium Soft</option>
<option value="4">Medium Firm</option>
<option value="5">Firm</option>
<option value="6">Extra Firm</option>
</select>
</div>

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

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

<!-- BROCHURE -->
<div class="col-xl-6">
<label class="form-label">Brochure File (PDF) <span class="text-danger">*</span></label>
<input id="brochure_file" class="form-control">
</div>

<!-- SEO -->
<div class="col-12">
<div class="card border">
<div class="card-header"><h6 class="mb-0">SEO Details</h6></div>
<div class="card-body row g-3">
<div class="col-md-6"><input id="meta_title" class="form-control" placeholder="Meta Title"></div>
<div class="col-md-6"><input id="meta_keywords" class="form-control" placeholder="Meta Keywords"></div>
<div class="col-12"><textarea id="meta_description" class="form-control" rows="3" placeholder="Meta Description"></textarea></div>
<div class="col-12"><textarea id="seo_schema" class="form-control font-monospace" rows="4" placeholder="SEO Schema JSON"></textarea></div>
<div class="col-12"><textarea id="ai_seo_content" class="form-control" rows="4" placeholder="AI SEO Content"></textarea></div>
</div>
</div>
</div>

<!-- VARIANTS -->
<div class="col-12">
<div class="card border">
<div class="card-header">
    <h6 class="mb-0">Variants <span class="text-danger">*</span></h6>
</div>
<div class="card-body">
<div id="variantsWrapper"></div>
<button class="btn btn-sm btn-outline-primary" onclick="addVariant()">+ Add Variant</button>
</div>
</div>
</div>

<!-- ACTIONS -->
<div class="col-12 text-end mt-3">
<button class="btn btn-light" onclick="location.reload()">Reset</button>
<button class="btn btn-primary" id="createBtn" onclick="createProduct()">Create Product</button>
</div>

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

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

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

<?php include '../partials/footer.php'; ?>
</div>

<!-- ================= SUCCESS MODAL ================= -->
<div class="modal fade" id="successModal" tabindex="-1">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header bg-success text-white">
    <h6 class="modal-title">Success</h6>
</div>
<div class="modal-body text-center">
    <i class="bi bi-check-circle fs-1 text-success"></i>
    <p class="mt-3 mb-0">Product added successfully.</p>
</div>
<div class="modal-footer justify-content-center">
    <button class="btn btn-success" onclick="redirectToList()">Go to Product List</button>
</div>
</div>
</div>
</div>

<?php include '../partials/vendor-scripts.php'; ?>
<script src="<?= ADMIN_BASE_URL ?>assets/libs/quill/quill.js"></script>
<script src="<?= ADMIN_BASE_URL ?>assets/libs/choices.js/public/assets/scripts/choices.min.js"></script>

<script>
const ADMIN = "<?= ADMIN_BASE_URL ?>";
let CSRF_TOKEN = null;
let quill;
let categoryChoice;

fetch(`${ADMIN}security/csrf.php`)
.then(r=>r.json()).then(j=>CSRF_TOKEN=j.data.csrf_token);

document.addEventListener('DOMContentLoaded', () => {
    quill = new Quill('#editor', { theme: 'snow' });
    categoryChoice = new Choices('#categories', { removeItemButton: true });
    loadCategories();
    addVariant();
});

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

async function loadCategories(){
    const r = await fetch(`${ADMIN}api/retail-categories/list.php?context=backend`).then(r=>r.json());
    r.data.forEach(c => {
        categoryChoice.setChoices([{ value:c.id, label:c.category_name }],'value','label',false);
    });
}

function addVariant(){
    variantsWrapper.insertAdjacentHTML('beforeend', `
<div class="border rounded p-3 mb-3" data-variant>
<div class="row g-3">
<div class="col-md-3"><input class="form-control variant_name" placeholder="Variant Name"></div>
<div class="col-md-2"><select class="form-select size"><option value="">Size</option><option>Single</option><option>Double</option><option>Queen</option><option>King</option><option>Custom</option></select></div>
<div class="col-md-2"><select class="form-select firmness"><option value="">Firmness</option><option>Soft</option><option>Medium</option><option>Firm</option><option>Custom</option></select></div>
<div class="col-md-2"><input class="form-control thickness" placeholder="Thickness"></div>
<div class="col-md-1"><input type="number" class="form-control mrp" placeholder="MRP"></div>
<div class="col-md-1"><input type="number" class="form-control selling_price" placeholder="Price"></div>
<div class="col-md-1 text-end"><button class="btn btn-sm btn-light-danger" onclick="this.closest('[data-variant]').remove()">✕</button></div>
</div>
</div>`);
}

function redirectToList(){
    window.location.href = `${ADMIN}retail-products/index.php`;
}

function createProduct(){

    document.getElementById('createBtn').disabled = true;

    const variants=[];
    document.querySelectorAll('[data-variant]').forEach(v=>{
        const o={
            variant_name:v.querySelector('.variant_name').value.trim(),
            size:v.querySelector('.size').value,
            firmness:v.querySelector('.firmness').value,
            thickness:v.querySelector('.thickness').value.trim(),
            mrp:parseFloat(v.querySelector('.mrp').value),
            selling_price:parseFloat(v.querySelector('.selling_price').value)
        };
        if(Object.values(o).some(x=>!x)){ throw new Error('Variant invalid'); }
        variants.push(o);
    });

    fetch(`${ADMIN}api/retail-products/create.php`,{
        method:'POST',
        headers:{'Content-Type':'application/json','X-CSRF-TOKEN':CSRF_TOKEN},
        body:JSON.stringify({
            product_name:product_name.value.trim(),
            category_id:categoryChoice.getValue(true)[0],
            primary_sleep_id:primary_sleep_id.value||null,
            secondary_sleep_id:secondary_sleep_id.value||null,
            short_description:short_description.value.trim(),
            full_description:quill.root.innerHTML.trim(),
            brochure_file:brochure_file.value.trim(),
            meta_title:meta_title.value||null,
            meta_description:meta_description.value||null,
            meta_keywords:meta_keywords.value||null,
            seo_schema:seo_schema.value||null,
            ai_seo_content:ai_seo_content.value||null,
            variants
        })
    })
    .then(r=>r.json())
    .then(r=>{
        if(r.status==='success'){
            new bootstrap.Modal(document.getElementById('successModal')).show();
            setTimeout(redirectToList, 2000);
        }else{
            msg.innerHTML=r.message;
            document.getElementById('createBtn').disabled=false;
        }
    });
}
</script>

</body>
</html>
