<?php
declare(strict_types=1);

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

$role = $_SESSION['role'] ?? '';
$isAdmin = in_array($role, ['Admin', 'Super Admin'], true);
$isSuperAdmin = ($role === 'Super Admin');
?>
<!DOCTYPE html>
<html lang="en">
<head>

<?php includeFileWithVariables(
    __DIR__ . '/../partials/title-meta.php',
    ['title' => 'Dealers']
); ?>

<link rel="stylesheet" href="<?= ADMIN_BASE_URL ?>assets/libs/air-datepicker/air-datepicker.css">
<link rel="stylesheet" href="<?= ADMIN_BASE_URL ?>assets/libs/choices.js/public/assets/styles/choices.min.css">
<?php include __DIR__ . '/../partials/head-css.php'; ?>

</head>
<body>

<div id="layout-wrapper">
<?php include __DIR__ . '/../partials/header.php'; ?>
<?php include __DIR__ . '/../partials/sidebar.php'; ?>
<?php include __DIR__ . '/../partials/horizontal.php'; ?>

<main class="app-wrapper">
<div class="container-fluid">

<?php includeFileWithVariables(
    __DIR__ . '/../partials/page-title.php',
    ['title_sub' => 'Masters', 'title' => 'Dealers']
); ?>

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

<div class="card-header d-flex justify-content-between align-items-center">
<h6 class="mb-0">Dealer List</h6>
<a href="<?= ADMIN_BASE_URL ?>dealers/create.php" class="btn btn-primary">
<i class="bi bi-plus-lg me-1"></i> Add Dealer
</a>
</div>

<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered align-middle text-nowrap">
<thead class="table-light">
<tr>
<th>#</th>
<th>Dealer Name</th>
<th>Dealer Type</th>
<th>Location</th>
<th>Status</th>
<th>Approval</th>
<th>Created</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="dealerTableBody">
<tr>
<td colspan="8" class="text-center text-muted">Loading dealers…</td>
</tr>
</tbody>
</table>
</div>
</div>

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

</div>
</main>

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

<?php include __DIR__ . '/../partials/vendor-scripts.php'; ?>

<!-- ================= TOAST ================= -->
<div class="toast-container position-fixed top-0 end-0 p-3" style="z-index:1100">
    <div id="appToast" class="toast align-items-center border-0" role="alert">
        <div class="d-flex">
            <div class="toast-body" id="toastMessage"></div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto"
                    data-bs-dismiss="toast"></button>
        </div>
    </div>
</div>

<!-- STATUS MODAL -->
<div class="modal fade" id="statusModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h6 class="modal-title">Update Dealer Status</h6>
<button class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<select id="newStatus" class="form-select">
<option value="Active">Active</option>
<option value="Inactive">Inactive</option>
<option value="Draft">Draft</option>
</select>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button class="btn btn-primary" onclick="confirmStatus()">Update</button>
</div>
</div>
</div>
</div>

<!-- APPROVAL MODAL -->
<div class="modal fade" id="approvalModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h6 class="modal-title">Approval Action</h6>
<button class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<textarea id="rejectReason" class="form-control"
placeholder="Rejection reason (required for reject)"></textarea>
</div>
<div class="modal-footer">
<button class="btn btn-success" onclick="approveDealer()">Approve</button>
<button class="btn btn-danger" onclick="rejectDealer()">Reject</button>
</div>
</div>
</div>
</div>

<script>
const ADMIN = "<?= ADMIN_BASE_URL ?>";
const IS_ADMIN = <?= $isAdmin ? 'true' : 'false' ?>;
const IS_SUPER_ADMIN = <?= $isSuperAdmin ? 'true' : 'false' ?>;

let CSRF_TOKEN = null;
let selectedDealerId = null;

/* ================= TOAST HELPER ================= */
function showToast(type, message) {
    const toastEl = document.getElementById('appToast');
    const toastBody = document.getElementById('toastMessage');

    toastEl.className = `toast align-items-center text-bg-${type} border-0`;
    toastBody.innerText = message;

    new bootstrap.Toast(toastEl, { delay: 3000 }).show();
}

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

