<?php
declare(strict_types=1);

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

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

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

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

<div class="row">

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

<!-- CORE -->
<div class="card">
<div class="card-header d-flex justify-content-between">
<h3>Dealer Core Details</h3>
<a href="list.php" class="btn btn-success w-10">← Back To Dealer List</a>
</div>

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

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

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

<div class="col-md-6">
<label class="form-label">Dealer Type</label>
<select id="dealer_type_id" class="form-select"></select>
</div>

<div class="col-md-6">
<label class="form-label">CST Manager</label>
<select id="cst_id" class="form-select"></select>
</div>

<div class="col-md-6">
<label class="form-label">Contact Person</label>
<input id="contact_person" class="form-control">
</div>

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

<div class="col-md-4">
<label class="form-label">Address Line 1</label>
<input id="address_line1" class="form-control">
</div>

<div class="col-md-4">
<label class="form-label">Address Line 2</label>
<input id="address_line2" class="form-control">
</div>

<div class="col-md-4">
<label class="form-label">Pincode</label>
<input id="pincode" class="form-control">
</div>
<div class="col-md-6">
<label class="form-label">Latitude</label>
<input id="latitude" class="form-control">
</div>
<div class="col-md-6">
<label class="form-label">Longitude</label>
<input id="longitude" class="form-control">
</div>

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

<div class="col-md-6">
<label class="form-label">Alt Phone</label>
<input id="alt_phone" class="form-control">
</div>

<div class="col-12">
<label class="form-label">Dealer Details</label>
<div id="dealerEditor" style="height:400px"></div>
</div>

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

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

</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">

<label class="form-label">Meta Title</label><input id="meta_title" class="form-control mb-2" placeholder="Meta Title">
<label class="form-label">Meta Keywords</label><input id="meta_keywords" class="form-control mb-2" placeholder="Meta Keywords">
<label class="form-label">Meta Description</label><textarea id="meta_description" class="form-control mb-2" placeholder="Meta Description"></textarea>
<label class="form-label">SEO Schema</label><textarea id="seo_schema" class="form-control mb-2" placeholder="SEO Schema"></textarea>
<label class="form-label">AI SEO Content</label><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 Section</button>
<div id="seoAlert" class="mt-2"></div>

</div>
</div>

<!-- IMAGES -->
<div class="card mt-3">
<div class="card-header"><h6>Dealer 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="isPrimary">
<label class="form-check-label">Set as Primary Image</label>
</div>

<div class="row g-2" id="imageList"></div>

<button class="btn btn-primary w-100 mt-2" onclick="uploadImage()">Upload Image</button>
<div id="imageAlert" 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 APP_BASE = ADMIN.replace('/admin/', '/');
const dealerId = <?= $dealerId ?>;
const USER_ROLE = <?= json_encode($userRole) ?>;
let CSRF_TOKEN = null;

const quill = new Quill('#dealerEditor', { theme: 'snow' });

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

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

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

/* Lookups */
fetch(`${ADMIN}api/lookups/dealer-types.php`)
.then(r=>r.json()).then(r=>{
    r.data.forEach(d=>{
        dealer_type_id.innerHTML+=`<option value="${d.id}">${d.dealer_type}</option>`;
    });
});

fetch(`${ADMIN}api/lookups/cst-managers.php`)
.then(r=>r.json()).then(r=>{
    r.data.forEach(c=>{
        cst_id.innerHTML+=`<option value="${c.id}">${c.name}</option>`;
    });
});

/* Load Dealer */
fetch(`${ADMIN}api/dealers/view.php?id=${dealerId}`)
.then(r=>r.json()).then(r=>{
    const d=r.data;

    dealer_name.value=d.dealer_name;
    slug.value=d.slug;
    dealer_type_id.value=d.dealer_type_id;
    cst_id.value=d.cst_id;
    contact_person.value=d.contact_person??'';
    email.value=d.email??'';
    address_line1.value=d.address_line1??'';
    address_line2.value=d.address_line2??'';
    pincode.value=d.pincode??'';
    latitude.value=d.latitude??'';
    longitude.value=d.longitude??'';
    phone.value=d.phone??'';
    alt_phone.value=d.alt_phone??'';
    quill.root.innerHTML=d.dealer_details??'';

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

    loadImages(d.images||[]);
});

