<?php

declare(strict_types=1);

require_once __DIR__ . '/../core/web_bootstrap.php';
require_once __DIR__ . '/../core/permissions.php';

/* ----------------------------------------------------------
   SESSION AUTH CHECK
---------------------------------------------------------- */

if (empty($_SESSION['user']) || empty($_SESSION['api_token'])) {
    header('Location: login.php');
    exit;
}

$user = $_SESSION['user'];

/* ----------------------------------------------------------
   RBAC CHECK
---------------------------------------------------------- */

if (!can($user, 'users', 'view', $pdo)) {
    http_response_code(403);
    die('Access denied.');
}

$canCreate = can($user, 'users', 'create', $pdo);
$canEdit   = can($user, 'users', 'edit', $pdo);

?>

<?php require 'partials/header.php'; ?>
<?php require 'partials/nav.php'; ?>

<h3>Users Management</h3>

<?php if ($canCreate): ?>
<div class="card mb-4 p-3">
    <h5>Create User</h5>
    <div class="row">
        <div class="col-md-2">
            <input type="text" id="firstName" class="form-control" placeholder="First Name">
        </div>
        <div class="col-md-2">
            <input type="text" id="lastName" class="form-control" placeholder="Last Name">
        </div>
        <div class="col-md-3">
            <input type="email" id="email" class="form-control" placeholder="Email">
        </div>
        <div class="col-md-2">
            <select id="role" class="form-select"></select>
        </div>
        <div class="col-md-2">
            <select id="companySelect" class="form-select"></select>
        </div>
        <div class="col-md-1">
            <button class="btn btn-primary" onclick="createUser()">+</button>
        </div>
    </div>
</div>
<?php endif; ?>

<table class="table table-bordered table-striped">
    <thead class="table-dark">
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Role</th>
            <th>Company</th>
            <th>RSP</th>
            <th>Status</th>
            <?php if ($canEdit): ?>
                <th>Action</th>
            <?php endif; ?>
        </tr>
    </thead>
    <tbody id="userTable"></tbody>
</table>

<script>
const token = '<?= htmlspecialchars($_SESSION['api_token'], ENT_QUOTES, 'UTF-8') ?>';
const canCreate = <?= $canCreate ? 'true' : 'false' ?>;
const canEdit   = <?= $canEdit ? 'true' : 'false' ?>;

function escapeHtml(text) {
    if (!text) return '';
    return text
        .toString()
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}

/* Roles loaded from API — NEVER hardcoded */
function loadRoles() {
    fetch('/api/admin/get_roles.php', {
        headers: { 'Authorization': 'Bearer ' + token }
    })
    .then(res => res.json())
    .then(data => {

        if (!data.success) return;

        let options = '';
        const roles = data.data.roles || [];

        roles.forEach(r => {
            options += `<option value="${escapeHtml(r.role_key)}">
                ${escapeHtml(r.role_label)}
            </option>`;
        });

        document.getElementById('role').innerHTML = options;
    });
}

function loadCompanies() {
    fetch('/api/admin/get_companies.php', {
        headers: { 'Authorization': 'Bearer ' + token }
    })
    .then(res => res.json())
    .then(data => {

        if (!data.success) return;

        let options = '';
        const companies = data.data.companies || [];

        companies.forEach(c => {
            options += `<option value="${c.id}">
                ${escapeHtml(c.company_name)}
            </option>`;
        });

        document.getElementById('companySelect').innerHTML = options;
    });
}

function loadUsers() {
    fetch('/api/admin/get_users.php', {
        headers: { 'Authorization': 'Bearer ' + token }
    })
    .then(res => res.json())
    .then(data => {

        if (!data.success) return;

        let rows = '';
        const users = data.data.users || [];

        users.forEach(u => {

            rows += `
                <tr>
                    <td>${u.id}</td>
                    <td>${escapeHtml(u.first_name)} ${escapeHtml(u.last_name)}</td>
                    <td>${escapeHtml(u.email)}</td>
                    <td>${escapeHtml(u.role)}</td>
                    <td>${escapeHtml(u.company_name ?? '-')}</td>
                    <td>${escapeHtml(u.rsp_name ?? '-')}</td>
                    <td>
                        <span class="badge ${u.status === 'active' ? 'bg-success' : 'bg-danger'}">
                            ${escapeHtml(u.status)}
                        </span>
                    </td>
            `;

            if (canEdit) {
                rows += `
                    <td>
                        <button class="btn btn-sm btn-warning"
                            onclick="toggleStatus(${u.id})">
                            Toggle
                        </button>
                    </td>
                `;
            }

            rows += `</tr>`;
        });

        document.getElementById('userTable').innerHTML = rows;
    });
}

function createUser() {

    if (!canCreate) return;

    const payload = {
        first_name: document.getElementById('firstName').value.trim(),
        last_name:  document.getElementById('lastName').value.trim(),
        email:      document.getElementById('email').value.trim(),
        role:       document.getElementById('role').value,
        company_id: document.getElementById('companySelect').value
    };

    if (!payload.first_name || !payload.last_name || !payload.email) {
        alert('All fields are required.');
        return;
    }

    fetch('/api/admin/create_user.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + token
        },
        body: JSON.stringify(payload)
    })
    .then(res => res.json())
    .then(data => {

        if (!data.success) return alert(data.message);

        alert('Temporary Password: ' + data.data.temporary_password);

        document.getElementById('firstName').value = '';
        document.getElementById('lastName').value = '';
        document.getElementById('email').value = '';

        loadUsers();
    });
}

function toggleStatus(id) {

    if (!canEdit) return;

    fetch('/api/admin/toggle_user_status.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + token
        },
        body: JSON.stringify({ user_id: id })
    })
    .then(res => res.json())
    .then(data => {
        if (!data.success) return alert(data.message);
        loadUsers();
    });
}

if (canCreate) {
    loadRoles();
    loadCompanies();
}

loadUsers();

</script>

<?php require 'partials/footer.php'; ?>