<?php 
include 'koneksi.php';
cek_akses(['Guru']);

$message = '';
$error = '';

// Ambil daftar kelas di unit guru
$kelas_list = mysqli_query($conn, "SELECT * FROM classes WHERE unit='{$_SESSION['unit']}' ORDER BY name");

// Ambil daftar siswa berdasarkan kelas yang dipilih
$siswa_list = [];
$selected_class = isset($_GET['class_id']) ? $_GET['class_id'] : (isset($_POST['class_id']) ? $_POST['class_id'] : '');
$selected_date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');

if ($selected_class) {
    $siswa_query = "SELECT s.*, c.name as class_name 
                    FROM students s 
                    JOIN classes c ON s.class_id = c.id 
                    WHERE s.class_id = '$selected_class' 
                    ORDER BY s.name";
    $siswa_result = mysqli_query($conn, $siswa_query);
    if ($siswa_result && mysqli_num_rows($siswa_result) > 0) {
        while ($row = mysqli_fetch_assoc($siswa_result)) {
            $siswa_list[] = $row;
        }
    }
}

// Proses simpan absensi
if (isset($_POST['simpan_absensi'])) {
    $class_id = $_POST['class_id'];
    $tanggal = $_POST['tanggal'];
    
    // Loop melalui setiap siswa
    foreach ($_POST['status'] as $siswa_id => $status) {
        // Pastikan status yang dikirim valid
        $valid_status = ['Hadir', 'Sakit', 'Izin', 'Alfa'];
        if (!in_array($status, $valid_status)) {
            continue;
        }
        
        // Cek apakah sudah ada absensi untuk siswa ini pada tanggal tersebut
        $check_query = "SELECT id FROM attendance WHERE student_id = '$siswa_id' AND date = '$tanggal'";
        $check_result = mysqli_query($conn, $check_query);
        
        if (mysqli_num_rows($check_result) > 0) {
            // Update data yang sudah ada
            $query = "UPDATE attendance SET status = '$status', teacher_id = '{$_SESSION['user_id']}' WHERE student_id = '$siswa_id' AND date = '$tanggal'";
        } else {
            // Insert data baru
            $query = "INSERT INTO attendance (student_id, class_id, date, status, teacher_id) 
                      VALUES ('$siswa_id', '$class_id', '$tanggal', '$status', '{$_SESSION['user_id']}')";
        }
        
        if (!mysqli_query($conn, $query)) {
            $error = "Gagal menyimpan untuk siswa ID $siswa_id: " . mysqli_error($conn);
        }
    }
    
    if (empty($error)) {
        $message = "Absensi berhasil disimpan!";
        echo "<script>alert('Absensi berhasil disimpan!'); window.location='absensi_siswa.php?class_id=$class_id&date=$tanggal';</script>";
        exit();
    } else {
        echo "<script>alert('$error');</script>";
    }
}

// Ambil data absensi yang sudah ada untuk tanggal dan kelas yang dipilih
$existing_attendance = [];
if ($selected_class && $selected_date) {
    $attendance_query = "SELECT student_id, status FROM attendance WHERE class_id = '$selected_class' AND date = '$selected_date'";
    $attendance_result = mysqli_query($conn, $attendance_query);
    if ($attendance_result && mysqli_num_rows($attendance_result) > 0) {
        while ($row = mysqli_fetch_assoc($attendance_result)) {
            $existing_attendance[$row['student_id']] = $row['status'];
        }
    }
}

