<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/nabila/includes/config.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/nabila/includes/functions.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/nabila/includes/header.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/nabila/includes/sidebar.php';

// Cek login
cek_login();

// Cek akses, jika role karyawan, redirect ke halaman generate_self
if ($_SESSION['role'] === 'karyawan') {
    header("Location: " . BASE_URL . "/modules/qrcode/generate_self.php");
    exit();
}

if (!cek_akses('qrcode', 'view')) {
    header("Location: " . BASE_URL . "/index.php?access=denied");
    exit();
}

// Pagination
$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$start = ($page > 1) ? ($page * $limit) - $limit : 0;

// Filter
$search = isset($_GET['search']) ? sanitize($_GET['search']) : '';
$where = "WHERE 1=1";
if (!empty($search)) {
    $where .= " AND (k.nama LIKE '%$search%' OR k.nik LIKE '%$search%')";
}

// Query total
$total_query = "SELECT COUNT(*) as total FROM karyawan k $where";
$total_result = mysqli_query($conn, $total_query);
$total_data = mysqli_fetch_assoc($total_result)['total'];
$total_pages = ceil($total_data / $limit);

// Query data
$query = "SELECT k.id, k.nik, k.nama, k.status, k.qrcode FROM karyawan k 
          $where 
          ORDER BY k.nama ASC 
          LIMIT $start, $limit";
$result = mysqli_query($conn, $query);

$success = isset($_GET['success']) ? $_GET['success'] : '';
$error = isset($_GET['error']) ? $_GET['error'] : '';
?>

