<?php
declare(strict_types=1);

require_once __DIR__ . '/../security/auth_guard.php';
require_once __DIR__ . '/../partials/main.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php includeFileWithVariables('../partials/title-meta.php', ['title' => 'Create 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' => 'Create Dealer'
]); ?>

<div class="row">

<div class="col-xl-12">
<div class="card">
<div class="card-header d-flex justify-content-between">
<h3>Dealer Core Details</h3>
<a href="list.php" class="btn btn-primary">← Back To Dealer's List</a>
</div>

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

<!-- Dealer Name -->
<div class="col-md-6">
<label class="form-label">
Dealer Name <span class="text-danger">*</span>
</label>
<input id="dealer_name" class="form-control" oninput="onMandatoryChange()">
</div>

<!-- Slug Preview -->
<div class="col-md-6">
<label class="form-label">Slug (Auto)</label>
<input id="slug_preview" class="form-control" readonly>
</div>

<!-- Dealer Type -->
<div class="col-md-6">
<label class="form-label">
Dealer Type <span class="text-danger">*</span>
</label>
<select id="dealer_type_id" class="form-select" onchange="onMandatoryChange()"></select>
</div>

<!-- CST Manager -->
<div class="col-md-6">
<label class="form-label">
CST Manager <span class="text-danger">*</span>
</label>
<select id="cst_id" class="form-select" onchange="onMandatoryChange()"></select>
</div>

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

<!-- Pincode -->
<div class="col-md-4">
<label class="form-label">Pincode</label>
<input id="pincode" class="form-control">
</div>

<!-- State -->
<div class="col-md-6">
<label class="form-label">
State <span class="text-danger">*</span>
</label>
<select id="state_id" class="form-select" onchange="loadCities()"></select>
</div>

<!-- City -->
<div class="col-md-6">
<label class="form-label">
City <span class="text-danger">*</span>
</label>
<select id="city_id" class="form-select" onchange="onMandatoryChange()">
<option value="">Select City</option>
</select>
</div>

<!-- Optional fields -->
<div class="col-md-6">
<label class="form-label">Latitude<span class="text-danger">*</span></label>
<input id="latitude" class="form-control">
</div>

<div class="col-md-6">
<label class="form-label">Longitude<span class="text-danger">*</span></label>
<input id="longitude" class="form-control">
</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-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:250px"></div>
</div>

<div class="col-12 text-end">
<button
    class="btn btn-success"
    id="createBtn"
    disabled
    onclick="createDealer()"
>
Create Dealer
</button>
</div>

<div class="col-12">
<div id="createAlert"></div>
</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 ?>";
let CSRF_TOKEN = null;

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

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

/* 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=>{
    dealer_type_id.innerHTML =
        '<option value="">Select Dealer Type</option>';
    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=>{
    cst_id.innerHTML =
        '<option value="">Select CST Manager</option>';
    r.data.forEach(c=>{
        cst_id.innerHTML +=
            `<option value="${c.id}">${c.name}</option>`;
    });
});

fetch(`${ADMIN}api/lookups/states.php`)
.then(r=>r.json()).then(r=>{
    state_id.innerHTML =
        '<option value="">Select State</option>';
    r.data.forEach(s=>{
        if(s.status === 'Active'){
            state_id.innerHTML +=
                `<option value="${s.id}">${s.state_name}</option>`;
        }
    });
});

/* State → City */
function loadCities(){
    city_id.innerHTML = '<option value="">Select City</option>';
    slug_preview.value = '';
    onMandatoryChange();

    if(!state_id.value) return;

    fetch(`${ADMIN}api/lookups/cities.php?state_id=${state_id.value}`)
    .then(r=>r.json())
    .then(r=>{
        r.data.forEach(c=>{
            if(c.status === 'Active'){
                city_id.innerHTML += `
                    <option value="${c.id}"
                            data-city="${c.city_name}">
                        ${c.city_name}
                    </option>`;
            }
        });
    });
}

/* Slug Preview */
function updateSlugPreview(){
    const name = dealer_name.value.trim();
    const opt = city_id.options[city_id.selectedIndex];
    const cityName = opt ? opt.getAttribute('data-city') : '';

    if(!name || !cityName){
        slug_preview.value = '';
        return;
    }

    slug_preview.value =
        `${name}-kingkoil-showroom-in-${cityName}`
        .toLowerCase()
        .replace(/[^a-z0-9]+/g,'-')
        .replace(/^-+|-+$/g,'');
}

/* Enable / Disable Create Button */
function onMandatoryChange(){
    updateSlugPreview();

    const ready =
        dealer_name.value.trim() &&
        dealer_type_id.value &&
        cst_id.value &&
        state_id.value &&
        city_id.value;

    createBtn.disabled = !ready;
}

/* CREATE DEALER */
function createDealer(){
    if(!CSRF_TOKEN){
        show('danger','Security token not ready');
        return;
    }

    fetch(`${ADMIN}api/dealers/create.php`,{
        method:'POST',
        headers:{
            'Content-Type':'application/json',
            'X-CSRF-TOKEN': CSRF_TOKEN
        },
        body: JSON.stringify({
            dealer_name: dealer_name.value.trim(),
            dealer_type_id: dealer_type_id.value,
            cst_id: cst_id.value,
            state_id: state_id.value,
            city_id: city_id.value,
            latitude: latitude.value,
            longitude: longitude.value,
            contact_person: contact_person.value,
            address_line1: address_line1.value,
            address_line2: address_line2.value,
            pincode: pincode.value,
            email: email.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('success', r.message + ' Redirecting...');
            setTimeout(()=>{
                window.location.href = 'list.php';
            }, 1200);
        }else{
            show('danger', r.message);
        }
    })
    .catch(()=>{
        show('danger','Network error');
    });
}
</script>

</body>
</html>
