<?php
require 'vendor/autoload.php';
require 'koneksi.php';
use Dompdf\Dompdf;
use Dompdf\Options;

// Pastikan data bulan dan tahun diterima
$bulan = isset($_GET['bulan']) ? (int)$_GET['bulan'] : date('n');
$tahun = isset($_GET['tahun']) ? (int)$_GET['tahun'] : date('Y');

// Hitung jumlah hari dalam bulan
$jumlah_hari = cal_days_in_month(CAL_GREGORIAN, $bulan, $tahun);
$tgl_awal = "$tahun-" . str_pad($bulan, 2, '0', STR_PAD_LEFT) . "-01";
$tgl_akhir = "$tahun-" . str_pad($bulan, 2, '0', STR_PAD_LEFT) . "-$jumlah_hari";

// Query data absensi
$query = "
    SELECT k.nama, a.tanggal, a.jam_masuk, a.jam_pulang
    FROM absensi a
    JOIN karyawan k ON a.rfid = k.rfid
    WHERE a.tanggal BETWEEN '$tgl_awal' AND '$tgl_akhir'
    ORDER BY k.nama, a.tanggal
";
$result = mysqli_query($conn, $query);

$absensi = [];
while ($row = mysqli_fetch_assoc($result)) {
    $absensi[$row['nama']][$row['tanggal']] = ['masuk' => $row['jam_masuk'], 'pulang' => $row['jam_pulang']];
}

// Hitung gaji berdasarkan kehadiran
$gaji_per_hari = 150000; // Gaji per hari
$html = '<h2 style="text-align:center;">PROSES PENGGAJIAN</h2>';
$html .= '<h4 style="text-align:center;">BULAN ' . strtoupper(date('F', mktime(0, 0, 0, $bulan, 1))) . ' ' . $tahun . '</h4>';
$html .= '<table border="1" cellpadding="5" cellspacing="0" style="width:100%; font-size:12px; border-collapse:collapse;">';
$html .= '<tr><th>Nama</th><th>Jumlah Hadir (Hari)</th><th>Total Gaji</th></tr>';

foreach ($absensi as $nama => $data) {
    $hadir = 0;
    foreach ($data as $tanggal => $absen) {
        if ($absen['masuk'] && $absen['pulang']) {  // Hanya hitung jika masuk dan pulang ada
            $hadir++;
        }
    }
    $gaji = $hadir * $gaji_per_hari;
    $html .= "<tr><td>$nama</td><td>$hadir</td><td>Rp " . number_format($gaji, 0, ',', '.') . "</td></tr>";
}

$html .= '</table>';
$html .= '<br><div style="text-align:right; font-size:12px;">';
$html .= 'Jakarta, ' . date('d F Y') . '<br><br>';
$html .= '<p>Admin</p><br><br>';
$html .= '<hr style="width:200px;">';
$html .= '<p style="text-align:center;">Mengetahui, Manajer Operasional</p>';
$html .= '</div>';

// Konfigurasi DOMPDF
$options = new Options();
$options->set('isHtml5ParserEnabled', true);
$dompdf = new Dompdf($options);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream("Penggajian_Bulan_$bulan-$tahun.pdf", array("Attachment" => 0));

// Tutup koneksi database
mysqli_close($conn);
?>