<!-- Main Content -->
<div class="main-content flex-1 p-8">
    <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6 gap-4">
        <div>
            <h2 class="text-3xl font-bold text-white">Manajemen QR Code</h2>
            <p class="text-slate-400">Generate dan kelola QR code absensi untuk semua karyawan.</p>
        </div>
    </div>
    
    <?php if (!empty($success)): ?>
    <div class="bg-green-500/20 border border-green-500/30 text-green-300 px-4 py-3 rounded-lg relative mb-6 text-sm flex items-center gap-3" role="alert">
        <i class="fas fa-check-circle"></i><span><?php echo htmlspecialchars($success); ?></span>
    </div>
    <?php endif; ?>
    
    <?php if (!empty($error)): ?>
    <div class="bg-red-500/20 border border-red-500/30 text-red-300 px-4 py-3 rounded-lg relative mb-6 text-sm flex items-center gap-3" role="alert">
        <i class="fas fa-exclamation-circle"></i><span><?php echo htmlspecialchars($error); ?></span>
    </div>
    <?php endif; ?>
    
    <div class="glass-effect p-6 rounded-xl shadow-lg">
        <form action="" method="GET" class="flex items-center mb-6 pb-6 border-b border-slate-700/50">
            <div class="relative flex-grow">
                 <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>" class="w-full border border-slate-600 bg-slate-700/50 text-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 pl-10 pr-4 py-2.5" placeholder="Cari berdasarkan nama atau NIK...">
                 <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"></i>
            </div>
            <button type="submit" class="bg-slate-700 hover:bg-slate-600 text-white font-bold py-2.5 px-6 rounded-lg transition-colors ml-4">
                Cari
            </button>
        </form>

        <div class="overflow-x-auto">
            <table class="w-full text-left table-auto">
                <thead>
                    <tr class="border-b border-slate-700">
                        <th class="px-4 py-3 text-slate-300 font-semibold">No</th>
                        <th class="px-4 py-3 text-slate-300 font-semibold">Nama Karyawan</th>
                        <th class="px-4 py-3 text-slate-300 font-semibold text-center">Status</th>
                        <th class="px-4 py-3 text-slate-300 font-semibold">QR Code</th>
                        <th class="px-4 py-3 text-slate-300 font-semibold text-center">Aksi</th>
                    </tr>
                </thead>
                <tbody class="text-slate-400">
                    <?php if (mysqli_num_rows($result) > 0): $no = $start + 1; while ($row = mysqli_fetch_assoc($result)): ?>
                    <tr class="hover:bg-slate-800/50">
                        <td class="px-4 py-3 border-b border-slate-800"><?php echo $no++; ?></td>
                        <td class="px-4 py-3 border-b border-slate-800">
                            <p class="font-medium text-slate-200"><?php echo htmlspecialchars($row['nama']); ?></p>
                            <p class="text-xs"><?php echo htmlspecialchars($row['nik']); ?></p>
                        </td>
                        <td class="px-4 py-3 border-b border-slate-800 text-center">
                            <span class="px-3 py-1 text-xs font-semibold rounded-full <?php echo ($row['status'] == 'aktif') ? 'bg-green-500/20 text-green-300' : 'bg-red-500/20 text-red-300'; ?>">
                                <?php echo ucfirst($row['status']); ?>
                            </span>
                        </td>
                        <td class="px-4 py-3 border-b border-slate-800">
                            <?php if (!empty($row['qrcode']) && file_exists(QR_DIR . $row['qrcode'])): ?>
                            <img src="<?php echo BASE_URL; ?>/uploads/qrcode/<?php echo htmlspecialchars($row['qrcode']); ?>" alt="QR Code" class="w-16 h-16 rounded-md bg-white p-1">
                            <?php else: ?>
                            <span class="text-slate-500 text-sm">Belum ada</span>
                            <?php endif; ?>
                        </td>
                        <td class="px-4 py-3 border-b border-slate-800 text-center">
                            <div class="flex items-center justify-center gap-2">
                                <?php if (cek_akses('qrcode', 'generate')): ?>
                                <a href="<?php echo BASE_URL; ?>/modules/qrcode/generate.php?id=<?php echo $row['id']; ?>" class="bg-sky-600 hover:bg-sky-700 text-white text-sm py-1 px-3 rounded-md transition-colors">
                                    Generate
                                </a>
                                <?php endif; ?>
                                
                                <?php if (!empty($row['qrcode']) && file_exists(QR_DIR . $row['qrcode'])): ?>
                                <a href="<?php echo BASE_URL; ?>/modules/qrcode/cetak.php?id=<?php echo $row['id']; ?>" target="_blank" class="bg-teal-600 hover:bg-teal-700 text-white text-sm py-1 px-3 rounded-md transition-colors">
                                    Cetak
                                </a>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endwhile; else: ?>
                    <tr><td colspan="5" class="px-4 py-10 text-center text-slate-500">Tidak ada data karyawan yang cocok.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <?php if ($total_pages > 1): ?>
        <div class="p-4 mt-6 flex flex-col md:flex-row justify-between items-center gap-4 text-sm">
            <p class="text-slate-400">Menampilkan <?php echo $start + 1; ?>-<?php echo min($start + $limit, $total_data); ?> dari <?php echo $total_data; ?> data</p>
            <div class="flex items-center">
                <?php if ($page > 1): ?>
                <a href="?page=<?php echo $page - 1; ?>&search=<?php echo $search; ?>" class="px-3 py-1 bg-slate-700 text-slate-300 rounded-l-md hover:bg-slate-600 transition-colors">&laquo;</a>
                <?php endif; ?>
                
                <?php for ($i = max(1, $page - 2); $i <= min($page + 2, $total_pages); $i++): ?>
                <a href="?page=<?php echo $i; ?>&search=<?php echo $search; ?>" class="px-3 py-1 <?php echo ($i == $page) ? 'bg-sky-600 text-white' : 'bg-slate-700 text-slate-300 hover:bg-slate-600'; ?> transition-colors">
                    <?php echo $i; ?>
                </a>
                <?php endfor; ?>
                
                <?php if ($page < $total_pages): ?>
                <a href="?page=<?php echo $page + 1; ?>&search=<?php echo $search; ?>" class="px-3 py-1 bg-slate-700 text-slate-300 rounded-r-md hover:bg-slate-600 transition-colors">&raquo;</a>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/nabila/includes/footer.php';
?>