<?php
session_start();
if (!isset($_SESSION['username']) || !in_array($_SESSION['role'], ['admin', 'guru'])) {
    header("Location: index.php");
    exit;
}

include "config.php";
date_default_timezone_set("Asia/Jakarta");

// Ambil ID guru dari parameter URL
$guru_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// Jika tidak ada ID guru, redirect ke halaman rekap
if ($guru_id <= 0) {
    header("Location: rekap_guru.php");
    exit;
}

// Ambil data guru
$guru_query = mysqli_query($conn, "SELECT * FROM guru WHERE id = $guru_id");
if (mysqli_num_rows($guru_query) == 0) {
    echo "<div class='alert alert-danger'>Data guru tidak ditemukan.</div>";
    exit;
}
$guru = mysqli_fetch_assoc($guru_query);

// Konfigurasi pagination
$limit = 20;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

// Query untuk riwayat absensi
$sql = "
    SELECT 
        a.id, 
        a.tanggal,
        a.jam_masuk, 
        a.jam_pulang,
        a.status,
        a.keterangan
    FROM absensi_guru a
    WHERE a.guru_id = $guru_id
    ORDER BY a.tanggal DESC
";

// Query untuk total data
$count_sql = "SELECT COUNT(*) as total FROM absensi_guru WHERE guru_id = $guru_id";
$count_result = mysqli_query($conn, $count_sql);
if ($count_result) {
    $count_row = mysqli_fetch_assoc($count_result);
    $total_rows = $count_row['total'];
} else {
    $total_rows = 0;
}

// Tambahkan pagination
$sql .= " LIMIT $limit OFFSET $offset";

$data = mysqli_query($conn, $sql);
if (!$data) {
    echo "<div class='alert alert-danger'>Error dalam query: " . mysqli_error($conn) . "</div>";
    $data = null;
}

// Fungsi untuk menentukan keterangan berdasarkan jam masuk
function getKeterangan($jam_masuk, $existing_keterangan) {
    // Jika sudah ada keterangan dan bukan Telat/Tepat Waktu, pertahankan
    if (!empty($existing_keterangan) && $existing_keterangan !== 'Tepat Waktu' && $existing_keterangan !== 'Telat') {
        return $existing_keterangan;
    }
    
    // Jika tidak ada jam masuk, kembalikan string kosong
    if (empty($jam_masuk)) {
        return $existing_keterangan;
    }
    
    // Tentukan keterangan berdasarkan jam masuk
    $jam_batas = '07:00:00';
    return (strtotime($jam_masuk) > strtotime($jam_batas)) ? 'Telat' : 'Tepat Waktu';
}

