<?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
if (!cek_akses('karyawan', 'view')) {
    header("Location: " . BASE_URL . "/index.php?access=denied");
    exit();
}

// Cek ID
if (!isset($_GET['id']) || empty($_GET['id'])) {
    header("Location: " . BASE_URL . "/modules/karyawan/index.php?error=" . urlencode("ID karyawan tidak valid!"));
    exit();
}

$id = (int)$_GET['id'];

// Ambil data karyawan
$query = "SELECT k.*, u.username, u.role FROM karyawan k 
          LEFT JOIN users u ON k.user_id = u.id 
          WHERE k.id = $id";
$result = mysqli_query($conn, $query);

if (mysqli_num_rows($result) == 0) {
    header("Location: " . BASE_URL . "/modules/karyawan/index.php?error=" . urlencode("Data karyawan tidak ditemukan!"));
    exit();
}

$karyawan = mysqli_fetch_assoc($result);

// Ambil data jumlah absensi bulan ini
$bulan = date('m');
$tahun = date('Y');

$query_hadir = "SELECT COUNT(*) as total FROM absensi WHERE karyawan_id = $id AND status = 'hadir' AND MONTH(tanggal) = $bulan AND YEAR(tanggal) = $tahun";
$result_hadir = mysqli_query($conn, $query_hadir);
$jumlah_hadir = mysqli_fetch_assoc($result_hadir)['total'];

$query_izin = "SELECT COUNT(*) as total FROM absensi WHERE karyawan_id = $id AND status IN ('izin', 'sakit', 'cuti') AND MONTH(tanggal) = $bulan AND YEAR(tanggal) = $tahun";
$result_izin = mysqli_query($conn, $query_izin);
$jumlah_izin = mysqli_fetch_assoc($result_izin)['total'];

$query_alpha = "SELECT COUNT(*) as total FROM absensi WHERE karyawan_id = $id AND status = 'alpha' AND MONTH(tanggal) = $bulan AND YEAR(tanggal) = $tahun";
$result_alpha = mysqli_query($conn, $query_alpha);
$jumlah_alpha = mysqli_fetch_assoc($result_alpha)['total'];

// Ambil data gaji bulan ini
$query_gaji = "SELECT * FROM penggajian WHERE karyawan_id = $id AND periode_bulan = $bulan AND periode_tahun = $tahun";
$result_gaji = mysqli_query($conn, $query_gaji);
$gaji_bulan_ini = mysqli_fetch_assoc($result_gaji);

function display_info($label, $value, $icon_class, $is_rupiah = false) {
    $formatted_value = $is_rupiah ? format_rupiah($value) : htmlspecialchars($value);
    echo '
        <div class="flex items-start gap-4">
            <div class="glass-effect-light w-10 h-10 rounded-lg flex items-center justify-center text-sky-300">
                <i class="fas ' . $icon_class . '"></i>
            </div>
            <div>
                <p class="text-slate-400 text-sm">' . $label . '</p>
                <p class="font-semibold text-white">' . ($formatted_value ?: '-') . '</p>
            </div>
        </div>
    ';
}
?>