/* IMAGES */
function loadImages(images){
    imageList.innerHTML='';

    images.filter(img => img.is_deleted != 1).forEach(img=>{

       const toggleBtn = img.status === 'Active'
    ? `<button class="btn btn-sm btn-outline-warning me-1"
         onclick="toggleImage(${img.id},'Inactive')">Deactivate</button>`
    : `<button class="btn btn-sm btn-outline-success me-1"
         onclick="toggleImage(${img.id},'Active')">Activate</button>`;

        const deleteBtn = USER_ROLE === 'seo_manager'
            ? `<button class="btn btn-sm btn-outline-danger"
                 onclick="deleteImage(${img.id})">Delete</button>`
            : '';

        imageList.innerHTML+=`
        <div class="col-12 border rounded p-2">
            <img src="${APP_BASE}${img.image_path.replace(/^\/+/,'')}"
                 class="img-fluid mb-1">

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

            <div class="mb-2">
                ${img.is_primary==1?'<span class="badge bg-success me-1">Primary</span>':''}
               <span class="badge ${img.status === 'Active' ? 'bg-info' : 'bg-secondary'}">
    ${img.status}
</span>

            </div>

            ${toggleBtn}
            ${deleteBtn}
        </div>`;
    });
}


/* IMAGE TOGGLE */
function toggleImage(imageId, status){
    if(!CSRF_TOKEN){
        alert('Security token not ready');
        return;
    }

    fetch(`${ADMIN}api/dealers/image-toggle.php`,{
        method:'POST',
        headers:{
            'Content-Type':'application/json',
            'X-CSRF-TOKEN':CSRF_TOKEN
        },
        body:JSON.stringify({
            image_id: imageId,
            status: status
        })
    })
    .then(r=>r.json())
    .then(r=>{
        show('imageAlert', r.status === 'success' ? 'success' : 'danger', r.message);
        location.reload();
    });
}



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

fetch(`${ADMIN}api/dealers/image-delete.php`,{
method:'POST',
headers:{'Content-Type':'application/json','X-CSRF-TOKEN':CSRF_TOKEN},
body:JSON.stringify({image_id:imageId})
}).then(r=>r.json()).then(r=>{
if(r.status==='success'){ show('imageAlert','success',r.message); reloadPage(); }
else{ show('imageAlert','danger',r.message); }
});
}

/* CORE UPDATE */
function updateDealer(){
fetch(`${ADMIN}api/dealers/update.php`,{
method:'POST',
headers:{'Content-Type':'application/json','X-CSRF-TOKEN':CSRF_TOKEN},
body:JSON.stringify({
dealer_id:dealerId,
dealer_name:dealer_name.value,
dealer_type_id:dealer_type_id.value,
cst_id:cst_id.value,
contact_person:contact_person.value,
email:email.value,
address_line1:address_line1.value,
address_line2:address_line2.value,
pincode:pincode.value,
latitude:latitude.value,
longitude:longitude.value,
phone:phone.value,
alt_phone:alt_phone.value,
dealer_details:quill.root.innerHTML
})
}).then(r=>r.json()).then(r=>{
if(r.status==='success'){ show('coreAlert','success','Updated'); reloadPage(); }
else{ show('coreAlert','danger',r.message); }
});
}

/* SEO UPDATE */
function updateSeo(){
fetch(`${ADMIN}api/dealers/update-seo.php`,{
method:'POST',
headers:{'Content-Type':'application/json','X-CSRF-TOKEN':CSRF_TOKEN},
body:JSON.stringify({
dealer_id:dealerId,
meta_title:meta_title.value.trim()||null,
meta_keywords:meta_keywords.value.trim()||null,
meta_description:meta_description.value.trim()||null,
seo_schema:seo_schema.value.trim()||null,
ai_seo_content:ai_seo_content.value.trim()||null
})
}).then(r=>r.json()).then(r=>{
if(r.status==='success'){ show('seoAlert','success','SEO Updated'); reloadPage(); }
else{ show('seoAlert','danger',r.message); }
});
}

/* IMAGE UPLOAD */
function uploadImage(){
const f=imageFile.files[0];
if(!f){ alert('Select image'); return; }

const fd=new FormData();
fd.append('dealer_id',dealerId);
fd.append('image',f);
fd.append('alt_text',imageAlt.value);
fd.append('caption',imageCaption.value);
fd.append('is_primary',isPrimary.checked?1:0);

fetch(`${ADMIN}api/dealers/upload-image.php`,{
method:'POST',
headers:{'X-CSRF-TOKEN':CSRF_TOKEN},
body:fd
}).then(r=>r.json()).then(r=>{
if(r.status==='success'){ show('imageAlert','success','Image uploaded'); reloadPage(); }
else{ show('imageAlert','danger',r.message); }
});
}
</script>

</body>
</html>
