<?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 siswa dari parameter URL
$siswa_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// Jika tidak ada ID siswa, tampilkan pesan error
if ($siswa_id <= 0) {
    echo "<div class='alert alert-danger'>ID siswa tidak valid.</div>";
    exit;
}

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

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

// Ambil parameter filter
$bulan = isset($_GET['bulan']) ? $_GET['bulan'] : date('Y-m');
$tahun = isset($_GET['tahun']) ? $_GET['tahun'] : date('Y');

// Query untuk riwayat absensi siswa tertentu
$sql = "
    SELECT 
        a.id, 
        a.tanggal,
        a.jam, 
        a.jam_pulang,
        a.status,
        a.keterangan
    FROM absensi a
    WHERE a.siswa_id = $siswa_id
";

// Filter berdasarkan bulan dan tahun
if (!empty($bulan)) {
    $sql .= " AND DATE_FORMAT(a.tanggal, '%Y-%m') = '" . mysqli_real_escape_string($conn, $bulan) . "'";
} elseif (!empty($tahun)) {
    $sql .= " AND YEAR(a.tanggal) = '" . mysqli_real_escape_string($conn, $tahun) . "'";
}

$sql .= " ORDER BY a.tanggal DESC";

// Query untuk total data
$count_sql = "SELECT COUNT(*) as total FROM absensi WHERE siswa_id = $siswa_id";
if (!empty($bulan)) {
    $count_sql .= " AND DATE_FORMAT(tanggal, '%Y-%m') = '" . mysqli_real_escape_string($conn, $bulan) . "'";
} elseif (!empty($tahun)) {
    $count_sql .= " AND YEAR(tanggal) = '" . mysqli_real_escape_string($conn, $tahun) . "'";
}

$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 status dan jam
function getKeteranganSiswa($status, $jam_masuk, $jam_pulang, $existing_keterangan) {
    // Jika sudah ada keterangan, pertahankan
    if (!empty($existing_keterangan)) {
        return $existing_keterangan;
    }
    
    // Tentukan keterangan berdasarkan status
    switch($status) {
        case 'H':
            if (!empty($jam_masuk)) {
                $jam_batas = '07:10:00';
                return (strtotime($jam_masuk) > strtotime($jam_batas)) ? 'Terlambat' : 'Tepat Waktu';
            }
            return 'Hadir';
        case 'T':
            return 'Terlambat';
        case 'PA':
            return 'Pulang Awal';
        case 'I':
            return 'Izin';
        case 'S':
            return 'Sakit';
        case 'A':
            return 'Alpa';
        default:
            return $status;
    }
}

// Fungsi untuk mendapatkan teks status siswa
function getStatusTextSiswa($status) {
    switch($status) {
        case 'H': return 'Hadir';
        case 'T': return 'Terlambat';
        case 'PA': return 'Pulang Awal';
        case 'I': return 'Izin';
        case 'S': return 'Sakit';
        case 'A': return 'Alpa';
        default: return $status;
    }
}

// Hitung statistik
$statistik_query = mysqli_query($conn, "
    SELECT 
        COUNT(*) as total_hari,
        SUM(CASE WHEN status = 'H' THEN 1 ELSE 0 END) as hadir,
        SUM(CASE WHEN status = 'T' THEN 1 ELSE 0 END) as terlambat,
        SUM(CASE WHEN status = 'PA' THEN 1 ELSE 0 END) as pulang_awal,
        SUM(CASE WHEN status = 'I' THEN 1 ELSE 0 END) as izin,
        SUM(CASE WHEN status = 'S' THEN 1 ELSE 0 END) as sakit,
        SUM(CASE WHEN status = 'A' THEN 1 ELSE 0 END) as alpa
    FROM absensi 
    WHERE siswa_id = $siswa_id
    " . (!empty($bulan) ? " AND DATE_FORMAT(tanggal, '%Y-%m') = '" . mysqli_real_escape_string($conn, $bulan) . "'" : "") . "
    " . (!empty($tahun) ? " AND YEAR(tanggal) = '" . mysqli_real_escape_string($conn, $tahun) . "'" : "")
);

