<?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';
require_once $_SERVER['DOCUMENT_ROOT'] . '/yoga/includes/sidebar.php';

// Cek login
cek_login();

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

// Filter
$bulan = isset($_GET['bulan']) ? (int)$_GET['bulan'] : date('m');
$tahun = isset($_GET['tahun']) ? (int)$_GET['tahun'] : date('Y');
$search = isset($_GET['search']) ? sanitize($_GET['search']) : '';
$where = "WHERE p.periode_bulan = $bulan AND p.periode_tahun = $tahun";

if ($_SESSION['role'] == 'karyawan') {
    $user_id = $_SESSION['user_id'];
    $karyawan = get_karyawan_by_user($user_id);
    if ($karyawan) {
        $where .= " AND p.karyawan_id = {$karyawan['id']}";
    } else {
        $where .= " AND p.karyawan_id = 0"; // Prevent showing data if no employee data found
    }
}

if (!empty($search)) {
    $where .= " AND (k.nama LIKE '%$search%' OR k.nik LIKE '%$search%')";
}

$query = "SELECT p.*, k.nik, k.nama, k.jabatan 
          FROM penggajian p 
          JOIN karyawan k ON p.karyawan_id = k.id 
          $where
          ORDER BY k.nama ASC";
$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">Data Penggajian</h2>
            <p class="text-slate-400">Menampilkan data penggajian berdasarkan periode.</p>
        </div>
        <?php if (cek_akses('penggajian', 'add')): ?>
        <a href="<?php echo BASE_URL; ?>/modules/penggajian/proses.php" class="bg-sky-600 hover:bg-sky-700 text-white font-bold py-2.5 px-5 rounded-lg transition-colors flex items-center gap-2">
            <i class="fas fa-cogs"></i> Proses Gaji Bulanan
        </a>
        <?php endif; ?>
    </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 flex-wrap items-end gap-4 mb-6 pb-6 border-b border-slate-700/50">
            <div>
                <label for="bulan" class="block text-slate-400 text-sm font-medium mb-2">Bulan</label>
                <select name="bulan" id="bulan" 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 px-3 py-2.5">
                    <?php for ($i = 1; $i <= 12; $i++): ?><option value="<?php echo $i; ?>" <?php echo ($bulan == $i) ? 'selected' : ''; ?>><?php echo date('F', mktime(0, 0, 0, $i, 1)); ?></option><?php endfor; ?>
                </select>
            </div>
            <div>
                <label for="tahun" class="block text-slate-400 text-sm font-medium mb-2">Tahun</label>
                <select name="tahun" id="tahun" 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 px-3 py-2.5">
                    <?php for ($i = date('Y') - 5; $i <= date('Y'); $i++): ?><option value="<?php echo $i; ?>" <?php echo ($tahun == $i) ? 'selected' : ''; ?>><?php echo $i; ?></option><?php endfor; ?>
                </select>
            </div>
            <?php if ($_SESSION['role'] !== 'karyawan'): ?>
            <div class="flex-grow">
                <label for="search" class="block text-slate-400 text-sm font-medium mb-2">Cari Karyawan</label>
                <input type="text" name="search" id="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 px-3 py-2.5" placeholder="Nama atau NIK...">
            </div>
            <?php endif; ?>
            <button type="submit" class="bg-slate-700 hover:bg-slate-600 text-white font-bold py-2.5 px-6 rounded-lg transition-colors flex items-center gap-2"><i class="fas fa-filter"></i> Terapkan</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-right">Gaji Pokok</th>
                        <th class="px-4 py-3 text-slate-300 font-semibold text-right">Potongan</th>
                        <th class="px-4 py-3 text-slate-300 font-semibold text-right">Total Gaji</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 text-center">Aksi</th>
                    </tr>
                </thead>
                <tbody class="text-slate-400">
                    <?php if (mysqli_num_rows($result) > 0): $no = 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-right"><?php echo format_rupiah($row['gaji_pokok']); ?></td>
                        <td class="px-4 py-3 border-b border-slate-800 text-right text-red-400"><?php echo format_rupiah($row['potongan']); ?></td>
                        <td class="px-4 py-3 border-b border-slate-800 text-right font-bold text-white"><?php echo format_rupiah($row['total_gaji']); ?></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 
                                switch ($row['status']) {
                                    case 'draft': echo 'bg-gray-500/20 text-gray-300'; break;
                                    case 'disetujui': echo 'bg-blue-500/20 text-blue-300'; break;
                                    case 'dibayar': echo 'bg-green-500/20 text-green-300'; break;
                                    default: echo 'bg-gray-500/20 text-gray-300';
                                } ?>"><?php echo ucfirst($row['status']); ?></span>
                        </td>
                        <td class="px-4 py-3 border-b border-slate-800 text-center">
                            <div class="flex items-center justify-center gap-3">
                                <a href="<?php echo BASE_URL; ?>/modules/penggajian/slip.php?id=<?php echo $row['id']; ?>" target="_blank" class="text-sky-400 hover:text-sky-300" title="Cetak Slip"><i class="fas fa-print"></i></a>
                                <?php if (cek_akses('penggajian', 'edit') && $row['status'] != 'dibayar'): ?>
                                <a href="<?php echo BASE_URL; ?>/modules/penggajian/edit.php?id=<?php echo $row['id']; ?>" class="text-yellow-400 hover:text-yellow-300" title="Edit"><i class="fas fa-edit"></i></a>
                                <?php endif; ?>
                                <?php if (cek_akses('penggajian', 'delete') && $row['status'] == 'draft'): ?>
                                <a href="<?php echo BASE_URL; ?>/modules/penggajian/hapus.php?id=<?php echo $row['id']; ?>" class="text-red-500 hover:text-red-400" title="Hapus" onclick="return confirm('Yakin ingin menghapus data gaji ini?')"><i class="fas fa-trash"></i></a>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endwhile; else: ?>
                    <tr><td colspan="7" class="px-4 py-10 text-center text-slate-500">Tidak ada data penggajian untuk periode ini.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <?php if (cek_akses('penggajian', 'report')): ?>
        <div class="p-4 mt-4 flex justify-end">
            <a href="<?php echo BASE_URL; ?>/modules/penggajian/laporan.php?bulan=<?php echo $bulan; ?>&tahun=<?php echo $tahun; ?>" class="bg-teal-600 hover:bg-teal-700 text-white font-bold py-2.5 px-5 rounded-lg transition-colors flex items-center gap-2">
                <i class="fas fa-file-alt"></i> Lihat Laporan
            </a>
        </div>
        <?php endif; ?>
    </div>
</div>

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