<?php
session_start();
require_once '../../config/database.php';
require_once '../../config/function.php';

// Cek login
checkLogin();

$current_user = getCurrentUser();

// Hanya admin yang bisa mengakses halaman users
if ($current_user['role'] != 'admin') {
    $_SESSION['alert'] = [
        'type' => 'error',
        'title' => 'Akses Ditolak!',
        'message' => 'Anda tidak memiliki izin untuk mengakses halaman ini.'
    ];
    header('Location: ../dashboard.php');
    exit;
}

// Ambil data users
$query = "SELECT * FROM bkcare_users ORDER BY 
          CASE role 
              WHEN 'admin' THEN 1 
              WHEN 'guru_bk' THEN 2 
              WHEN 'wali_kelas' THEN 3 
              WHEN 'kepala_sekolah' THEN 4 
              WHEN 'guru' THEN 5
              WHEN 'siswa' THEN 6 
          END, nama ASC";
$result = mysqli_query($conn, $query);

include '../../includes/header.php';
include '../../includes/navbar.php';
?>

<!-- Main Content -->
<main class="container mx-auto px-4 py-6">
    <!-- Header -->
    <div class="flex justify-between items-center mb-6">
        <div>
            <h1 class="text-2xl font-bold text-gray-800 flex items-center">
                <i class="fas fa-users text-purple-600 mr-3"></i>
                Data Pengguna
            </h1>
            <p class="text-gray-600 text-sm mt-1">Kelola data pengguna sistem</p>
        </div>
        <a href="tambah.php" class="btn-primary">
            <i class="fas fa-plus mr-2"></i>Tambah Pengguna
        </a>
    </div>

    <!-- Alert Notification -->
    <?php if (isset($_SESSION['alert'])): ?>
    <div id="alert-notification" class="mb-6 rounded-lg p-4 <?= 
        $_SESSION['alert']['type'] == 'success' ? 'bg-green-50 border-l-4 border-green-500' : 
        ($_SESSION['alert']['type'] == 'error' ? 'bg-red-50 border-l-4 border-red-500' : 
        'bg-yellow-50 border-l-4 border-yellow-500') ?> shadow-md">
        <div class="flex items-start">
            <div class="flex-shrink-0">
                <?php if ($_SESSION['alert']['type'] == 'success'): ?>
                    <i class="fas fa-check-circle text-green-500 text-xl"></i>
                <?php elseif ($_SESSION['alert']['type'] == 'error'): ?>
                    <i class="fas fa-exclamation-circle text-red-500 text-xl"></i>
                <?php else: ?>
                    <i class="fas fa-exclamation-triangle text-yellow-500 text-xl"></i>
                <?php endif; ?>
            </div>
            <div class="ml-3 flex-1">
                <h3 class="text-sm font-medium <?= 
                    $_SESSION['alert']['type'] == 'success' ? 'text-green-800' : 
                    ($_SESSION['alert']['type'] == 'error' ? 'text-red-800' : 
                    'text-yellow-800') ?>">
                    <?= $_SESSION['alert']['title'] ?>
                </h3>
                <div class="mt-1 text-sm <?= 
                    $_SESSION['alert']['type'] == 'success' ? 'text-green-700' : 
                    ($_SESSION['alert']['type'] == 'error' ? 'text-red-700' : 
                    'text-yellow-700') ?>">
                    <?= $_SESSION['alert']['message'] ?>
                </div>
            </div>
            <div class="ml-auto pl-3">
                <button onclick="this.parentElement.parentElement.parentElement.remove()" class="inline-flex <?= 
                    $_SESSION['alert']['type'] == 'success' ? 'text-green-500 hover:text-green-600' : 
                    ($_SESSION['alert']['type'] == 'error' ? 'text-red-500 hover:text-red-600' : 
                    'text-yellow-500 hover:text-yellow-600') ?>">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        </div>
    </div>
    <?php 
    unset($_SESSION['alert']);
    endif; 
    ?>

    <!-- Table -->
    <div class="card-stat p-6">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">No</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Username</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Nama</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Role</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Terdaftar</th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">Aksi</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    <?php if (mysqli_num_rows($result) > 0): ?>
                        <?php $no = 1; ?>
                        <?php while($row = mysqli_fetch_assoc($result)): ?>
                            <tr class="hover:bg-purple-50 transition">
                                <td class="px-6 py-4 text-sm text-gray-600"><?= $no++ ?></td>
                                <td class="px-6 py-4 text-sm font-mono text-gray-600">
                                    <div class="flex items-center">
                                        <div class="w-8 h-8 bg-purple-100 rounded-full flex items-center justify-center mr-2">
                                            <i class="fas fa-user-circle text-purple-600"></i>
                                        </div>
                                        <?= htmlspecialchars($row['username']) ?>
                                    </div>
                                </td>
                                <td class="px-6 py-4 text-sm font-medium text-gray-800"><?= htmlspecialchars($row['nama']) ?></td>
                                <td class="px-6 py-4 text-sm">
                                    <?php
                                    $role_class = '';
                                    $role_icon = '';
                                    $role_text = '';
                                    
                                    switch($row['role']) {
                                        case 'admin':
                                            $role_class = 'bg-red-100 text-red-800';
                                            $role_icon = 'fa-crown';
                                            $role_text = 'Admin';
                                            break;
                                        case 'guru_bk':
                                            $role_class = 'bg-green-100 text-green-800';
                                            $role_icon = 'fa-hand-holding-heart';
                                            $role_text = 'Guru BK';
                                            break;
                                        case 'wali_kelas':
                                            $role_class = 'bg-blue-100 text-blue-800';
                                            $role_icon = 'fa-users';
                                            $role_text = 'Wali Kelas';
                                            break;
                                        case 'kepala_sekolah':
                                            $role_class = 'bg-purple-100 text-purple-800';
                                            $role_icon = 'fa-school';
                                            $role_text = 'Kepala Sekolah';
                                            break;
                                        case 'guru':
                                            $role_class = 'bg-yellow-100 text-yellow-800';
                                            $role_icon = 'fa-chalkboard';
                                            $role_text = 'Guru';
                                            break;
                                        case 'siswa':
                                            $role_class = 'bg-indigo-100 text-indigo-800';
                                            $role_icon = 'fa-user-graduate';
                                            $role_text = 'Siswa';
                                            break;
                                        default:
                                            $role_class = 'bg-gray-100 text-gray-800';
                                            $role_icon = 'fa-user';
                                            $role_text = ucfirst($row['role']);
                                    }
                                    ?>
                                    <span class="<?= $role_class ?> px-3 py-1 rounded-full text-xs font-medium inline-flex items-center">
                                        <i class="fas <?= $role_icon ?> mr-1"></i>
                                        <?= $role_text ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 text-sm">
                                    <?php if ($row['is_active'] == '1'): ?>
                                        <span class="bg-green-100 text-green-800 px-3 py-1 rounded-full text-xs font-medium inline-flex items-center">
                                            <i class="fas fa-check-circle mr-1"></i>Aktif
                                        </span>
                                    <?php else: ?>
                                        <span class="bg-yellow-100 text-yellow-800 px-3 py-1 rounded-full text-xs font-medium inline-flex items-center">
                                            <i class="fas fa-clock mr-1"></i>Nonaktif
                                        </span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4 text-sm text-gray-600">
                                    <i class="fas fa-calendar-alt text-gray-400 mr-1"></i>
                                    <?= date('d M Y', strtotime($row['created_at'])) ?>
                                </td>
                                <td class="px-6 py-4 text-sm text-right">
                                    <a href="edit.php?id=<?= $row['id_user'] ?>" 
                                       class="text-blue-600 hover:text-blue-800 mx-2"
                                       data-bs-toggle="tooltip" 
                                       title="Edit Data">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    
                                    <?php if ($row['id_user'] == $current_user['id_user']): ?>
                                        <span class="text-gray-400 mx-2 cursor-not-allowed" 
                                              data-bs-toggle="tooltip" 
                                              title="Tidak dapat menghapus akun sendiri">
                                            <i class="fas fa-trash"></i>
                                        </span>
                                    <?php else: ?>
                                        <a href="#" 
                                           onclick="confirmDelete(<?= $row['id_user'] ?>, '<?= htmlspecialchars($row['nama']) ?> (<?= htmlspecialchars($row['username']) ?>)')"
                                           class="text-red-600 hover:text-red-800 mx-2"
                                           data-bs-toggle="tooltip" 
                                           title="Hapus Data">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="7" class="px-6 py-12 text-center text-gray-500">
                                <i class="fas fa-users text-5xl mb-3 text-gray-300"></i>
                                <p class="text-lg font-medium">Belum ada data pengguna</p>
                                <p class="text-sm mt-1">Klik tombol "Tambah Pengguna" untuk menambahkan data</p>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

