<?php
require_once __DIR__ . '/../../core/helpers.php';
require_once __DIR__ . '/../../templates/header.php';

// Lấy danh sách nhân viên
$users = $conn->query("SELECT * FROM cms_users WHERE user_status = 1 ORDER BY display_name ASC");
?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>

<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h3 text-gray-800">Mã QR Nhân viên</h1>
        <a href="/quanlybanhang/modules/attendance/index.php" class="btn btn-secondary btn-sm"><i class="fas fa-arrow-left"></i> Quay lại</a>
    </div>

    <div class="card shadow mb-4">
        <div class="card-body">
            <input type="text" id="searchQR" class="form-control form-control-lg" placeholder="Nhập tên nhân viên để tìm nhanh...">
        </div>
    </div>

    <div class="row" id="qr-list-container">
        <?php while($u = $users->fetch_assoc()): 
             // Logic hiển thị mã: Ưu tiên user_code, nếu không có thì fallback sang USER_id (nhưng nên dùng user_code)
             $code_val = !empty($u['user_code']) ? $u['user_code'] : 'NV'.str_pad($u['id'], 3, '0', STR_PAD_LEFT);
        ?>
        <div class="col-md-3 mb-4 qr-item" data-name="<?php echo strtolower($u['display_name']); ?>">
            <div class="card border-bottom-warning shadow h-100 py-2">
                <div class="card-body text-center">
                    <div class="font-weight-bold text-primary text-uppercase mb-1"><?php echo $u['display_name']; ?></div>
                    
                    <div id="qrcode_<?php echo $u['id']; ?>" class="d-flex justify-content-center my-3"></div>
                    
                    <div class="small text-gray-500 font-weight-bold"><?php echo $code_val; ?></div>
                </div>
            </div>
            <script>
                // Tạo QR Code
                new QRCode(document.getElementById("qrcode_<?php echo $u['id']; ?>"), {
                    text: "<?php echo $code_val; ?>",
                    width: 128,
                    height: 128,
                    colorDark : "#000000",
                    colorLight : "#ffffff",
                    correctLevel : QRCode.CorrectLevel.H
                });
            </script>
        </div>
        <?php endwhile; ?>
    </div>
</div>

<?php require_once __DIR__ . '/../../templates/footer.php'; ?>

<script>
$(document).ready(function(){
  // Chức năng tìm kiếm nhanh
  $("#searchQR").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#qr-list-container .qr-item").filter(function() {
      $(this).toggle($(this).attr('data-name').indexOf(value) > -1)
    });
  });
});
</script>