$statistik = mysqli_fetch_assoc($statistik_query);
$persen_hadir = $statistik['total_hari'] > 0 ? round(($statistik['hadir'] / $statistik['total_hari']) * 100, 1) : 0;

// Generate pilihan bulan dan tahun
$bulan_sekarang = date('Y-m');
$tahun_sekarang = date('Y');
$bulan_options = [];
for ($i = 1; $i <= 12; $i++) {
    $bulan_options[] = date('Y-m', mktime(0, 0, 0, $i, 1, $tahun_sekarang));
}

$tahun_options = [];
for ($i = $tahun_sekarang; $i >= $tahun_sekarang - 5; $i--) {
    $tahun_options[] = $i;
}
?>

<!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 Siswa</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-pulang-awal { color: #ff6b00; }
        .status-izin { color: blue; }
        .status-sakit { color: purple; }
        .status-alpa { color: red; }
        .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; }
        .badge-pulang-awal { background-color: #fd7e14; color: white; }
        .jam-cell { font-family: 'Courier New', monospace; font-weight: bold; }
        .stat-card { border-left: 4px solid #007bff; }
        .stat-card.hadir { border-left-color: #28a745; }
        .stat-card.terlambat { border-left-color: #ffc107; }
        .stat-card.pulang-awal { border-left-color: #fd7e14; }
        .stat-card.izin { border-left-color: #17a2b8; }
        .stat-card.sakit { border-left-color: #6f42c1; }
        .stat-card.alpa { border-left-color: #dc3545; }
    </style>
</head>
<body class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="bi bi-clock-history"></i> Riwayat Absensi Siswa</h2>
    </div>

    <!-- Info Siswa -->
    <div class="card mb-4">
        <div class="card-header">
            <h5 class="mb-0"><i class="bi bi-person-badge"></i> Informasi Siswa</h5>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <table class="table table-borderless">
                        <tr>
                            <th width="120">Nama</th>
                            <td><?= htmlspecialchars($siswa['nama']) ?></td>
                        </tr>
                        <tr>
                            <th>NISN</th>
                            <td><?= htmlspecialchars($siswa['nisn']) ?></td>
                        </tr>
                        <tr>
                            <th>Kelas</th>
                            <td><?= htmlspecialchars($siswa['kelas']) ?></td>
                        </tr>
                    </table>
                </div>
                <div class="col-md-6">
                    <table class="table table-borderless">
                        <tr>
                            <th width="120">Status</th>
                            <td>
                                <span class="badge bg-<?= $siswa['status'] == 'aktif' ? 'success' : 'secondary' ?>">
                                    <?= ucfirst($siswa['status']) ?>
                                </span>
                            </td>
                        </tr>
                        <tr>
                            <th>Total Absensi</th>
                            <td><strong><?= $total_rows ?> hari</strong></td>
                        </tr>
                        <tr>
                            <th>Persentase Hadir</th>
                            <td>
                                <span class="badge bg-<?= $persen_hadir >= 80 ? 'success' : ($persen_hadir >= 60 ? 'warning' : 'danger') ?>">
                                    <?= $persen_hadir ?>%
                                </span>
                            </td>
                        </tr>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Filter -->
    <div class="card mb-4">
        <div class="card-header">
            <h5 class="mb-0"><i class="bi bi-funnel"></i> Filter Periode</h5>
        </div>
        <div class="card-body">
            <form method="GET" class="row g-3">
                <input type="hidden" name="id" value="<?= $siswa_id ?>">
                <div class="col-md-4">
                    <label class="form-label"><strong>Bulan</strong></label>
                    <select name="bulan" class="form-select">
                        <option value="">Pilih Bulan</option>
                        <?php foreach ($bulan_options as $option): ?>
                            <option value="<?= $option ?>" <?= $bulan == $option ? 'selected' : '' ?>>
                                <?= date('F Y', strtotime($option . '-01')) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label"><strong>Tahun</strong></label>
                    <select name="tahun" class="form-select">
                        <option value="">Pilih Tahun</option>
                        <?php foreach ($tahun_options as $option): ?>
                            <option value="<?= $option ?>" <?= $tahun == $option ? 'selected' : '' ?>>
                                <?= $option ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-4 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary me-2"><i class="bi bi-search"></i> Tampilkan</button>
                    <a href="riwayat.php?id=<?= $siswa_id ?>" class="btn btn-outline-secondary">Reset</a>
                </div>
            </form>
        </div>
    </div>

    <!-- Statistik -->
    <div class="row mb-4">
        <div class="col-md-2">
            <div class="card stat-card hadir">
                <div class="card-body text-center">
                    <h3 class="text-success"><?= $statistik['hadir'] ?></h3>
                    <small class="text-muted">Hadir</small>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="card stat-card terlambat">
                <div class="card-body text-center">
                    <h3 class="text-warning"><?= $statistik['terlambat'] ?></h3>
                    <small class="text-muted">Terlambat</small>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="card stat-card pulang-awal">
                <div class="card-body text-center">
                    <h3 class="text-warning"><?= $statistik['pulang_awal'] ?></h3>
                    <small class="text-muted">Pulang Awal</small>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="card stat-card izin">
                <div class="card-body text-center">
                    <h3 class="text-info"><?= $statistik['izin'] ?></h3>
                    <small class="text-muted">Izin</small>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="card stat-card sakit">
                <div class="card-body text-center">
                    <h3 class="text-primary"><?= $statistik['sakit'] ?></h3>
                    <small class="text-muted">Sakit</small>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="card stat-card alpa">
                <div class="card-body text-center">
                    <h3 class="text-danger"><?= $statistik['alpa'] ?></h3>
                    <small class="text-muted">Alpa</small>
                </div>
            </div>
        </div>
    </div>

    <!-- Tabel Riwayat -->
    <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($siswa['nama']) ?> (Kelas: <?= htmlspecialchars($siswa['kelas']) ?>)
            </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 = getKeteranganSiswa($row['status'], $row['jam'], $row['jam_pulang'], $row['keterangan']);
                        ?>
                            <tr>
                                <td><?= $no++ ?></td>
                                <td><?= date("d/m/Y", strtotime($row['tanggal'])) ?></td>
                                <td class="jam-cell">
                                    <?php if (!empty($row['jam'])): ?>
                                        <?= htmlspecialchars($row['jam']) ?>
                                    <?php else: ?>
                                        <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                                <td class="jam-cell">
                                    <?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 'T': 
                                            $status_class = 'status-terlambat'; 
                                            $status_text = 'Terlambat';
                                            break;
                                        case 'PA': 
                                            $status_class = 'status-pulang-awal'; 
                                            $status_text = 'Pulang Awal';
                                            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-alpa'; 
                                            $status_text = 'Alpa';
                                            break;
                                    }
                                    ?>
                                    <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 === 'Terlambat'): ?>
                                        <span class="badge badge-telat">Terlambat</span>
                                    <?php elseif ($keterangan === 'Pulang Awal'): ?>
                                        <span class="badge badge-pulang-awal">Pulang Awal</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">
                <ul class="pagination">
                    <?php if ($page > 1): ?>
                    <li class="page-item">
                        <a class="page-link" href="?id=<?= $siswa_id ?>&page=<?= $page - 1 ?><?= !empty($bulan) ? '&bulan=' . $bulan : '' ?><?= !empty($tahun) ? '&tahun=' . $tahun : '' ?>" 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);
                    
                    for ($i = $start_page; $i <= $end_page; $i++): 
                    ?>
                    <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                        <a class="page-link" href="?id=<?= $siswa_id ?>&page=<?= $i ?><?= !empty($bulan) ? '&bulan=' . $bulan : '' ?><?= !empty($tahun) ? '&tahun=' . $tahun : '' ?>"><?= $i ?></a>
                    </li>
                    <?php endfor; ?>

                    <?php if ($page < $total_pages): ?>
                    <li class="page-item">
                        <a class="page-link" href="?id=<?= $siswa_id ?>&page=<?= $page + 1 ?><?= !empty($bulan) ? '&bulan=' . $bulan : '' ?><?= !empty($tahun) ? '&tahun=' . $tahun : '' ?>" 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 siswa ini.</p>
                </div>
            <?php endif; ?>
        </div>
    </div>

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