<?php
declare(strict_types=1);

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

$role = $_SESSION['role'] ?? '';
$isAdmin = in_array($role, ['Admin', 'Super Admin'], true);
$isSuperAdmin = ($role === 'Super Admin');

$db = Database::getInstance();

/**
 * Fetch roles for edit dropdown (exclude Super Admin)
 */
$stmt = $db->prepare("
    SELECT id, name
    FROM roles
    WHERE name != 'Super Admin'
    ORDER BY level DESC
");
$stmt->execute();
$roles = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>

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

<?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' => 'Users', 'title' => 'Employees']
); ?>

<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">Employee List</h6>

    <?php if ($isAdmin): ?>
    <a href="<?= ADMIN_BASE_URL ?>employees/create.php" class="btn btn-primary">
        <i class="bi bi-plus-lg me-1"></i> Add Employee
    </a>
    <?php endif; ?>
</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>Name</th>
    <th>Email</th>
    <th>Mobile</th>
    <th>Role</th>
    <th>Status</th>
    <th>Last Login</th>
    <th>Created</th>
    <th>Actions</th>
</tr>
</thead>

<tbody id="employeeTableBody">
<tr>
<td colspan="9" class="text-center text-muted">Loading employees…</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">
<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>

<!-- ================= VIEW MODAL ================= -->
<div class="modal fade" id="viewModal" tabindex="-1">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h6 class="modal-title">Employee Details</h6>
<button class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body" id="viewBody"></div>
</div>
</div>
</div>

<!-- ================= EDIT MODAL ================= -->
<div class="modal fade" id="editModal" tabindex="-1">
<div class="modal-dialog modal-lg modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h6 class="modal-title">Edit Employee</h6>
<button class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">

<input type="hidden" id="edit_id">

<div class="row">
<div class="col-md-6 mb-3">
<label>First Name</label>
<input class="form-control" id="edit_first">
</div>
<div class="col-md-6 mb-3">
<label>Last Name</label>
<input class="form-control" id="edit_last">
</div>
</div>

<div class="row">
<div class="col-md-6 mb-3">
<label>Email</label>
<input class="form-control" id="edit_email">
</div>
<div class="col-md-6 mb-3">
<label>Mobile</label>
<input class="form-control" id="edit_mobile">
</div>
</div>

<div class="row">
<div class="col-md-6 mb-3">
<label>Password (optional)</label>
<input type="password" class="form-control" id="edit_password">
</div>
<div class="col-md-6 mb-3">
<label>Role</label>
<select id="edit_role" class="form-select">
<?php foreach ($roles as $r): ?>
<option value="<?= $r['id'] ?>">
    <?= htmlspecialchars($r['name']) ?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>

<div id="editError" class="alert alert-danger d-none"></div>

</div>
<div class="modal-footer">
<button class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button class="btn btn-primary" onclick="saveEdit()">Save Changes</button>
</div>
</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 Employee 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="suspended">Suspended</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>

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

let CSRF_TOKEN = null;
let selectedEmployeeId = null;

/* ================= TOAST ================= */
function showToast(type,msg){
    const t=document.getElementById('appToast');
    document.getElementById('toastMessage').innerText=msg;
    t.className=`toast align-items-center text-bg-${type} border-0`;
    new bootstrap.Toast(t,{delay:3000}).show();
}

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

/* LOAD EMPLOYEES */
async function loadEmployees(){
    try{
        const r=await fetch(`${ADMIN}api/employees/list.php`,{credentials:'include'});
        const j=await r.json();
        if(j.status!=='success'){showToast('danger',j.message);return;}

        employeeTableBody.innerHTML=j.data.employees.map((e,i)=>`
<tr>
<td>${i+1}</td>
<td>${e.first_name} ${e.last_name}</td>
<td>${e.email}</td>
<td>${e.mobile ?? '-'}</td>
<td>${e.role_name}</td>

<td>
<span class="badge bg-${e.status==='active'?'success':'warning'}
${IS_ADMIN?'cursor-pointer':''}"
${IS_ADMIN?`onclick="openStatusModal(${e.id},'${e.status}')"`:''}>
${e.status}
</span>
</td>

<td>${e.last_login_at ?? '-'}</td>
<td>${e.created_at}</td>

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

${IS_ADMIN?`
<button class="btn btn-light-primary icon-btn-sm me-1"
onclick="openEdit(${e.id},
'${e.first_name}','${e.last_name}','${e.email}','${e.mobile ?? ''}',${e.role_id})">
<i class="bi bi-pencil-square"></i>
</button>`:''}

${IS_SUPER_ADMIN?`
<button class="btn btn-light-danger icon-btn-sm"
onclick="deleteEmployee(${e.id})">
<i class="bi bi-trash"></i>
</button>`:''}
</td>
</tr>
`).join('');
    }catch{
        showToast('danger','Failed to load employees');
    }
}

/* VIEW */
function viewEmployee(id){
fetch(`${ADMIN}api/employees/view.php?id=${id}`,{credentials:'include'})
.then(r=>r.json()).then(j=>{
const e=j.data;
viewBody.innerHTML=`
<b>Name:</b> ${e.first_name} ${e.last_name}<br>
<b>Email:</b> ${e.email}<br>
<b>Mobile:</b> ${e.mobile ?? '-'}<br>
<b>Role:</b> ${e.role_name}<br>
<b>Status:</b> ${e.status}<br>
<b>Last Login:</b> ${e.last_login_at ?? '-'}<br>
<b>Created:</b> ${e.created_at}`;
new bootstrap.Modal(viewModal).show();
});
}

/* EDIT */
function openEdit(id,f,l,e,m,roleId){
edit_id.value=id;
edit_first.value=f;
edit_last.value=l;
edit_email.value=e;
edit_mobile.value=m;
edit_password.value='';
edit_role.value=roleId;   // ✅ FIXED
editError.classList.add('d-none');
new bootstrap.Modal(editModal).show();
}
function saveEdit(){
const d={
employee_id:edit_id.value,
first_name:edit_first.value,
last_name:edit_last.value,
email:edit_email.value,
mobile:edit_mobile.value,
role_id:edit_role.value
};
if(edit_password.value)d.password=edit_password.value;

fetch(`${ADMIN}api/employees/update.php`,{
method:'POST',credentials:'include',
headers:{'Content-Type':'application/json','X-CSRF-TOKEN':CSRF_TOKEN},
body:JSON.stringify(d)
}).then(r=>r.json()).then(j=>{
if(j.status!=='success'){
editError.innerText=j.message;
editError.classList.remove('d-none');
return;
}
bootstrap.Modal.getInstance(editModal).hide();
showToast('success',j.message);
loadEmployees();
});
}

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

/* DELETE */
function deleteEmployee(id){
if(!IS_SUPER_ADMIN)return;
if(!confirm('This will permanently delete the employee. Continue?'))return;

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

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

</body>
</html>
