<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/yoga/includes/config.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/yoga/includes/functions.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/yoga/includes/header.php';
// sidebar.php sudah di-include di dalam header.php

// Cek login dan akses
cek_login();
if (!cek_akses('karyawan', '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;

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

// Query untuk menghitung total data
$total_query_sql = "SELECT COUNT(*) as total FROM karyawan k " . ($where ? "WHERE k.nama LIKE '%$search%' OR k.nik LIKE '%$search%' OR k.jabatan LIKE '%$search%'" : "");
$total_result = mysqli_query($conn, $total_query_sql);
$total_data = mysqli_fetch_assoc($total_result)['total'];
$total_pages = ceil($total_data / $limit);

// Query untuk mengambil data karyawan
$query_sql = "SELECT k.*, u.username FROM karyawan k LEFT JOIN users u ON k.user_id = u.id " . ($where ? "WHERE k.nama LIKE '%$search%' OR k.nik LIKE '%$search%' OR k.jabatan LIKE '%$search%'" : "") . " ORDER BY k.nama ASC LIMIT $start, $limit";
$result = mysqli_query($conn, $query_sql);

// Pesan notifikasi
$success = isset($_GET['success']) ? urldecode($_GET['success']) : '';
$error = isset($_GET['error']) ? urldecode($_GET['error']) : '';
?>

<!-- Konten dimulai setelah <main> di header.php -->
<div class="flex justify-between items-center mb-6">
    <!-- Judul halaman ini sudah diatur oleh JavaScript di footer.php -->
</div>

<?php if (!empty($success)): ?>
<div class="bg-emerald-500/20 border border-emerald-500/30 text-emerald-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 rounded-xl shadow-lg">
    <!-- Header Tabel: Search dan Tombol Tambah -->
    <div class="p-5 border-b border-slate-700/50 flex flex-col sm:flex-row justify-between items-center gap-4">
        <form action="" method="GET" class="w-full sm:max-w-xs">
            <div class="relative">
                <span class="absolute inset-y-0 left-0 flex items-center pl-3"><i class="fas fa-search text-slate-500"></i></span>
                <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>" class="pl-10 pr-3 py-2.5 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" placeholder="Cari NIK, nama, jabatan...">
            </div>
        </form>
        <?php if (cek_akses('karyawan', 'add')): ?>
        <a href="<?php echo BASE_URL; ?>/modules/karyawan/tambah.php" class="w-full sm:w-auto bg-sky-600 hover:bg-sky-700 text-white font-bold py-2.5 px-4 rounded-lg transition-colors duration-200 flex items-center justify-center gap-2">
            <i class="fas fa-plus"></i>
            <span>Tambah Karyawan</span>
        </a>
        <?php endif; ?>
    </div>

    <!-- Tabel Data -->
    <div class="overflow-x-auto">
        <table class="w-full text-sm text-left">
            <thead class="text-xs text-slate-400 uppercase bg-slate-700/20">
                <tr>
                    <th class="py-3 px-6">No</th>
                    <th class="py-3 px-6">Karyawan</th>
                    <th class="py-3 px-6">Jabatan</th>
                    <th class="py-3 px-6">Gaji Pokok</th>
                    <th class="py-3 px-6">Status</th>
                    <th class="py-3 px-6 text-center">Aksi</th>
                </tr>
            </thead>
            <tbody class="text-slate-300">
                <?php if (mysqli_num_rows($result) > 0): ?>
                    <?php $no = $start + 1; ?>
                    <?php while ($row = mysqli_fetch_assoc($result)): ?>
                    <tr class="border-b border-slate-700/50 hover:bg-slate-700/20">
                        <td class="py-4 px-6"><?php echo $no++; ?></td>
                        <td class="py-4 px-6">
                            <div class="flex items-center gap-3">
                                <div class="w-10 h-10 rounded-full bg-slate-700 flex-shrink-0">
                                    <?php if (!empty($row['foto']) && file_exists(FOTO_DIR . $row['foto'])): ?>
                                    <img src="<?php echo BASE_URL . '/uploads/foto/' . htmlspecialchars($row['foto']); ?>" alt="Foto" class="w-full h-full object-cover rounded-full">
                                    <?php else: ?>
                                    <div class="w-full h-full flex items-center justify-center text-sky-400 font-bold text-lg">
                                        <?php echo strtoupper(substr($row['nama'], 0, 1)); ?>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                <div>
                                    <div class="font-medium text-white"><?php echo htmlspecialchars($row['nama']); ?></div>
                                    <div class="text-slate-400 text-xs">NIK: <?php echo htmlspecialchars($row['nik']); ?></div>
                                </div>
                            </div>
                        </td>
                        <td class="py-4 px-6"><?php echo htmlspecialchars($row['jabatan']); ?></td>
                        <td class="py-4 px-6"><?php echo format_rupiah($row['gaji_pokok']); ?></td>
                        <td class="py-4 px-6">
                            <span class="px-2.5 py-1 inline-flex text-xs leading-5 font-semibold rounded-full <?php echo ($row['status'] == 'aktif') ? 'bg-emerald-500/20 text-emerald-300' : 'bg-red-500/20 text-red-300'; ?>">
                                <?php echo ucfirst($row['status']); ?>
                            </span>
                        </td>
                        <td class="py-4 px-6 text-center">
                            <div class="flex items-center justify-center gap-3">
                                <a href="<?php echo BASE_URL; ?>/modules/karyawan/detail.php?id=<?php echo $row['id']; ?>" class="text-slate-400 hover:text-sky-400" title="Detail"><i class="fas fa-eye"></i></a>
                                <?php if (cek_akses('karyawan', 'edit')): ?>
                                <a href="<?php echo BASE_URL; ?>/modules/karyawan/edit.php?id=<?php echo $row['id']; ?>" class="text-slate-400 hover:text-amber-400" title="Edit"><i class="fas fa-edit"></i></a>
                                <?php endif; ?>
                                <?php if (cek_akses('karyawan', 'delete')): ?>
                                <a href="<?php echo BASE_URL; ?>/modules/karyawan/hapus.php?id=<?php echo $row['id']; ?>" class="text-slate-400 hover:text-red-400" title="Hapus" onclick="return confirm('Apakah Anda yakin ingin menghapus karyawan ini?')"><i class="fas fa-trash"></i></a>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="6" class="text-center py-8 text-slate-400">
                            <i class="fas fa-folder-open fa-2x mb-2"></i>
                            <p>Data karyawan tidak ditemukan.</p>
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Footer Tabel: Info dan Paginasi -->
    <?php if ($total_pages > 1): ?>
    <div class="p-5 border-t border-slate-700/50 flex flex-col sm:flex-row justify-between items-center gap-4">
        <p class="text-sm text-slate-400">
            Menampilkan <span class="font-medium text-white"><?php echo $start + 1; ?></span> - <span class="font-medium text-white"><?php echo min($start + $limit, $total_data); ?></span> dari <span class="font-medium text-white"><?php echo $total_data; ?></span> data
        </p>
        <div class="flex">
            <a href="?page=<?php echo max(1, $page - 1); ?>&search=<?php echo urlencode($search); ?>" class="px-3 py-2 bg-slate-700 text-slate-300 rounded-l-lg hover:bg-slate-600 transition-colors <?php echo ($page <= 1) ? 'opacity-50 cursor-not-allowed' : ''; ?>">
                <i class="fas fa-chevron-left"></i>
            </a>
            <a href="?page=<?php echo min($total_pages, $page + 1); ?>&search=<?php echo urlencode($search); ?>" class="px-3 py-2 bg-slate-700 text-slate-300 rounded-r-lg hover:bg-slate-600 transition-colors <?php echo ($page >= $total_pages) ? 'opacity-50 cursor-not-allowed' : ''; ?>">
                <i class="fas fa-chevron-right"></i>
            </a>
        </div>
    </div>
    <?php endif; ?>
</div>

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