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

$bulan = isset($_POST['bulan']) ? (int)$_POST['bulan'] : date('m');
$tahun = isset($_POST['tahun']) ? (int)$_POST['tahun'] : date('Y');
$success = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['proses'])) {
    $bulan = (int)$_POST['bulan'];
    $tahun = (int)$_POST['tahun'];
    
    $check_query = "SELECT COUNT(*) as total FROM penggajian WHERE periode_bulan = $bulan AND periode_tahun = $tahun";
    $check_result = mysqli_query($conn, $check_query);
    $check_data = mysqli_fetch_assoc($check_result);
    
    if ($check_data['total'] > 0) {
        $error = "Penggajian untuk periode " . date('F Y', mktime(0, 0, 0, $bulan, 1, $tahun)) . " sudah pernah diproses!";
    } else {
        $karyawan_query = "SELECT * FROM karyawan WHERE status = 'aktif'";
        $karyawan_result = mysqli_query($conn, $karyawan_query);
        
        mysqli_begin_transaction($conn);
        try {
            $success_count = 0;
            $error_count = 0;
            $pengaturan = get_pengaturan();
            
            while ($karyawan = mysqli_fetch_assoc($karyawan_result)) {
                $karyawan_id = $karyawan['id'];
                $gaji_pokok = $karyawan['gaji_pokok'];
                $tunjangan = $karyawan['tunjangan'];
                $potongan = hitung_potongan_absensi($karyawan_id, $bulan, $tahun);
                $bonus = 0;
                $total_gaji = hitung_gaji_total($gaji_pokok, $tunjangan, $bonus, $potongan);
                
                $insert_query = "INSERT INTO penggajian (karyawan_id, periode_bulan, periode_tahun, gaji_pokok, tunjangan, bonus, potongan, total_gaji, status, created_at) VALUES ($karyawan_id, $bulan, $tahun, $gaji_pokok, $tunjangan, $bonus, $potongan, $total_gaji, 'draft', NOW())";
                
                if (mysqli_query($conn, $insert_query)) {
                    $penggajian_id = mysqli_insert_id($conn);
                    
                    // Detail potongan alpha
                    $jumlah_alpha = hitung_absensi($karyawan_id, $bulan, $tahun, 'alpha');
                    if ($jumlah_alpha > 0) {
                        $potongan_alpha = $jumlah_alpha * $pengaturan['potongan_alpha'];
                        if ($potongan_alpha > 0) {
                            $detail_query = "INSERT INTO detail_potongan (penggajian_id, jenis_potongan, nominal, keterangan) VALUES ($penggajian_id, 'alpha', $potongan_alpha, 'Tidak hadir (alpha) $jumlah_alpha hari')";
                            mysqli_query($conn, $detail_query);
                        }
                    }
                    
                    // Detail potongan keterlambatan
                    $total_keterlambatan = hitung_total_keterlambatan_menit($karyawan_id, $bulan, $tahun);
                    if ($total_keterlambatan > $pengaturan['toleransi_keterlambatan']) {
                         $menit_kena_potongan = $total_keterlambatan - $pengaturan['toleransi_keterlambatan'];
                         $potongan_terlambat = floor($menit_kena_potongan / 60) * $pengaturan['potongan_keterlambatan'];
                         if($potongan_terlambat > 0) {
                              $detail_query = "INSERT INTO detail_potongan (penggajian_id, jenis_potongan, nominal, keterangan) VALUES ($penggajian_id, 'terlambat', $potongan_terlambat, 'Terlambat total $total_keterlambatan menit')";
                              mysqli_query($conn, $detail_query);
                         }
                    }
                    
                    $success_count++;
                } else {
                    $error_count++;
                }
            }
            
            mysqli_commit($conn);
            $success = "Berhasil memproses gaji untuk $success_count karyawan. Gagal: $error_count karyawan.";
            
        } catch (Exception $e) {
            mysqli_rollback($conn);
            $error = "Gagal memproses penggajian: " . $e->getMessage();
        }
    }
}
?>

<!-- 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">Proses Penggajian Bulanan</h2>
            <p class="text-slate-400">Generate data gaji untuk semua karyawan aktif dalam satu periode.</p>
        </div>
        <a href="<?php echo BASE_URL; ?>/modules/penggajian/index.php" class="bg-slate-700 hover:bg-slate-600 text-white font-bold py-2.5 px-6 rounded-lg transition-colors">
            Kembali
        </a>
    </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 method="POST" action="">
            <div class="border-b border-slate-700/50 pb-6 mb-6">
                <h3 class="text-xl font-semibold text-white mb-4">Pilih Periode Penggajian</h3>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                    <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" required>
                            <?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" required>
                            <?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>
                    <div class="flex items-end">
                         <button type="submit" name="proses" class="w-full bg-sky-600 hover:bg-sky-700 text-white font-bold py-2.5 px-6 rounded-lg transition-colors flex items-center justify-center gap-2">
                            <i class="fas fa-cogs"></i> Proses Gaji
                        </button>
                    </div>
                </div>
            </div>
            
            <div class="space-y-4">
                 <h3 class="text-xl font-semibold text-white">Informasi</h3>
                <div class="bg-slate-700/50 p-4 rounded-lg border border-slate-600/80">
                    <h4 class="font-bold text-sky-400 mb-2 flex items-center gap-2"><i class="fas fa-info-circle"></i>Alur Proses</h4>
                    <ul class="list-decimal list-inside space-y-1 text-sm text-slate-300">
                        <li>Sistem akan menghitung gaji berdasarkan data absensi (hadir, alpha, terlambat).</li>
                        <li>Data gaji yang dihasilkan akan berstatus "Draft".</li>
                        <li>Anda dapat mengubah (menambah bonus/potongan) pada data gaji yang berstatus "Draft".</li>
                         <li>Setelah disetujui, Anda dapat mencetak slip gaji.</li>
                    </ul>
                </div>
                 <div class="bg-yellow-800/20 p-4 rounded-lg border border-yellow-600/50">
                    <h4 class="font-bold text-yellow-400 mb-2 flex items-center gap-2"><i class="fas fa-exclamation-triangle"></i>Perhatian</h4>
                     <p class="text-sm text-yellow-300">
                        Pastikan semua data absensi pada periode yang dipilih sudah lengkap dan benar sebelum menjalankan proses ini.
                    </p>
                 </div>
            </div>
        </form>
    </div>
</div>

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