<!-- Main Content -->
<div class="main-content flex-1 p-8">
    <div class="flex justify-between items-center mb-6">
        <div>
             <h2 class="text-3xl font-bold text-white">Detail Karyawan</h2>
             <p class="text-slate-400">Informasi lengkap mengenai karyawan.</p>
        </div>
        <div class="flex space-x-3">
            <?php if (cek_akses('karyawan', 'edit')): ?>
            <a href="<?php echo BASE_URL; ?>/modules/karyawan/edit.php?id=<?php echo $karyawan['id']; ?>" class="bg-yellow-500/80 hover:bg-yellow-500 text-white font-bold py-2.5 px-5 rounded-lg transition-colors flex items-center gap-2">
                <i class="fas fa-edit"></i> Edit
            </a>
            <?php endif; ?>
            
            <a href="<?php echo BASE_URL; ?>/modules/karyawan/index.php" class="bg-slate-700 hover:bg-slate-600 text-white font-bold py-2.5 px-5 rounded-lg transition-colors">
                Kembali
            </a>
        </div>
    </div>
    
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- Kolom Kiri: Profil Karyawan -->
        <div class="lg:col-span-1 space-y-6">
            <div class="glass-effect p-6 rounded-xl shadow-lg text-center">
                <div class="mb-4">
                    <?php if (!empty($karyawan['foto']) && $karyawan['foto'] != 'default.jpg' && file_exists(FOTO_DIR . $karyawan['foto'])): ?>
                    <img src="<?php echo BASE_URL; ?>/uploads/foto/<?php echo htmlspecialchars($karyawan['foto']); ?>" alt="Foto <?php echo htmlspecialchars($karyawan['nama']); ?>" class="w-32 h-32 object-cover rounded-full mx-auto border-4 border-slate-600/50">
                    <?php else: ?>
                    <div class="w-32 h-32 rounded-full mx-auto bg-slate-700/50 flex items-center justify-center border-4 border-slate-600/50">
                        <i class="fas fa-user text-slate-400 text-5xl"></i>
                    </div>
                    <?php endif; ?>
                </div>
                
                <h3 class="text-2xl font-bold text-white"><?php echo htmlspecialchars($karyawan['nama']); ?></h3>
                <p class="text-sky-300 font-medium"><?php echo htmlspecialchars($karyawan['jabatan']); ?></p>
                
                <div class="mt-4 pt-4 border-t border-slate-700/50">
                    <span class="inline-block px-3 py-1 text-sm rounded-full <?php echo ($karyawan['status'] == 'aktif') ? 'bg-green-500/20 text-green-300' : 'bg-red-500/20 text-red-300'; ?>">
                        Status: <?php echo ucfirst($karyawan['status']); ?>
                    </span>
                </div>

                 <?php if (!empty($karyawan['username'])): ?>
                <div class="bg-slate-700/50 p-3 rounded-lg border border-slate-600/80 mt-4 text-left">
                    <h4 class="font-semibold text-sky-400 text-sm mb-2 flex items-center gap-2"><i class="fas fa-user-shield"></i>Informasi Akun</h4>
                    <p class="text-xs text-slate-300">Username: <span class="font-medium text-white"><?php echo htmlspecialchars($karyawan['username']); ?></span></p>
                    <p class="text-xs text-slate-300">Role: <span class="font-medium text-white"><?php echo ucfirst(htmlspecialchars($karyawan['role'])); ?></span></p>
                </div>
                <?php endif; ?>
            </div>

            <?php if (!empty($karyawan['qrcode']) && file_exists(QR_DIR . $karyawan['qrcode'])): ?>
            <div class="glass-effect p-6 rounded-xl shadow-lg text-center">
                <h4 class="font-bold text-white mb-3">QR Code Absensi</h4>
                <img src="<?php echo BASE_URL; ?>/uploads/qrcode/<?php echo htmlspecialchars($karyawan['qrcode']); ?>" alt="QR Code" class="w-32 h-32 mx-auto rounded-lg border-2 border-slate-600/50">
                <div class="mt-4">
                    <a href="<?php echo BASE_URL; ?>/modules/qrcode/cetak.php?id=<?php echo $karyawan['id']; ?>" class="text-sky-400 hover:text-sky-300 text-sm transition-colors" target="_blank">
                        <i class="fas fa-print mr-1"></i> Cetak QR Code
                    </a>
                </div>
            </div>
            <?php endif; ?>
        </div>
        
        <!-- Kolom Kanan: Detail Data dengan Tabs -->
        <div class="lg:col-span-2">
            <div class="glass-effect p-6 rounded-xl shadow-lg">
                <div class="mb-6">
                    <div class="border-b border-slate-700/50">
                         <nav class="-mb-px flex space-x-6" aria-label="Tabs">
                             <button onclick="changeTab(this, 'detail')" class="tab-button active">Data Rinci</button>
                             <button onclick="changeTab(this, 'absensi')" class="tab-button">Absensi</button>
                             <button onclick="changeTab(this, 'gaji')" class="tab-button">Penggajian</button>
                         </nav>
                    </div>
                </div>

                <!-- Konten Tab: Data Rinci -->
                <div id="detail" class="tab-content">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-6">
                        <?php display_info('Nomor Induk Karyawan', $karyawan['nik'], 'fa-id-card'); ?>
                        <?php display_info('Jenis Kelamin', ($karyawan['jenis_kelamin'] == 'L' ? 'Laki-laki' : 'Perempuan'), 'fa-venus-mars'); ?>
                        <?php display_info('Email', $karyawan['email'], 'fa-envelope'); ?>
                        <?php display_info('No. Telepon', $karyawan['telepon'], 'fa-phone'); ?>
                        <?php display_info('Alamat', $karyawan['alamat'], 'fa-map-marker-alt'); ?>
                        <?php display_info('Departemen', $karyawan['departemen'], 'fa-building'); ?>
                        <?php display_info('Tanggal Masuk', tanggal_indo($karyawan['tanggal_masuk']), 'fa-calendar-alt'); ?>
                        <?php
                            $tanggal_masuk = new DateTime($karyawan['tanggal_masuk']);
                            $today = new DateTime();
                            $interval = $tanggal_masuk->diff($today);
                            $masa_kerja = $interval->y . ' Tahun, ' . $interval->m . ' Bulan';
                            display_info('Masa Kerja', $masa_kerja, 'fa-business-time');
                        ?>
                    </div>
                </div>

                <!-- Konten Tab: Absensi -->
                <div id="absensi" class="tab-content hidden">
                    <h4 class="text-lg font-semibold text-white mb-4">Rekap Absensi Bulan Ini (<?php echo date('F Y'); ?>)</h4>
                    <div class="grid grid-cols-1 sm:grid-cols-3 gap-4 text-center">
                        <div class="glass-effect-light p-4 rounded-lg">
                            <div class="text-4xl font-bold text-green-400"><?php echo $jumlah_hadir; ?></div>
                            <div class="text-sm text-slate-300 mt-1">Hadir</div>
                        </div>
                        <div class="glass-effect-light p-4 rounded-lg">
                            <div class="text-4xl font-bold text-yellow-400"><?php echo $jumlah_izin; ?></div>
                            <div class="text-sm text-slate-300 mt-1">Izin/Sakit/Cuti</div>
                        </div>
                        <div class="glass-effect-light p-4 rounded-lg">
                            <div class="text-4xl font-bold text-red-400"><?php echo $jumlah_alpha; ?></div>
                            <div class="text-sm text-slate-300 mt-1">Alpha</div>
                        </div>
                    </div>
                     <div class="mt-6 text-center">
                        <a href="<?php echo BASE_URL; ?>/modules/absensi/riwayat.php?karyawan_id=<?php echo $karyawan['id']; ?>" class="text-sky-400 hover:text-sky-300 transition-colors">
                            <i class="fas fa-history mr-1"></i> Lihat Riwayat Absensi Lengkap
                        </a>
                    </div>
                </div>

                <!-- Konten Tab: Gaji -->
                <div id="gaji" class="tab-content hidden">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-6">
                        <?php display_info('Gaji Pokok', $karyawan['gaji_pokok'], 'fa-money-bill-wave', true); ?>
                        <?php display_info('Tunjangan', $karyawan['tunjangan'], 'fa-plus-circle', true); ?>
                        <div class="md:col-span-2">
                             <?php display_info('Total Gaji Dasar', ($karyawan['gaji_pokok'] + $karyawan['tunjangan']), 'fa-wallet', true); ?>
                        </div>
                    </div>

                    <div class="border-t border-slate-700/50 mt-6 pt-6">
                         <h4 class="text-lg font-semibold text-white mb-4">Gaji Bulan Ini (<?php echo date('F Y'); ?>)</h4>
                         <?php if ($gaji_bulan_ini): ?>
                            <div class="space-y-4">
                                <?php display_info('Periode Gaji', date('F Y', mktime(0, 0, 0, $gaji_bulan_ini['periode_bulan'], 1, $gaji_bulan_ini['periode_tahun'])), 'fa-calendar-check'); ?>
                                <?php display_info('Total Diterima', $gaji_bulan_ini['total_gaji'], 'fa-check-double', true); ?>
                                <div>
                                    <p class="text-slate-400 text-sm">Status:</p>
                                     <p class="font-medium">
                                        <span class="px-3 py-1 text-xs rounded-full font-semibold <?php 
                                            switch ($gaji_bulan_ini['status']) {
                                                case 'draft': echo 'bg-gray-500/30 text-gray-300'; break;
                                                case 'disetujui': echo 'bg-blue-500/30 text-blue-300'; break;
                                                case 'dibayar': echo 'bg-green-500/30 text-green-300'; break;
                                                default: echo 'bg-gray-500/30 text-gray-300';
                                            }
                                        ?>">
                                            <?php echo ucfirst($gaji_bulan_ini['status']); ?>
                                        </span>
                                    </p>
                                </div>
                                <div class="pt-2">
                                    <a href="<?php echo BASE_URL; ?>/modules/penggajian/slip.php?id=<?php echo $gaji_bulan_ini['id']; ?>" class="text-sky-400 hover:text-sky-300 transition-colors">
                                        <i class="fas fa-print mr-1"></i> Cetak Slip Gaji
                                    </a>
                                </div>
                            </div>
                         <?php else: ?>
                            <div class="glass-effect-light p-4 rounded-lg text-center">
                                <p class="text-yellow-300">Data penggajian untuk bulan ini belum tersedia.</p>
                            </div>
                         <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    .tab-button {
        @apply border-transparent text-slate-400 hover:text-white hover:border-slate-400 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm transition-all;
    }
    .tab-button.active {
        @apply border-sky-500 text-sky-400;
    }
    .glass-effect-light {
        background: rgba(45, 55, 72, 0.5); /* slate-800 with opacity */
        -webkit-backdrop-filter: blur(4px);
        backdrop-filter: blur(4px);
        border: 1px solid rgba(255, 255, 255, 0.1);
    }
</style>

<script>
    function changeTab(button, tabId) {
        // Hide all tab contents
        document.querySelectorAll('.tab-content').forEach(function(tab) {
            tab.classList.add('hidden');
        });

        // Deactivate all tab buttons
        document.querySelectorAll('.tab-button').forEach(function(btn) {
            btn.classList.remove('active');
        });

        // Show the selected tab content
        document.getElementById(tabId).classList.remove('hidden');

        // Activate the clicked button
        button.classList.add('active');
    }
</script>

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