<?php
require_once '../includes/config.php';
require_once __DIR__ . '/includes/admin_auth.php';
require_once __DIR__ . '/includes/admin_header.php';

requirePermission('manage_users');

// Fetch users
$users = [];
$sql = "SELECT u.id, u.full_name AS name, u.username, u.email, u.phone, u.role_id, u.is_active, u.last_login, r.name AS role_name
        FROM admin_users u
        LEFT JOIN admin_roles r ON u.role_id = r.id
        ORDER BY u.id DESC";
$result = $conn->query($sql);
if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $users[] = $row;
    }
}

// Fetch roles
$roles = [];
$role_result = $conn->query("SELECT id, name FROM admin_roles ORDER BY name ASC");
if ($role_result && $role_result->num_rows > 0) {
    while ($row = $role_result->fetch_assoc()) {
        $roles[] = $row;
    }
}
?>

<div class="admin-content">
    <div class="page-header">
        <h1 class="page-title">Admin Users</h1>
        <ul class="breadcrumb">
            <li><a href="dashboard.php">Dashboard</a></li>
            <li>Users</li>
        </ul>
    </div>

    <div class="table-actions">
        <button onclick="document.getElementById('createUserModal').style.display='block'" class="btn btn-primary">Add User</button>
    </div>

    <table class="data-table">
        <thead>
            <tr>
                <th>Name</th>
                <th>Username</th>
                <th>Email</th>
                <th>Phone</th>
                <th>Role</th>
                <th>Last Login</th>
                <th>Status</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($users as $user): ?>
                <tr>
                    <td><?= htmlspecialchars($user['name']) ?></td>
                    <td><?= htmlspecialchars($user['username']) ?></td>
                    <td><?= htmlspecialchars($user['email']) ?></td>
                    <td><?= htmlspecialchars($user['phone']) ?></td>
                    <td><?= htmlspecialchars($user['role_name']) ?></td>
                    <td><?= $user['last_login'] ? date('M j, Y H:i', strtotime($user['last_login'])) : 'Never' ?></td>
                    <td>
                        <span class="badge <?= $user['is_active'] ? 'success' : 'danger' ?>">
                            <?= $user['is_active'] ? 'Active' : 'Inactive' ?>
                        </span>
                    </td>
                    <td>
                        <button onclick="editUser(
                            <?= $user['id'] ?>,
                            '<?= addslashes($user['name']) ?>',
                            '<?= addslashes($user['username']) ?>',
                            '<?= addslashes($user['email']) ?>',
                            '<?= addslashes($user['phone']) ?>',
                            <?= $user['role_id'] ?>,
                            <?= $user['is_active'] ?>
                        )" class="btn btn-sm">Edit</button>

                        <?php if ($user['id'] != $_SESSION['user']['id']): ?>
                            <a href="user_delete.php?id=<?= $user['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure?')">Delete</a>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<!-- Create User Modal -->
<div id="createUserModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="this.closest('.modal').style.display='none'">&times;</span>
        <form action="user_save.php" method="post">
            <h2>Create User</h2>
            <div class="form-group"><label>Name</label><input type="text" name="name" required></div>
            <div class="form-group"><label>Username</label><input type="text" name="username" required></div>
            <div class="form-group"><label>Email</label><input type="email" name="email" required></div>
            <div class="form-group"><label>Phone</label><input type="text" name="phone"></div>
            <div class="form-group">
                <label>Role</label>
                <select name="role_id" required>
                    <option value="">Select Role</option>
                    <?php foreach ($roles as $role): ?>
                        <option value="<?= $role['id'] ?>"><?= htmlspecialchars($role['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group"><label>Password</label><input type="password" name="password" required></div>
            <div class="form-group"><label>Confirm Password</label><input type="password" name="confirm_password" required></div>
            <div class="form-actions"><button type="submit" class="btn btn-primary">Create</button></div>
        </form>
    </div>
</div>

<!-- Edit User Modal -->
<div id="editUserModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="this.closest('.modal').style.display='none'">&times;</span>
        <form action="user_save.php" method="post">
            <h2>Edit User</h2>
            <input type="hidden" name="id" id="edit_id">
            <div class="form-group"><label>Name</label><input type="text" name="name" id="edit_name" required></div>
            <div class="form-group"><label>Username</label><input type="text" id="edit_username" disabled></div>
            <div class="form-group"><label>Email</label><input type="email" name="email" id="edit_email" required></div>
            <div class="form-group"><label>Phone</label><input type="text" name="phone" id="edit_phone"></div>
            <div class="form-group">
                <label>Role</label>
                <select name="role_id" id="edit_role_id" required>
                    <?php foreach ($roles as $role): ?>
                        <option value="<?= $role['id'] ?>"><?= htmlspecialchars($role['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label>Status</label>
                <select name="is_active" id="edit_is_active">
                    <option value="1">Active</option>
                    <option value="0">Inactive</option>
                </select>
            </div>
            <div class="form-group"><label>New Password <small>(leave blank to keep current)</small></label><input type="password" name="password"></div>
            <div class="form-group"><label>Confirm New Password</label><input type="password" name="confirm_password"></div>
            <div class="form-actions"><button type="submit" class="btn btn-primary">Save Changes</button></div>
        </form>
    </div>
</div>

<script>
function editUser(id, name, username, email, phone, role_id, is_active) {
    document.getElementById('edit_id').value = id;
    document.getElementById('edit_name').value = name;
    document.getElementById('edit_username').value = username;
    document.getElementById('edit_email').value = email;
    document.getElementById('edit_phone').value = phone;
    document.getElementById('edit_role_id').value = role_id;
    document.getElementById('edit_is_active').value = is_active;
    document.getElementById('editUserModal').style.display = 'block';
}
</script>

<?php require_once __DIR__ . '/includes/admin_footer.php'; ?>
