<?php
declare(strict_types=1);

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

$productId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($productId <= 0) {
    die('Invalid product id');
}

$userRole = $_SESSION['role'] ?? '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php includeFileWithVariables('../partials/title-meta.php', ['title' => 'Edit Retail Product']); ?>
<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 Retail Product'
]); ?>

<div class="row">

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

<!-- CORE -->
<div class="card">
<div class="card-header d-flex justify-content-between">
<h5>Product Core Details</h5>
<a href="list.php" class="btn btn-success btn-sm">← Back to List</a>
</div>

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

<div class="col-md-6">
<label class="form-label">Product Name</label>
<input id="product_name" class="form-control">
</div>

<div class="col-md-6">
<label class="form-label">Slug</label>
<input id="slug" class="form-control" readonly>
<div class="form-check mt-1">
<input type="checkbox" id="update_slug" class="form-check-input">
<label class="form-check-label">Update slug with product name</label>
</div>
</div>

<div class="col-md-6">
<label class="form-label">Category</label>
<select id="category_id" class="form-select"></select>
</div>

<div class="col-md-3">
<label class="form-label">Primary Sleep</label>
<select id="primary_sleep_id" class="form-select">
<option value="">--</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>

<div class="col-md-3">
<label class="form-label">Secondary Sleep</label>
<select id="secondary_sleep_id" class="form-select">
<option value="">--</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>

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

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

<div class="col-md-6">
<label class="form-label">Brochure File (PDF)</label>
<input id="brochure_file" class="form-control">
</div>

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

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

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

<!-- VARIANTS -->
<div class="card mt-3">
<div class="card-header"><h6>Variants</h6></div>
<div class="card-body">
<table class="table table-sm">
<thead>
<tr>
<th>Name</th><th>Size</th><th>Firmness</th><th>MRP</th><th>Selling</th><th>Status</th>
</tr>
</thead>
<tbody id="variantRows"></tbody>
</table>
</div>
</div>

<!-- SECTIONS -->
<div class="card mt-3">
<div class="card-header"><h6>Sections</h6></div>
<div class="card-body">
<div id="sectionAlert"></div>
<div id="sectionList" class="row g-2"></div>
</div>
</div>

</div>

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

<!-- SEO -->
<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">
<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 type="button" class="btn btn-success w-100" onclick="updateSeo()">Update SEO</button>
<div id="seoAlert" class="mt-2"></div>

</div>
</div>

<!-- IMAGES -->
<div class="card mt-3">
<div class="card-header"><h6>Images</h6></div>
<div class="card-body">

<input type="file" id="imageFile" class="form-control mb-2">
<input type="text" id="imageAlt" class="form-control mb-2" placeholder="ALT text">
<input type="text" id="imageCaption" class="form-control mb-2" placeholder="Caption">

<div class="form-check mb-2">
<input class="form-check-input" type="checkbox" id="isFeatured">
<label class="form-check-label">Set as Featured</label>
</div>

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

<div class="row g-2 mt-2" id="imageList"></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_BASE = ADMIN.replace('/admin/', '/');
const productId = <?= $productId ?>;
let CSRF_TOKEN = null;
const quill = new Quill('#editor', { theme: 'snow' });

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

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

/* Load categories */
fetch(`${ADMIN}api/retail-categories/list.php?context=backend`)
.then(r=>r.json()).then(r=>{
    r.data.forEach(c=>{
        category_id.innerHTML+=`<option value="${c.id}">${c.category_name}</option>`;
    });
});

/* Load product */
fetch(`${ADMIN}api/retail-products/view.php?id=${productId}`)
.then(r=>r.json()).then(r=>{
    const p=r.data.product;
    product_name.value=p.product_name;
    slug.value=p.slug;
    category_id.value=p.category_id;
    primary_sleep_id.value=p.primary_sleep_id||'';
    secondary_sleep_id.value=p.secondary_sleep_id||'';
    short_description.value=p.short_description||'';
    brochure_file.value=p.brochure_file||'';
    quill.root.innerHTML=p.full_description||'';

    const seo=r.data.seo||{};
    meta_title.value=seo.meta_title||'';
    meta_keywords.value=seo.meta_keywords||'';
    meta_description.value=seo.meta_description||'';
    seo_schema.value=seo.seo_schema||'';
    ai_seo_content.value=seo.ai_seo_content||'';

    loadVariants(r.data.variants||[]);
    loadSections(r.data.sections||[]);
    loadImages(r.data.images||[]);
});

/* CORE UPDATE */
function updateCore(){
fetch(`${ADMIN}api/retail-products/update.php`,{
method:'POST',
headers:{'Content-Type':'application/json','X-CSRF-TOKEN':CSRF_TOKEN},
body:JSON.stringify({
product_id:productId,
product_name:product_name.value,
category_id:category_id.value,
primary_sleep_id:primary_sleep_id.value||null,
secondary_sleep_id:secondary_sleep_id.value||null,
short_description:short_description.value,
full_description:quill.root.innerHTML,
brochure_file:brochure_file.value,
update_slug: document.getElementById('update_slug').checked
})
}).then(r=>r.json()).then(r=>{
show('coreAlert',r.status==='success'?'success':'danger',r.message);
});
}

/* SEO UPDATE */
function updateSeo(){
fetch(`${ADMIN}api/retail-products/update-seo.php`,{
method:'POST',
headers:{'Content-Type':'application/json','X-CSRF-TOKEN':CSRF_TOKEN},
body:JSON.stringify({
product_id:productId,
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('seoAlert',r.status==='success'?'success':'danger',r.message);
});
}

/* VARIANTS */
function loadVariants(variants){
variantRows.innerHTML='';
if(!variants.length){
variantRows.innerHTML=`<tr><td colspan="6" class="text-muted text-center">No variants</td></tr>`;
return;
}
variants.forEach(v=>{
variantRows.innerHTML+=`
<tr>
<td>${v.variant_name}</td>
<td>${v.size}</td>
<td>${v.firmness}</td>
<td>${v.mrp}</td>
<td>${v.selling_price}</td>
<td>${v.status}</td>
</tr>`;
});
}

/* SECTIONS */
function loadSections(sections){
sectionList.innerHTML='';
if(!sections.length){
sectionList.innerHTML='<div class="text-muted">No sections added</div>';
return;
}
sections.forEach(s=>{
sectionList.innerHTML+=`
<div class="col-12 border rounded p-2">
<strong>${s.section_title||'(No title)'}</strong>
<span class="badge bg-info ms-2">${s.status}</span>
<span class="badge bg-secondary ms-1">${s.approval_status}</span>
</div>`;
});
}

/* IMAGES */
function loadImages(images){
imageList.innerHTML='';
images.forEach(img=>{
imageList.innerHTML+=`
<div class="col-12 border rounded p-2">
<img src="${APP_BASE}${img.image_path}" class="img-fluid mb-1">
<div class="small"><b>ALT:</b> ${img.alt_text||'-'}</div>
<div class="small"><b>Caption:</b> ${img.caption||'-'}</div>
</div>`;
});
}

function uploadImage(){
const f=imageFile.files[0];
if(!f) return;
const fd=new FormData();
fd.append('product_id',productId);
fd.append('image',f);
fd.append('alt_text',imageAlt.value);
fd.append('caption',imageCaption.value);
fd.append('is_featured',isFeatured.checked?1:0);

fetch(`${ADMIN}api/retail-products/upload-image.php`,{
method:'POST',
headers:{'X-CSRF-TOKEN':CSRF_TOKEN},
body:fd
}).then(()=>location.reload());
}
</script>

</body>
</html>
