<?php
require 'auth.php';
requireAdmin();
require 'db.php';

$message = '';
$selectedUser = null;

// Fetch all users with full info for the list and modal
$users = $pdo->query("SELECT id, username, full_name, email, user_role, phone, access_group FROM users ORDER BY username")->fetchAll(PDO::FETCH_ASSOC);



// When a user is selected
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['select_user'])) {
    $userId = $_POST['user_id'];
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $selectedUser = $stmt->fetch(PDO::FETCH_ASSOC);
}

// When user info is updated
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_user'])) {
    $userId     = $_POST['user_id'];
    $full_name  = $_POST['full_name'];
    $email      = $_POST['email'];
    $phone      = $_POST['phone'];
    $user_role  = $_POST['user_role'];
    $access_group = $_POST['access_group'];

    $stmt = $pdo->prepare("UPDATE users SET full_name = ?, email = ?, phone = ?, user_role = ?, access_group = ? WHERE id = ?");
    $stmt->execute([$full_name, $email, $phone, $user_role, $access_group, $userId]);

    $message = "User updated successfully.";

    // Reload updated user
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $selectedUser = $stmt->fetch(PDO::FETCH_ASSOC);
}
?>

<?php include 'header.php'; ?>

<div class="container mt-4">
    <h2><?= t('Users') ?>
    <a href="add_user.php">
        <button name="add_user" class="btn btn-success"><?= t('Add user') ?></button>
    </a>
</h2>

<?php if ($message): ?>
    <div class="alert alert-success"><?= htmlspecialchars(t($message)) ?></div>
<?php endif; ?>

<div class="mb-3">
    <label for="filterRole" class="form-label"><?= t('Filter by Role') ?></label>
    <select id="filterRole" class="form-select">
        <option value=""><?= t('All Roles') ?></option>
        <option value="Admin"><?= t('Admin') ?></option>
        <option value="Operator"><?= t('Operator') ?></option>
        <option value="Installer"><?= t('Installer') ?></option>
        <option value="Client"><?= t('Client') ?></option>
    </select>
</div>

<div class="mb-3">
    <label for="searchUser" class="form-label"><?= t('Search User') ?></label>
    <input type="text" id="searchUser" class="form-control" placeholder="<?= t('Search by name, username, or email...') ?>">
</div>

<table class="table table-hover" id="userTable" style="cursor: pointer;">
    <thead>
        <tr>
            <th><?= t('Full Name') ?></th>
            <th><?= t('Username') ?></th>
            <th><?= t('Email') ?></th>
            <th><?= t('Role') ?></th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($users as $user): ?>
            <tr
                data-user='<?= json_encode($user, JSON_HEX_APOS | JSON_HEX_QUOT) ?>'
                data-role="<?= htmlspecialchars($user['user_role']) ?>"
            >
                <td><?= htmlspecialchars($user['full_name']) ?></td>
                <td><?= htmlspecialchars($user['username']) ?></td>
                <td><?= htmlspecialchars($user['email']) ?></td>
                <td><?= htmlspecialchars($user['user_role']) ?></td>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>

</div>

<!-- Modal -->
<div class="modal fade" id="editUserModal" tabindex="-1" aria-labelledby="editUserModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <form id="editUserForm" method="POST" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="editUserModalLabel"><?= t('Edit User') ?></h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
            <input type="hidden" name="user_id" id="modal_user_id">
            <div class="mb-3">
                <label class="form-label"><?= t('Full Name') ?></label>
                <input type="text" name="full_name" id="modal_full_name" class="form-control" required>
            </div>
            <div class="mb-3">
                <label class="form-label"><?= t('Email') ?></label>
                <input type="email" name="email" id="modal_email" class="form-control" required>
            </div>
            <div class="mb-3">
                <label class="form-label"><?= t('Phone') ?></label>
                <input type="text" name="phone" id="modal_phone" class="form-control">
            </div>
            <div class="mb-3">
                <label class="form-label"><?= t('Role') ?></label>
                <select name="user_role" id="modal_user_role" class="form-select" required>
                    <?php foreach (['Admin', 'Operator', 'Installer', 'Client'] as $role): ?>
                        <option value="<?= $role ?>"><?= $role ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label"><?= t('Access Group') ?></label>
                <input type="text" name="access_group" id="modal_access_group" class="form-control">
            </div>
      </div>
      <div class="modal-footer">
        <button type="submit" name="update_user" class="btn btn-success"><?= t('Update User') ?></button>
    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?= t('Cancel') ?></button>
      </div>
    </form>
  </div>
</div>

<script>
const searchInput = document.getElementById('searchUser');
const roleFilter = document.getElementById('filterRole');
const userTable = document.getElementById('userTable');
const rows = userTable.querySelectorAll('tbody tr');

function filterTable() {
    const searchTerm = searchInput.value.toLowerCase();
    const selectedRole = roleFilter.value;

    rows.forEach(row => {
        const user = JSON.parse(row.getAttribute('data-user'));
        const matchesSearch =
            user.full_name.toLowerCase().includes(searchTerm) ||
            user.username.toLowerCase().includes(searchTerm) ||
            user.email.toLowerCase().includes(searchTerm);

        const matchesRole = selectedRole === '' || user.user_role === selectedRole;

        row.style.display = (matchesSearch && matchesRole) ? '' : 'none';
    });
}

searchInput.addEventListener('input', filterTable);
roleFilter.addEventListener('change', filterTable);

// Show modal on row click with user data
rows.forEach(row => {
    row.addEventListener('click', () => {
        const user = JSON.parse(row.getAttribute('data-user'));
        document.getElementById('modal_user_id').value = user.id;
        document.getElementById('modal_full_name').value = user.full_name;
        document.getElementById('modal_email').value = user.email;
        document.getElementById('modal_phone').value = user.phone || '';
        document.getElementById('modal_user_role').value = user.user_role;
        document.getElementById('modal_access_group').value = user.access_group || '';
        new bootstrap.Modal(document.getElementById('editUserModal')).show();
    });
});

</script>

<?php include 'footer.php'; ?>