// Hitung statistik untuk ringkasan
$hadir = 0;
$sakit = 0;
$izin = 0;
$alfa = 0;
foreach ($siswa_list as $siswa) {
    $status = isset($existing_attendance[$siswa['id']]) ? $existing_attendance[$siswa['id']] : '';
    if ($status == 'Hadir') $hadir++;
    elseif ($status == 'Sakit') $sakit++;
    elseif ($status == 'Izin') $izin++;
    elseif ($status == 'Alfa') $alfa++;
}
$total_siswa = count($siswa_list);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Absensi Siswa - SIM ISTIQLAL</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/css/adminlte.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/css/theme-istiqlal-green.css">
    <style>
        .content-wrapper { background: #f1f5f9; }
        .card { border-radius: 20px; box-shadow: 0 5px 20px rgba(0,0,0,0.08); }
        .table thead th { background: linear-gradient(135deg, #0b5e4e 0%, #10b981 100%); color: white; }
        .radio-group { display: flex; gap: 15px; justify-content: center; }
        .radio-option { display: inline-flex; align-items: center; gap: 5px; cursor: pointer; padding: 5px 12px; border-radius: 20px; transition: all 0.3s; }
        .radio-option input { margin: 0; transform: scale(1.2); cursor: pointer; }
        .radio-option:hover { background: #e2e8f0; }
        .radio-hadir:has(input:checked) { background: #dcfce7; color: #166534; }
        .radio-sakit:has(input:checked) { background: #fed7aa; color: #9a3412; }
        .radio-izin:has(input:checked) { background: #dbeafe; color: #1e40af; }
        .radio-alpha:has(input:checked) { background: #fee2e2; color: #991b1b; }
        .btn-save { background: linear-gradient(135deg, #0b5e4e 0%, #10b981 100%); border: none; padding: 12px 30px; font-weight: 600; border-radius: 12px; }
        .btn-save:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(11, 94, 78, 0.3); }
        .btn-hadir-semua { background: #10b981; border: none; color: white; padding: 8px 20px; border-radius: 8px; font-weight: 600; }
        .btn-hadir-semua:hover { background: #059669; transform: translateY(-2px); }
        .filter-box { background: white; border-radius: 16px; padding: 20px; margin-bottom: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
        .info-box { background: white; border-radius: 16px; padding: 15px; text-align: center; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
        .info-box-number { font-size: 28px; font-weight: 800; }
        .progress { height: 30px; border-radius: 15px; overflow: hidden; }
        .progress-bar { font-size: 12px; font-weight: 600; display: flex; align-items: center; justify-content: center; }
        .btn-group-actions { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
    </style>
</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">
    <?php include 'sidebar.php'; ?>
    
    <div class="content-wrapper">
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0 font-weight-bold">
                            <i class="fas fa-fingerprint text-primary"></i> Absensi Siswa
                        </h1>
                        <small class="text-muted">Form kehadiran siswa harian</small>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
                            <li class="breadcrumb-item active">Absensi Siswa</li>
                        </ol>
                    </div>
                </div>
            </div>
        </div>

        <div class="content">
            <div class="container-fluid">
                <!-- Filter Kelas dan Tanggal -->
                <div class="filter-box">
                    <form method="GET" action="" id="filterForm">
                        <div class="row align-items-end">
                            <div class="col-md-5">
                                <div class="form-group">
                                    <label><i class="fas fa-school"></i> Pilih Kelas</label>
                                    <select name="class_id" class="form-control" required>
                                        <option value="">-- Pilih Kelas --</option>
                                        <?php while($kelas = mysqli_fetch_assoc($kelas_list)): ?>
                                        <option value="<?= $kelas['id'] ?>" <?= ($selected_class == $kelas['id']) ? 'selected' : '' ?>>
                                            <?= $kelas['name'] ?> (<?= $kelas['unit'] ?>)
                                        </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label><i class="fas fa-calendar"></i> Tanggal</label>
                                    <input type="date" name="date" class="form-control" value="<?= $selected_date ?>" required>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <button type="submit" class="btn btn-primary btn-block">
                                    <i class="fas fa-search"></i> Tampilkan
                                </button>
                            </div>
                        </div>
                    </form>
                </div>

                <!-- Form Absensi -->
                <?php if ($selected_class && count($siswa_list) > 0): ?>
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <div class="d-flex justify-content-between align-items-center">
                            <h4 class="mb-0"><i class="fas fa-check-circle"></i> Form Absensi Harian</h4>
                            <div>
                                <span class="badge bg-light text-dark">
                                    <i class="fas fa-users"></i> Jumlah Siswa: <?= count($siswa_list) ?>
                                </span>
                                <span class="badge bg-light text-dark ml-2">
                                    <i class="fas fa-calendar"></i> <?= date('d-m-Y', strtotime($selected_date)) ?>
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <form method="POST" id="absensiForm">
                            <input type="hidden" name="class_id" value="<?= $selected_class ?>">
                            <input type="hidden" name="tanggal" value="<?= $selected_date ?>">
                            
                            <!-- Tombol Hadir Semua -->
                            <div class="mb-3">
                                <div class="btn-group-actions">
                                    <button type="button" class="btn-hadir-semua" onclick="setAllHadir()">
                                        <i class="fas fa-check-double"></i> Hadir Semua
                                    </button>
                                    <button type="button" class="btn btn-secondary" onclick="resetAll()">
                                        <i class="fas fa-undo"></i> Reset Semua
                                    </button>
                                    <small class="text-muted ms-2">
                                        <i class="fas fa-info-circle"></i> Klik "Hadir Semua" untuk mengisi semua siswa dengan status Hadir
                                    </small>
                                </div>
                            </div>
                            
                            <div class="table-responsive">
                                <table class="table table-bordered table-striped table-hover">
                                    <thead class="table-dark">
                                        <tr>
                                            <th width="5%">No</th>
                                            <th width="40%">Nama Siswa</th>
                                            <th width="13%" class="text-center">Hadir (H)</th>
                                            <th width="13%" class="text-center">Sakit (S)</th>
                                            <th width="13%" class="text-center">Izin (I)</th>
                                            <th width="13%" class="text-center">Alfa (A)</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php 
                                        $no = 1;
                                        foreach ($siswa_list as $siswa):
                                            $current_status = isset($existing_attendance[$siswa['id']]) ? $existing_attendance[$siswa['id']] : '';
                                        ?>
                                        <tr>
                                            <td class="text-center"><?= $no++ ?></td>
                                            <td>
                                                <strong><?= htmlspecialchars($siswa['name']) ?></strong>
                                                <br><small class="text-muted">NIS: <?= htmlspecialchars($siswa['nis']) ?></small>
                                             </div>
                                            <td class="text-center">
                                                <label class="radio-option radio-hadir">
                                                    <input type="radio" name="status[<?= $siswa['id'] ?>]" value="Hadir" <?= ($current_status == 'Hadir') ? 'checked' : '' ?>>
                                                    <span>H</span>
                                                </label>
                                             </div>
                                            <td class="text-center">
                                                <label class="radio-option radio-sakit">
                                                    <input type="radio" name="status[<?= $siswa['id'] ?>]" value="Sakit" <?= ($current_status == 'Sakit') ? 'checked' : '' ?>>
                                                    <span>S</span>
                                                </label>
                                             </div>
                                            <td class="text-center">
                                                <label class="radio-option radio-izin">
                                                    <input type="radio" name="status[<?= $siswa['id'] ?>]" value="Izin" <?= ($current_status == 'Izin') ? 'checked' : '' ?>>
                                                    <span>I</span>
                                                </label>
                                             </div>
                                            <td class="text-center">
                                                <label class="radio-option radio-alpha">
                                                    <input type="radio" name="status[<?= $siswa['id'] ?>]" value="Alfa" <?= ($current_status == 'Alfa') ? 'checked' : '' ?>>
                                                    <span>A</span>
                                                </label>
                                             </div>
                                          </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                    <tfoot class="table-secondary">
                                        <tr>
                                            <td colspan="6" class="text-right">
                                                <button type="submit" name="simpan_absensi" class="btn btn-save btn-lg">
                                                    <i class="fas fa-save"></i> Simpan Absensi
                                                </button>
                                            </div>
                                         </tr>
                                    </tfoot>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Ringkasan Absensi -->
                <div class="row mt-3">
                    <div class="col-md-12">
                        <div class="card">
                            <div class="card-header bg-success text-white">
                                <h5 class="mb-0"><i class="fas fa-chart-bar"></i> Ringkasan Kehadiran</h5>
                            </div>
                            <div class="card-body">
                                <div class="row text-center">
                                    <div class="col-md-3 col-6">
                                        <div class="info-box">
                                            <div class="info-box-number text-success"><?= $hadir ?></div>
                                            <div class="text-muted">Hadir</div>
                                            <div class="progress mt-2" style="height: 8px;">
                                                <div class="progress-bar bg-success" style="width: <?= $total_siswa > 0 ? ($hadir/$total_siswa)*100 : 0 ?>%"></div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-3 col-6">
                                        <div class="info-box">
                                            <div class="info-box-number text-warning"><?= $sakit ?></div>
                                            <div class="text-muted">Sakit</div>
                                            <div class="progress mt-2" style="height: 8px;">
                                                <div class="progress-bar bg-warning" style="width: <?= $total_siswa > 0 ? ($sakit/$total_siswa)*100 : 0 ?>%"></div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-3 col-6">
                                        <div class="info-box">
                                            <div class="info-box-number text-info"><?= $izin ?></div>
                                            <div class="text-muted">Izin</div>
                                            <div class="progress mt-2" style="height: 8px;">
                                                <div class="progress-bar bg-info" style="width: <?= $total_siswa > 0 ? ($izin/$total_siswa)*100 : 0 ?>%"></div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-3 col-6">
                                        <div class="info-box">
                                            <div class="info-box-number text-danger"><?= $alfa ?></div>
                                            <div class="text-muted">Alfa</div>
                                            <div class="progress mt-2" style="height: 8px;">
                                                <div class="progress-bar bg-danger" style="width: <?= $total_siswa > 0 ? ($alfa/$total_siswa)*100 : 0 ?>%"></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="progress mt-3" style="height: 30px;">
                                    <div class="progress-bar bg-success" style="width: <?= $total_siswa > 0 ? ($hadir/$total_siswa)*100 : 0 ?>%">Hadir <?= $total_siswa > 0 ? round(($hadir/$total_siswa)*100) : 0 ?>%</div>
                                    <div class="progress-bar bg-warning" style="width: <?= $total_siswa > 0 ? ($sakit/$total_siswa)*100 : 0 ?>%">Sakit <?= $total_siswa > 0 ? round(($sakit/$total_siswa)*100) : 0 ?>%</div>
                                    <div class="progress-bar bg-info" style="width: <?= $total_siswa > 0 ? ($izin/$total_siswa)*100 : 0 ?>%">Izin <?= $total_siswa > 0 ? round(($izin/$total_siswa)*100) : 0 ?>%</div>
                                    <div class="progress-bar bg-danger" style="width: <?= $total_siswa > 0 ? ($alfa/$total_siswa)*100 : 0 ?>%">Alfa <?= $total_siswa > 0 ? round(($alfa/$total_siswa)*100) : 0 ?>%</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <?php elseif ($selected_class && count($siswa_list) == 0): ?>
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle"></i> 
                    Belum ada siswa di kelas ini. Silakan tambahkan siswa terlebih dahulu.
                    <a href="kelola_siswa.php" class="alert-link">Kelola Siswa</a>
                </div>
                <?php elseif (!$selected_class): ?>
                <div class="alert alert-info">
                    <i class="fas fa-info-circle"></i> 
                    Silakan pilih kelas dan tanggal untuk memulai absensi.
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <footer class="main-footer">
        <strong>&copy; <?= date('Y') ?> SIM ISTIQLAL - Sistem Administrasi Guru</strong>
    </footer>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/js/adminlte.min.js"></script>

<script>
// Fungsi untuk mengisi semua radio button dengan nilai "Hadir"
function setAllHadir() {
    // Ambil semua radio button dengan name="status[...]"
    var radioButtons = document.querySelectorAll('input[type="radio"][name^="status"]');
    
    // Kelompokkan berdasarkan siswa (name attribute)
    var siswaGroups = {};
    radioButtons.forEach(function(radio) {
        var name = radio.name;
        if (!siswaGroups[name]) {
            siswaGroups[name] = [];
        }
        siswaGroups[name].push(radio);
    });
    
    // Untuk setiap siswa, pilih radio dengan value "Hadir"
    for (var name in siswaGroups) {
        var radios = siswaGroups[name];
        for (var i = 0; i < radios.length; i++) {
            if (radios[i].value === 'Hadir') {
                radios[i].checked = true;
                // Trigger change event untuk update style
                var event = new Event('change', { bubbles: true });
                radios[i].dispatchEvent(event);
                break;
            }
        }
    }
}

// Fungsi untuk reset semua radio button
function resetAll() {
    var radioButtons = document.querySelectorAll('input[type="radio"][name^="status"]');
    radioButtons.forEach(function(radio) {
        radio.checked = false;
        var event = new Event('change', { bubbles: true });
        radio.dispatchEvent(event);
    });
}

// Auto submit filter saat class atau date berubah
$(document).ready(function() {
    $('#filterForm select, #filterForm input[type="date"]').on('change', function() {
        $('#filterForm').submit();
    });
    
    // Update style saat radio berubah
    $('input[type="radio"][name^="status"]').on('change', function() {
        var parentLabel = $(this).closest('.radio-option');
        if ($(this).is(':checked')) {
            parentLabel.addClass('active');
        } else {
            parentLabel.removeClass('active');
        }
    });
});
</script>

</body>
</html>