/* LOAD DEALERS */
async function loadDealers(){
    const tbody = dealerTableBody;

    try {
        const res = await fetch(`${ADMIN}api/dealers/list.php`, {
            credentials: 'include'
        });
        const json = await res.json();

        if(json.status !== 'success'){
            showToast('danger', json.message);
            return;
        }

        tbody.innerHTML = json.data.items.map((d,i)=>`
<tr>
<td>${i+1}</td>
<td>${d.dealer_name}</td>
<td>${d.dealer_type}</td>
<td>${d.city_name}, ${d.state_name}</td>

<td>
<span class="badge bg-secondary ${IS_ADMIN?'cursor-pointer':''}"
${IS_ADMIN?`onclick="openStatus(${d.id},'${d.status}')"`:''}>
${d.status}
</span>
</td>

<td>
<span class="badge bg-warning ${IS_ADMIN?'cursor-pointer':''}"
${IS_ADMIN?`onclick="openApproval(${d.id})"`:''}>
${d.approval_status}
</span>
</td>

<td>${d.created_at}</td>

<td>
<button class="btn btn-light-info icon-btn-sm me-1"
onclick="viewDealer(${d.id})">
<i class="bi bi-eye"></i>
</button>

${IS_ADMIN ? `
<a href="edit.php?id=${d.id}"
class="btn btn-light-primary icon-btn-sm me-1">
<i class="bi bi-pencil-square"></i>
</a>` : ''}

${IS_SUPER_ADMIN ? `
<button class="btn btn-light-danger icon-btn-sm"
onclick="deleteDealer(${d.id})">
<i class="bi bi-trash"></i>
</button>` : ''}
</td>
</tr>
`).join('');

    } catch {
        showToast('danger', 'Failed to load dealers');
    }
}

/* VIEW */
function viewDealer(id){
    window.location.href = `view.php?id=${id}`;
}

/* DELETE */
function deleteDealer(id){
    if(!IS_SUPER_ADMIN) return;
    if(!CSRF_TOKEN){
        showToast('warning','Security token not ready');
        return;
    }
    if(!confirm('This will permanently delete the dealer. Continue?')) return;

    fetch(`${ADMIN}api/dealers/delete.php`,{
        method:'POST',
        credentials:'include',
        headers:{
            'Content-Type':'application/json',
            'X-CSRF-TOKEN':CSRF_TOKEN
        },
        body:JSON.stringify({dealer_id:id})
    })
    .then(r=>r.json())
    .then(r=>{
        r.status==='success'
            ? showToast('success',r.message)
            : showToast('danger',r.message);
        loadDealers();
    });
}

/* STATUS */
function openStatus(id,status){
    selectedDealerId=id;
    newStatus.value=status;
    new bootstrap.Modal(statusModal).show();
}
function confirmStatus(){
    fetch(`${ADMIN}api/dealers/status-update.php`,{
        method:'POST',
        credentials:'include',
        headers:{
            'Content-Type':'application/json',
            'X-CSRF-TOKEN':CSRF_TOKEN
        },
        body:JSON.stringify({
            dealer_id:selectedDealerId,
            status:newStatus.value
        })
    }).then(r=>r.json()).then(r=>{
        showToast(r.status==='success'?'success':'danger',r.message);
        bootstrap.Modal.getInstance(statusModal).hide();
        loadDealers();
    });
}

/* APPROVAL */
function openApproval(id){
    selectedDealerId=id;
    rejectReason.value='';
    new bootstrap.Modal(approvalModal).show();
}
function approveDealer(){
    fetch(`${ADMIN}api/dealers/approve.php`,{
        method:'POST',
        credentials:'include',
        headers:{
            'Content-Type':'application/json',
            'X-CSRF-TOKEN':CSRF_TOKEN
        },
        body:JSON.stringify({dealer_id:selectedDealerId})
    }).then(r=>r.json()).then(r=>{
        showToast(r.status==='success'?'success':'danger',r.message);
        bootstrap.Modal.getInstance(approvalModal).hide();
        loadDealers();
    });
}
function rejectDealer(){
    if(!rejectReason.value.trim()){
        showToast('warning','Rejection reason required');
        return;
    }
    fetch(`${ADMIN}api/dealers/reject.php`,{
        method:'POST',
        credentials:'include',
        headers:{
            'Content-Type':'application/json',
            'X-CSRF-TOKEN':CSRF_TOKEN
        },
        body:JSON.stringify({
            dealer_id:selectedDealerId,
            rejection_reason:rejectReason.value
        })
    }).then(r=>r.json()).then(r=>{
        showToast(r.status==='success'?'success':'danger',r.message);
        bootstrap.Modal.getInstance(approvalModal).hide();
        loadDealers();
    });
}

/* INIT */
loadDealers();
</script>

</body>
</html>