<!-- Modal Konfirmasi Hapus -->
<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content rounded-2xl">
            <div class="modal-header bg-red-500 text-white rounded-t-2xl">
                <h5 class="modal-title">
                    <i class="fas fa-exclamation-triangle mr-2"></i>Konfirmasi Hapus
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-6">
                <p class="text-gray-600 mb-2">Apakah Anda yakin ingin menghapus data pengguna:</p>
                <p class="font-semibold text-gray-800" id="deleteItemInfo"></p>
                <p class="text-sm text-red-600 mt-3">
                    <i class="fas fa-info-circle mr-1"></i>
                    Data yang sudah dihapus tidak dapat dikembalikan!
                </p>
            </div>
            <div class="modal-footer border-t border-gray-100 p-4">
                <button type="button" class="btn-outline-primary text-sm" data-bs-dismiss="modal">
                    <i class="fas fa-times mr-1"></i>Batal
                </button>
                <a href="#" id="confirmDeleteBtn" class="bg-red-500 text-white px-6 py-2 rounded-full hover:bg-red-600 transition text-sm">
                    <i class="fas fa-trash mr-1"></i>Ya, Hapus
                </a>
            </div>
        </div>
    </div>
</div>

<script>
// Auto hide alert after 5 seconds
$(document).ready(function() {
    if ($('#alert-notification').length) {
        setTimeout(function() {
            $('#alert-notification').fadeOut('slow');
        }, 5000);
    }
});

// Fungsi konfirmasi hapus
function confirmDelete(id, info) {
    document.getElementById('deleteItemInfo').textContent = info;
    document.getElementById('confirmDeleteBtn').href = 'hapus.php?id=' + id;
    
    var deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
    deleteModal.show();
}

// Tooltip initialization
$(document).ready(function() {
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function(tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
});
</script>

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