// Fungsi untuk mendapatkan teks status
function getStatusText($status) {
    switch($status) {
        case 'H': return 'Hadir';
        case 'I': return 'Izin';
        case 'S': return 'Sakit';
        case 'A': return 'Alpa';
        default: return $status;
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sistem Absensi QR - Riwayat Absensi Guru</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <style>
        .status-hadir { color: green; }
        .status-terlambat { color: orange; }
        .status-tanpa-keterangan { color: red; }
        .status-izin { color: blue; }
        .status-sakit { color: purple; }
        .table th { background-color: #f8f9fa; }
        .card-header { background-color: #f0f8ff; }
        .badge-status { font-size: 0.85em; padding: 5px 10px; border-radius: 15px; }
        .pagination { justify-content: center; margin-top: 20px; }
        .badge-tepat-waktu { background-color: #28a745; color: white; }
        .badge-telat { background-color: #ffc107; color: black; }
        .navbar-custom { background-color: #f8f9fa; border-bottom: 1px solid #dee2e6; }
        .print-only { display: none; }
        @media print {
            body * {
                visibility: hidden;
            }
            .print-container, .print-container * {
                visibility: visible;
            }
            .print-container {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
            }
            .no-print {
                display: none !important;
            }
            .print-only {
                display: block;
            }
            .table {
                font-size: 12px;
            }
        }
    </style>
</head>
<body class="container mt-4">
    <!-- Navbar Custom -->
    <nav class="navbar navbar-expand-lg navbar-light navbar-custom mb-4 no-print">
        <div class="container-fluid">
            <a class="navbar-brand" href="dashboard.php">
                <i class="bi bi-house-door"></i> Dashboard
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a href="rekap_guru.php" class="btn btn-outline-primary me-2">
                            <i class="bi bi-arrow-left"></i> Kembali ke Rekap
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="print-container">
        <!-- Header untuk cetak -->
        <div class="print-only text-center mb-4">
            <h3>RIWAYAT ABSENSI GURU</h3>
            <h4><?= htmlspecialchars($guru['nama']) ?></h4>
            <p>NIP: <?= htmlspecialchars($guru['nip']) ?></p>
            <p>Dicetak pada: <?= date('d/m/Y H:i:s') ?></p>
            <hr>
        </div>

        <div class="d-flex justify-content-between align-items-center mb-4 no-print">
            <h2>Riwayat Absensi Guru</h2>
            <button onclick="window.print()" class="btn btn-success">
                <i class="bi bi-printer"></i> Cetak
            </button>
        </div>

        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="bi bi-list-check"></i> Riwayat Absensi: 
                    <?= htmlspecialchars($guru['nama']) ?> (NIP: <?= htmlspecialchars($guru['nip']) ?>)
                </h5>
                <div>
                    <span class="badge bg-primary">Total: <?= $total_rows ?> Data</span>
                </div>
            </div>
            <div class="card-body">
                <?php if ($data && mysqli_num_rows($data) > 0): ?>
                <div class="table-responsive">
                    <table class="table table-bordered table-striped table-hover">
                        <thead class="table-light">
                            <tr>
                                <th>No</th>
                                <th>Tanggal</th>
                                <th>Jam Masuk</th>
                                <th>Jam Pulang</th>
                                <th>Status</th>
                                <th>Keterangan</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $no = $offset + 1; while($row = mysqli_fetch_assoc($data)): 
                                $keterangan = getKeterangan($row['jam_masuk'], $row['keterangan']);
                            ?>
                                <tr>
                                    <td><?= $no++ ?></td>
                                    <td><?= date("d/m/Y", strtotime($row['tanggal'])) ?></td>
                                    <td><?= !empty($row['jam_masuk']) ? htmlspecialchars($row['jam_masuk']) : '-' ?></td>
                                    <td>
                                        <?php if (!empty($row['jam_pulang'])): ?>
                                            <span class="text-success"><?= htmlspecialchars($row['jam_pulang']) ?></span>
                                        <?php else: ?>
                                            <span class="text-danger">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php 
                                        $status_class = '';
                                        $status_text = '';
                                        switch($row['status']) {
                                            case 'H': 
                                                $status_class = 'status-hadir'; 
                                                $status_text = 'Hadir';
                                                break;
                                            case 'I': 
                                                $status_class = 'status-izin'; 
                                                $status_text = 'Izin';
                                                break;
                                            case 'S': 
                                                $status_class = 'status-sakit'; 
                                                $status_text = 'Sakit';
                                                break;
                                            case 'A': 
                                                $status_class = 'status-tanpa-keterangan'; 
                                                $status_text = 'Alpa';
                                                break;
                                            default: 
                                                $status_text = $row['status'];
                                        }
                                        ?>
                                        <span class="badge badge-status <?= $status_class ?>">
                                            <?= $status_text ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php if ($keterangan === 'Tepat Waktu'): ?>
                                            <span class="badge badge-tepat-waktu">Tepat Waktu</span>
                                        <?php elseif ($keterangan === 'Telat'): ?>
                                            <span class="badge badge-telat">Telat</span>
                                        <?php else: ?>
                                            <?= !empty($keterangan) ? htmlspecialchars($keterangan) : '-' ?>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <?php if ($total_rows > $limit): ?>
                <nav aria-label="Page navigation" class="no-print">
                    <ul class="pagination">
                        <?php if ($page > 1): ?>
                        <li class="page-item">
                            <a class="page-link" href="?id=<?= $guru_id ?>&page=<?= $page - 1 ?>" aria-label="Previous">
                                <span aria-hidden="true">&laquo;</span>
                            </a>
                        </li>
                        <?php endif; ?>

                        <?php
                        $total_pages = ceil($total_rows / $limit);
                        $start_page = max(1, $page - 2);
                        $end_page = min($total_pages, $start_page + 4);
                        
                        if ($end_page - $start_page < 4) {
                            $start_page = max(1, $end_page - 4);
                        }
                        
                        for ($i = $start_page; $i <= $end_page; $i++): 
                        ?>
                        <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                            <a class="page-link" href="?id=<?= $guru_id ?>&page=<?= $i ?>"><?= $i ?></a>
                        </li>
                        <?php endfor; ?>

                        <?php if ($page < $total_pages): ?>
                        <li class="page-item">
                            <a class="page-link" href="?id=<?= $guru_id ?>&page=<?= $page + 1 ?>" aria-label="Next">
                                <span aria-hidden="true">&raquo;</span>
                            </a>
                        </li>
                        <?php endif; ?>
                    </ul>
                </nav>
                <?php endif; ?>

                <?php else: ?>
                    <div class="alert alert-info text-center py-4">
                        <i class="bi bi-info-circle display-4"></i>
                        <h4 class="mt-3">Tidak ada data absensi</h4>
                        <p class="mb-0">Belum ada data absensi untuk guru ini.</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>