<?php
require_once '../../includes/auth_middleware.php';
require_once '../../config/database.php';
require_once '../../includes/header.php';
checkRole(['admin']);

// Set Default Filter (Awal bulan sampai hari ini)
$start_date = $_GET['start_date'] ?? date('Y-m-01');
$end_date = $_GET['end_date'] ?? date('Y-m-d');

// Query Ambil Data Absen Karyawan
$stmt = $pdo->prepare("
    SELECT a.*, u.username 
    FROM attendance a 
    JOIN users u ON a.user_id = u.id 
    WHERE DATE(a.attendance_time) BETWEEN ? AND ? 
    ORDER BY a.attendance_time DESC
");
$stmt->execute([$start_date, $end_date]);
$attendances = $stmt->fetchAll();

// ==========================================
// LOGIKA MENGHITUNG DURASI KERJA (JAM:MENIT)
// ==========================================
$work_durations = [];
foreach ($attendances as $row) {
    $date = date('Y-m-d', strtotime($row['attendance_time']));
    $day = date('d', strtotime($row['attendance_time']));
    $username = $row['username'];
    $type = $row['type'];
    
    // Inisialisasi wadah data per karyawan & tanggal
    if (!isset($work_durations[$username][$date])) {
        $work_durations[$username][$date] = ['in' => null, 'out' => null, 'day' => $day];
    }
    
    // Simpan waktu Masuk / Pulang dalam format Timestamp Unix (detik)
    if ($type == 'in') {
        $work_durations[$username][$date]['in'] = strtotime($row['attendance_time']);
    } else if ($type == 'out') {
        $work_durations[$username][$date]['out'] = strtotime($row['attendance_time']);
    }
}
?>

<div class="container" style="max-width: 1200px;">
    <header style="margin-bottom: 2rem; display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 1rem;">
        <div>
            <h2 style="margin:0;">LAPORAN KEHADIRAN KARYAWAN</h2>
            <p class="report-period" style="color: #4b5563; margin:5px 0 0 0; font-weight: bold; font-size: 1.1rem;">
                Periode: <?= date('d M Y', strtotime($start_date)) ?> s/d <?= date('d M Y', strtotime($end_date)) ?>
            </p>
        </div>
        
        <form method="GET" class="no-print" style="display: flex; gap: 10px; align-items: center; background: white; padding: 10px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
            <div style="display: flex; flex-direction: column;">
                <label style="font-size: 0.75rem; color: #666; font-weight: bold;">Dari Tanggal</label>
                <input type="date" name="start_date" value="<?= $start_date ?>" style="padding: 8px; border: 1px solid #ddd; border-radius: 6px;">
            </div>
            <span style="font-weight: bold; color: #999; margin-top: 15px;">-</span>
            <div style="display: flex; flex-direction: column;">
                <label style="font-size: 0.75rem; color: #666; font-weight: bold;">Sampai Tanggal</label>
                <input type="date" name="end_date" value="<?= $end_date ?>" style="padding: 8px; border: 1px solid #ddd; border-radius: 6px;">
            </div>
            <button type="submit" class="btn-primary" style="margin-top: 15px; padding: 10px 15px; border-radius: 6px;">Filter</button>
            <button type="button" onclick="window.print()" style="margin-top: 15px; padding: 10px 15px; border-radius: 6px; background: #374151; color: white; border: none; cursor: pointer; font-weight: bold;">🖨️ Print PDF</button>
        </form>
    </header>

    <div class="card" style="border-top: 5px solid #10b981; margin-bottom: 2rem;">
        <div style="overflow-x: auto;">
            <table style="width: 100%; border-collapse: collapse; min-width: 800px;">
                <thead style="background: #f9fafb;">
                    <tr style="text-align: left; border-bottom: 2px solid #ddd;">
                        <th style="padding: 15px; color: #4b5563; font-size: 0.85rem;">FOTO BUKTI</th>
                        <th style="padding: 15px; color: #4b5563; font-size: 0.85rem;">NAMA KASIR</th>
                        <th style="padding: 15px; color: #4b5563; font-size: 0.85rem;">WAKTU ABSEN</th>
                        <th style="padding: 15px; color: #4b5563; font-size: 0.85rem;">STATUS</th>
                        <th style="padding: 15px; color: #4b5563; font-size: 0.85rem;" class="no-print">LOKASI GPS</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(count($attendances) > 0): ?>
                        <?php foreach($attendances as $abs): ?>
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 10px;">
                                <div style="width: 60px; height: 60px; border-radius: 8px; overflow: hidden; border: 2px solid #e5e7eb; background: #f3f4f6;">
                                    <?php if(!empty($abs['photo'])): ?>
                                        <img src="../../assets/img/attendance/<?= htmlspecialchars($abs['photo']) ?>" style="width: 100%; height: 100%; object-fit: cover; cursor: pointer;" onclick="window.open(this.src, '_blank')" title="Klik untuk perbesar">
                                    <?php else: ?>
                                        <div style="display: flex; align-items: center; justify-content: center; height: 100%; font-size: 0.7rem; color: #9ca3af;">No Pic</div>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td style="padding: 15px; font-weight: bold; font-size: 1rem; color: #1f2937;">
                                <?= htmlspecialchars($abs['username']) ?>
                            </td>
                            <td style="padding: 15px;">
                                <div style="font-weight: bold; color: #374151;"><?= date('H:i', strtotime($abs['attendance_time'])) ?> WIB</div>
                                <div style="font-size: 0.8rem; color: #6b7280;"><?= date('d M Y', strtotime($abs['attendance_time'])) ?></div>
                            </td>
                            <td style="padding: 15px;">
                                <?php if($abs['type'] == 'in'): ?>
                                    <span style="background: #ecfdf5; color: #059669; padding: 5px 12px; border-radius: 20px; font-size: 0.8rem; font-weight: bold; border: 1px solid #a7f3d0;">
                                        🟢 ABSEN MASUK
                                    </span>
                                <?php else: ?>
                                    <span style="background: #fff7ed; color: #c2410c; padding: 5px 12px; border-radius: 20px; font-size: 0.8rem; font-weight: bold; border: 1px solid #fed7aa;">
                                        🟠 ABSEN PULANG
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td style="padding: 15px;" class="no-print">
                                <?php if(!empty($abs['latitude']) && !empty($abs['longitude'])): ?>
                                    <a href="https://www.google.com/maps?q=<?= $abs['latitude'] ?>,<?= $abs['longitude'] ?>" target="_blank" style="display: inline-block; background: #eff6ff; color: #2563eb; font-size: 0.8rem; font-weight: bold; padding: 8px 12px; border-radius: 6px; text-decoration: none; border: 1px solid #bfdbfe; transition: 0.2s;">
                                        📍 Cek Peta
                                    </a>
                                <?php else: ?>
                                    <span style="color: #9ca3af; font-size: 0.8rem; font-style: italic;">GPS Tidak Aktif</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="5" style="text-align: center; padding: 30px; color: #6b7280; font-size: 1rem;">
                                📭 Tidak ada data kehadiran pada periode ini.
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="card summary-print" style="background: #f9fafb; border-left: 5px solid #3b82f6;">
        <h3 style="color: #1e40af; margin-top: 0; margin-bottom: 15px; font-size: 1.1rem; text-transform: uppercase;">📝 Catatan Ringkasan Kerja</h3>
        <ul style="padding-left: 20px; line-height: 1.8; margin: 0; color: #374151;">
            <?php 
            $has_summary = false;
            foreach ($work_durations as $user => $dates) {
                // Urutkan tanggal dari yang tertua ke terbaru
                ksort($dates);
                foreach ($dates as $date => $data) {
                    // Jika absen lengkap (ada In dan Out)
                    if ($data['in'] && $data['out']) {
                        $has_summary = true;
                        // Pastikan jam pulang setelah jam masuk
                        if ($data['out'] > $data['in']) {
                            $diff = $data['out'] - $data['in']; // Selisih dalam satuan detik
                            $hours = floor($diff / 3600); // Hitung jam
                            $minutes = floor(($diff / 60) % 60); // Hitung sisa menit
                            
                            // Tampilkan teksnya
                            echo "<li><strong>" . htmlspecialchars($user) . "</strong> bekerja di tanggal <strong>{$data['day']}</strong> selama <strong style='color: #10b981;'>{$hours}:" . str_pad($minutes, 2, "0", STR_PAD_LEFT) . " jam:menit</strong>.</li>";
                        }
                    }
                }
            }
            if (!$has_summary) {
                echo "<li style='color:#6b7280; list-style: none;'>Belum ada karyawan yang absen masuk dan pulang di hari yang sama.</li>";
            }
            ?>
        </ul>
    </div>
</div>

<style>
    /* Styling saat di-print PDF */
    @media print {
        .no-print, .side-menu, nav, header select { display: none !important; }
        .report-period { display: block !important; margin-bottom: 20px !important; }
        .summary-print { break-inside: avoid; background: #f3f4f6 !important; border: 1px solid #d1d5db !important; }
        @page { margin: 1cm; }
        body { background: white !important; }
        .card { box-shadow: none !important; border: 1px solid #ccc !important; break-inside: avoid; margin-bottom: 20px !important; }
        a { text-decoration: none !important; color: black !important; border: none !important; }
    }
</style>