<?php $users = $users ?? []; ?>

<div class="page-header">
    <div class="page-header-left">
        <h1 class="page-title">User Management</h1>
        <p class="page-subtitle">Manage administrator accounts</p>
    </div>
    <div class="page-header-right">
        <button class="btn btn-primary" onclick="showCreateUserModal()">
            <i class="fas fa-plus"></i> Add User
        </button>
    </div>
</div>

<div class="card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Username</th>
                        <th>Email</th>
                        <th>Role</th>
                        <th>Status</th>
                        <th>Last Login</th>
                        <th>Created</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users['data'] as $user): ?>
                        <tr>
                            <td><?= $user['id'] ?></td>
                            <td><?= htmlspecialchars($user['username']) ?></td>
                            <td><?= htmlspecialchars($user['email']) ?></td>
                            <td>
                                <span class="badge badge-<?= $user['role'] === 'super_admin' ? 'danger' : ($user['role'] === 'admin' ? 'warning' : 'info') ?>">
                                    <?= htmlspecialchars(ucfirst(str_replace('_', ' ', $user['role']))) ?>
                                </span>
                            </td>
                            <td>
                                <span class="status-badge <?= $user['is_active'] ? 'status-online' : 'status-offline' ?>">
                                    <?= $user['is_active'] ? 'Active' : 'Inactive' ?>
                                </span>
                            </td>
                            <td><?= $user['last_login_at'] ?? 'Never' ?></td>
                            <td><?= date('Y-m-d', strtotime($user['created_at'] ?? '')) ?></td>
                            <td>
                                <button class="btn btn-xs" onclick="editUser(<?= $user['id'] ?>, '<?= htmlspecialchars(addslashes($user['username'])) ?>', '<?= htmlspecialchars(addslashes($user['email'])) ?>', '<?= $user['role'] ?>', <?= $user['is_active'] ?>)">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button class="btn btn-xs btn-danger" onclick="deleteUser(<?= $user['id'] ?>, '<?= htmlspecialchars(addslashes($user['username'])) ?>')">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <?php if ($users['total_pages'] > 1): ?>
            <div class="pagination">
                <?php for ($i = 1; $i <= $users['total_pages']; $i++): ?>
                    <a href="?page=<?= $i ?>" class="page-link <?= $i === ($users['page'] ?? 1) ? 'active' : '' ?>">
                        <?= $i ?>
                    </a>
                <?php endfor; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<div class="modal" id="userModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modalTitle">Create User</h3>
                <button class="modal-close" onclick="closeModal()">&times;</button>
            </div>
            <div class="modal-body">
                <form id="userForm">
                    <input type="hidden" name="_csrf_token" value="<?= $this->csrfToken() ?>">
                    <input type="hidden" id="userId" value="">

                    <div class="form-group">
                        <label for="modalUsername">Username</label>
                        <input type="text" id="modalUsername" name="username" class="form-input" required minlength="3">
                    </div>
                    <div class="form-group">
                        <label for="modalEmail">Email</label>
                        <input type="email" id="modalEmail" name="email" class="form-input" required>
                    </div>
                    <div class="form-group">
                        <label for="modalPassword">Password</label>
                        <input type="password" id="modalPassword" name="password" class="form-input" minlength="8">
                        <small class="form-hint" id="passwordHint">Minimum 8 characters</small>
                    </div>
                    <div class="form-group">
                        <label for="modalRole">Role</label>
                        <select id="modalRole" name="role" class="form-select" required>
                            <option value="admin" selected>Administrator</option>
                            <option value="operator">Operator</option>
                            <option value="super_admin">Super Administrator</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="checkbox-label">
                            <input type="checkbox" id="modalActive" name="is_active" value="1" checked>
                            <span>Active</span>
                        </label>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" onclick="closeModal()">Cancel</button>
                <button class="btn btn-primary" id="saveUserBtn" onclick="saveUser()">Save</button>
            </div>
        </div>
    </div>
</div>

<script>
function showCreateUserModal() {
    document.getElementById('modalTitle').textContent = 'Create User';
    document.getElementById('userId').value = '';
    document.getElementById('modalUsername').value = '';
    document.getElementById('modalEmail').value = '';
    document.getElementById('modalPassword').value = '';
    document.getElementById('modalPassword').required = true;
    document.getElementById('passwordHint').style.display = 'block';
    document.getElementById('modalRole').value = 'admin';
    document.getElementById('modalActive').checked = true;
    document.getElementById('saveUserBtn').textContent = 'Create';
    document.getElementById('userModal').style.display = 'flex';
}

function editUser(id, username, email, role, isActive) {
    document.getElementById('modalTitle').textContent = 'Edit User';
    document.getElementById('userId').value = id;
    document.getElementById('modalUsername').value = username;
    document.getElementById('modalEmail').value = email;
    document.getElementById('modalPassword').value = '';
    document.getElementById('modalPassword').required = false;
    document.getElementById('passwordHint').style.display = 'none';
    document.getElementById('modalRole').value = role;
    document.getElementById('modalActive').checked = !!isActive;
    document.getElementById('saveUserBtn').textContent = 'Update';
    document.getElementById('userModal').style.display = 'flex';
}

function closeModal() {
    document.getElementById('userModal').style.display = 'none';
}

function saveUser() {
    const id = document.getElementById('userId').value;
    const formData = new FormData(document.getElementById('userForm'));

    const isEdit = !!id;
    const url = isEdit ? '/admin/users/' + id + '/update' : '/admin/users/create';

    fetch(url, {
        method: 'POST',
        headers: {
            'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]')?.content || '',
        },
        body: new URLSearchParams(formData),
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            showToast('success', data.message);
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast('error', data.message);
        }
        closeModal();
    })
    .catch(err => showToast('error', 'Failed to save user'));
}

function deleteUser(id, username) {
    if (!confirm('Are you sure you want to delete user "' + username + '"?')) return;

    fetch('/admin/users/' + id + '/delete', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]')?.content || '',
        },
        body: '_csrf_token=' + encodeURIComponent(document.querySelector('meta[name="csrf-token"]')?.content || ''),
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) location.reload();
        else showToast('error', data.message);
    });
}
</script>
