<div class="container-fluid pt-4 px-4">
    <div class="card shadow-lg mb-4">
        
        <div class="card-header bg-white py-3 d-flex justify-content-between align-items-center">
            <h5 class="m-0 font-weight-bold text-primary">
                <i class="fas fa-users-cog me-2"></i> User Account Master Data
            </h5>
            <a href="<?php echo site_url('Admin/Akun/masteruser/input') ?>" class="btn btn-primary btn-sm">
                <i class="fas fa-plus me-1"></i> Add New User
            </a>
        </div>
        
        <div class="card-body">
            
            <div id="flash" data-flash="<?=$this->session->flashdata('pesan_success'); ?>"></div> 
            <?php if ($this->session->flashdata('pesan_error')): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-triangle me-2"></i>
                <?php echo $this->session->flashdata('pesan_error'); // Keeping 'pesan_error' since it's a variable name ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            <?php endif; ?> 

            <div class="row mb-3 align-items-center">
                
                <div class="col-md-4 col-lg-3">
                    <label for="filterRole" class="form-label fw-bold">Filter by Role:</label>
                    <select id="filterRole" class="form-select" onchange="filterTable()">
                        <option value="">All Roles</option>
                        <option value="Admin">Admin</option>
                        <option value="Manager">Manager</option>
                        <option value="Super Admin">Super Admin</option>
                        <option value="Workshop">Workshop</option>
                        <option value="User">User</option>
                    </select>
                </div>
            </div>

            <div class="table-responsive">
                <table class="table table-bordered table-hover table-striped w-100" id="datatables">
                    <thead class="bg-light">
                        <tr>
                            <th style="width: 5%;">No.</th>
                            <th>Full Name</th>
                            <th style="width: 15%;">Role</th>
                            <th style="width: 30%;">Email</th>
                            <th class="text-center" style="width: 15%;">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $i = 1; // Start from 1 for neat counting ?>
                        <?php foreach ($user as $u): ?>
                            <tr>
                                <td><?php echo $i++ ?></td>
                                <td><?php echo $u->nama_user // Keeping variable name ?></td> 
                                <td>
                                    <?php 
                                         // Logic to display role badge
                                         $role_lower = strtolower($u->role);
                                         $role_display = ucwords($role_lower);
                                         $badge_class = 'bg-secondary';
                                         
                                         if ($role_lower === 'admin') {
                                             $badge_class = 'bg-danger';
                                         } elseif ($role_lower === 'manager') {
                                             $badge_class = 'bg-warning text-dark';
                                         } elseif ($role_lower === 'pc') {
                                             $role_display = 'Project Coordinator';
                                             $badge_class = 'bg-info';
                                         } elseif ($role_lower === 'workshop') {
                                             $badge_class = 'bg-primary';
                                         } elseif ($role_lower === 'crew') {
                                             $badge_class = 'bg-dark';
                                         } elseif ($role_lower === 'user') {
                                             $badge_class = 'bg-success';
                                         }
                                    ?>
                                    <span class="badge <?= $badge_class ?> fw-bold"><?= $role_display ?></span>
                                </td>
                                <td><?php echo $u->email ?></td>

                                <td class="text-center">
                                    <a href="<?= base_url('Admin/Akun/masteruser/view_detail/'.$u->id_akun) ?>" class="btn btn-sm btn-info" data-bs-toggle="tooltip" title="View Detail">
                                        <i class="fas fa-eye"></i> 
                                    </a>
                                    <a href="<?= base_url('Admin/Akun/masteruser/view_ubah/'.$u->id_akun) ?>" class="btn btn-sm btn-warning" data-bs-toggle="tooltip" title="Edit Data">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="<?= base_url('Admin/Akun/masteruser/hapus/'.$u->id_akun) ?>" class="btn btn-sm btn-danger tombol-hapus-js" data-nama-user="<?= $u->nama_user ?>" data-bs-toggle="tooltip" title="Delete Account"> 
                                        <i class="fas fa-trash-alt"></i> 
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table> 
            </div> 
        </div>
    </div>
</div>

<script>
    // FUNCTION FOR TOOLTIP (Requires Bootstrap JS Bundle)
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
      return new bootstrap.Tooltip(tooltipTriggerEl)
    })

    // FUNCTION TO FILTER TABLE (Simplified)
    function filterTable() {
        var filterValue = document.getElementById("filterRole").value.toLowerCase();
        var table = document.getElementById("datatables");
        // Assuming DataTables is initialized, we use its API if available
        // If not, your previous manual JS code was correct, we just tweak it slightly:

        var rows = table.getElementsByTagName("tr");
        for (var i = 1; i < rows.length; i++) {
            var roleCell = rows[i].getElementsByTagName("td")[2];
            if (roleCell) {
                // Get text from the badge (covers all roles)
                var roleText = roleCell.querySelector('.badge').textContent || roleCell.querySelector('.badge').innerText; 
                if (filterValue === "" || roleText.toLowerCase().includes(filterValue)) {
                    rows[i].style.display = "";
                } else {
                    rows[i].style.display = "none";
                }
            } 
        }
    }
    
    // FUNCTION FOR DELETE CONFIRMATION WITH SWEETALERT/STANDARD CONFIRM (Optional)
    document.querySelectorAll('.tombol-hapus-js').forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            const href = this.getAttribute('href');
            const namaUser = this.getAttribute('data-nama-user'); // Keeping 'namaUser' since it's a variable name

            if (confirm(`Are you sure you want to delete the account "${namaUser}"? Deleted data cannot be recovered.`)) {
                window.location.href = href;
            }
        });
    });
</script>