<?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");

$message = "";
$message_type = "";

// Cek apakah tabel guru dan izin_guru ada
$check_guru_table = mysqli_query($conn, "SHOW TABLES LIKE 'guru'");
$guru_table_exists = (mysqli_num_rows($check_guru_table) > 0);

$check_izin_table = mysqli_query($conn, "SHOW TABLES LIKE 'izin_guru'");
$izin_table_exists = (mysqli_num_rows($check_izin_table) > 0);

// Jika tabel tidak ada, buat terlebih dahulu
if (!$guru_table_exists) {
    $create_guru_table = "CREATE TABLE guru (
        id INT(11) AUTO_INCREMENT PRIMARY KEY,
        nip VARCHAR(20) NOT NULL,
        nama VARCHAR(100) NOT NULL,
        status ENUM('aktif', 'non-aktif') DEFAULT 'aktif',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )";
    
    if (mysqli_query($conn, $create_guru_table)) {
        // Insert data contoh guru
        $sample_guru = [
            "INSERT INTO guru (nip, nama) VALUES ('198203122005011001', 'Dr. Ahmad Susanto, M.Pd')",
            "INSERT INTO guru (nip, nama) VALUES ('197911052006042002', 'Drs. Budi Raharjo')",
            "INSERT INTO guru (nip, nama) VALUES ('198506152010012003', 'Siti Aminah, S.Pd')",
            "INSERT INTO guru (nip, nama) VALUES ('199005202015032004', 'Dewi Kusuma, S.Pd')"
        ];
        
        foreach ($sample_guru as $query) {
            mysqli_query($conn, $query);
        }
        
        $guru_table_exists = true;
    }
}

if (!$izin_table_exists) {
    $create_izin_table = "CREATE TABLE izin_guru (
        id INT(11) AUTO_INCREMENT PRIMARY KEY,
        guru_id INT(11) NOT NULL,
        tanggal DATE NOT NULL,
        jenis_izin ENUM('I', 'S', 'A') NOT NULL,
        keterangan VARCHAR(255) NULL,
        status ENUM('pending', 'disetujui', 'ditolak') DEFAULT 'disetujui',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (guru_id) REFERENCES guru(id) ON DELETE CASCADE
    )";
    
    mysqli_query($conn, $create_izin_table);
    $izin_table_exists = true;
} else {
    // Cek apakah kolom status sudah ada di tabel izin_guru
    $check_status_column = mysqli_query($conn, "SHOW COLUMNS FROM izin_guru LIKE 'status'");
    if (mysqli_num_rows($check_status_column) == 0) {
        // Tambahkan kolom status jika belum ada
        $add_status_column = "ALTER TABLE izin_guru ADD COLUMN status ENUM('pending', 'disetujui', 'ditolak') DEFAULT 'disetujui'";
        mysqli_query($conn, $add_status_column);
    }
}

// Proses form input izin
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit_izin'])) {
    $guru_id = (int)$_POST['guru_id'];
    $tanggal = $_POST['tanggal'];
    $jenis_izin = $_POST['jenis_izin'];
    $keterangan = mysqli_real_escape_string($conn, $_POST['keterangan']);
    
    // Validasi data
    if (empty($guru_id) || empty($tanggal) || empty($jenis_izin)) {
        $message = "Semua field wajib diisi!";
        $message_type = "danger";
    } else {
        // Cek apakah sudah ada data izin untuk guru dan tanggal tersebut
        $check_existing = mysqli_query($conn, "SELECT id FROM izin_guru WHERE guru_id = $guru_id AND tanggal = '$tanggal'");
        
        if (mysqli_num_rows($check_existing) > 0) {
            $message = "Guru tersebut sudah memiliki data izin pada tanggal yang dipilih!";
            $message_type = "warning";
        } else {
            // Insert data izin (tanpa kolom status jika tidak ada)
            $insert_query = "INSERT INTO izin_guru (guru_id, tanggal, jenis_izin, keterangan";
            
            // Cek apakah kolom status ada
            $check_status_column = mysqli_query($conn, "SHOW COLUMNS FROM izin_guru LIKE 'status'");
            if (mysqli_num_rows($check_status_column) > 0) {
                $insert_query .= ", status) VALUES ($guru_id, '$tanggal', '$jenis_izin', '$keterangan', 'disetujui')";
            } else {
                $insert_query .= ") VALUES ($guru_id, '$tanggal', '$jenis_izin', '$keterangan')";
            }
            
            if (mysqli_query($conn, $insert_query)) {
                $message = "Data izin berhasil disimpan!";
                $message_type = "success";
                
                // Redirect ke rekap_bulanan_guru.php setelah 2 detik
                $bulan = date('m', strtotime($tanggal));
                $tahun = date('Y', strtotime($tanggal));
                echo "<script>
                    setTimeout(function() {
                        window.location.href = 'rekap_bulanan_guru.php?bulan=$bulan&tahun=$tahun';
                    }, 2000);
                </script>";
            } else {
                $message = "Error: " . mysqli_error($conn);
                $message_type = "danger";
            }
        }
    }
}

// Proses hapus data izin
if (isset($_GET['hapus'])) {
    $id = (int)$_GET['hapus'];
    
    // Validasi ID
    if ($id > 0) {
        $delete_query = "DELETE FROM izin_guru WHERE id = $id";
        
        if (mysqli_query($conn, $delete_query)) {
            $_SESSION['message'] = "Data izin berhasil dihapus!";
            $_SESSION['message_type'] = "success";
        } else {
            $_SESSION['message'] = "Error: " . mysqli_error($conn);
            $_SESSION['message_type'] = "danger";
        }
        
        header("Location: " . $_SERVER['PHP_SELF']);
        exit();
    }
}

// Proses form edit izin
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_izin'])) {
    $id = (int)$_POST['id'];
    $guru_id = (int)$_POST['guru_id'];
    $tanggal = $_POST['tanggal'];
    $jenis_izin = $_POST['jenis_izin'];
    $keterangan = mysqli_real_escape_string($conn, $_POST['keterangan']);
    
    // Validasi data
    if (empty($guru_id) || empty($tanggal) || empty($jenis_izin)) {
        $message = "Semua field wajib diisi!";
        $message_type = "danger";
    } else {
        // Cek apakah sudah ada data izin untuk guru dan tanggal tersebut (kecuali data yang sedang diedit)
        $check_existing = mysqli_query($conn, "SELECT id FROM izin_guru WHERE guru_id = $guru_id AND tanggal = '$tanggal' AND id != $id");
        
        if (mysqli_num_rows($check_existing) > 0) {
            $message = "Guru tersebut sudah memiliki data izin pada tanggal yang dipilih!";
            $message_type = "warning";
        } else {
            // Update data izin
            $update_query = "UPDATE izin_guru SET 
                            guru_id = $guru_id, 
                            tanggal = '$tanggal', 
                            jenis_izin = '$jenis_izin', 
                            keterangan = '$keterangan' 
                            WHERE id = $id";
            
            if (mysqli_query($conn, $update_query)) {
                $message = "Data izin berhasil diupdate!";
                $message_type = "success";
                
                // Redirect ke rekap_bulanan_guru.php setelah 2 detik
                $bulan = date('m', strtotime($tanggal));
                $tahun = date('Y', strtotime($tanggal));
                echo "<script>
                    setTimeout(function() {
                        window.location.href = 'rekap_bulanan_guru.php?bulan=$bulan&tahun=$tahun';
                    }, 2000);
                </script>";
            } else {
                $message = "Error: " . mysqli_error($conn);
                $message_type = "danger";
            }
        }
    }
}

// Ambil data untuk edit jika ada parameter edit
$edit_data = null;
if (isset($_GET['edit'])) {
    $id_edit = (int)$_GET['edit'];
    $edit_query = mysqli_query($conn, "SELECT * FROM izin_guru WHERE id = $id_edit");
    
    if (mysqli_num_rows($edit_query) > 0) {
        $edit_data = mysqli_fetch_assoc($edit_query);
    }
}

// Ambil daftar guru aktif
$guru_list = [];
if ($guru_table_exists) {
    $guru_query = mysqli_query($conn, "SELECT id, nip, nama FROM guru WHERE status = 'aktif' ORDER BY nama");
    while ($row = mysqli_fetch_assoc($guru_query)) {
        $guru_list[] = $row;
    }
}

// Ambil pesan dari session jika ada
if (isset($_SESSION['message'])) {
    $message = $_SESSION['message'];
    $message_type = $_SESSION['message_type'];
    unset($_SESSION['message']);
    unset($_SESSION['message_type']);
}
?>

<!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 - Input Izin 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>
        .card-header { 
            background: linear-gradient(45deg, #3498db, #2980b9);
            color: white;
        }
        .navbar-custom { 
            background-color: #2c3e50;
            border-bottom: 1px solid #34495e;
        }
        .navbar-custom .navbar-brand, 
        .navbar-custom .nav-link {
            color: white !important;
        }
        .btn-primary {
            background: linear-gradient(45deg, #3498db, #2980b9);
            border: none;
        }
        .btn-primary:hover {
            background: linear-gradient(45deg, #2980b9, #3498db);
        }
        .badge-izin { background-color: #f39c12; }
        .badge-sakit { background-color: #9b59b6; }
        .badge-alpha { background-color: #e74c3c; }
        .badge-success { background-color: #28a745; }
        .badge-warning { background-color: #ffc107; }
        .badge-danger { background-color: #dc3545; }
        .legend-item {
            display: inline-flex;
            align-items: center;
            margin-right: 15px;
        }
        .legend-color {
            width: 15px;
            height: 15px;
            border-radius: 3px;
            margin-right: 5px;
        }
        .legend-izin { background-color: #f39c12; }
        .legend-sakit { background-color: #9b59b6; }
        .legend-alpha { background-color: #e74c3c; }
        .card {
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            border: none;
            border-radius: 8px;
        }
        .table th {
            background-color: #f8f9fa;
        }
        .info-box {
            background: #e7f4ff;
            border-left: 4px solid #3498db;
            padding: 10px 15px;
            margin-bottom: 15px;
            border-radius: 4px;
        }
        .btn-action {
            padding: 0.25rem 0.5rem;
            font-size: 0.75rem;
        }
    </style>
</head>
<body class="container mt-4">
    <!-- Navbar Custom -->
    <nav class="navbar navbar-expand-lg navbar-dark navbar-custom mb-4 rounded">
        <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_bulanan_guru.php" class="btn btn-outline-light me-2">
                            <i class="bi bi-list-check"></i> Rekap Bulanan Guru
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">
                    <h4 class="mb-0"><i class="bi bi-pencil-square"></i> 
                        <?= $edit_data ? 'Edit Data Izin Guru' : 'Input Izin Guru Manual' ?>
                    </h4>
                </div>
                <div class="card-body">
                    <div class="info-box">
                        <strong>Info:</strong> Data yang diinput di sini akan langsung muncul di 
                        <a href="rekap_bulanan_guru.php">Rekap Bulanan Guru</a>. Pastikan memilih tanggal yang benar.
                    </div>

                    <?php if (!empty($message)): ?>
                        <div class="alert alert-<?= $message_type ?> alert-dismissible fade show" role="alert">
                            <?= $message ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>

                    <div class="mb-3">
                        <div class="legend-item"><div class="legend-color legend-izin"></div> Izin (I)</div>
                        <div class="legend-item"><div class="legend-color legend-sakit"></div> Sakit (S)</div>
                        <div class="legend-item"><div class="legend-color legend-alpha"></div> Alpha (A)</div>
                    </div>

                    <form method="POST">
                        <?php if ($edit_data): ?>
                            <input type="hidden" name="id" value="<?= $edit_data['id'] ?>">
                        <?php endif; ?>
                        
                        <div class="mb-3">
                            <label for="guru_id" class="form-label"><strong>Pilih Guru</strong></label>
                            <select class="form-select" id="guru_id" name="guru_id" required>
                                <option value="">-- Pilih Guru --</option>
                                <?php foreach ($guru_list as $guru): ?>
                                    <option value="<?= $guru['id'] ?>" 
                                        <?= ($edit_data && $edit_data['guru_id'] == $guru['id']) || (isset($_POST['guru_id']) && $_POST['guru_id'] == $guru['id']) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($guru['nip'] . ' - ' . $guru['nama']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="mb-3">
                            <label for="tanggal" class="form-label"><strong>Tanggal Izin</strong></label>
                            <input type="date" class="form-control" id="tanggal" name="tanggal" 
                                   value="<?= $edit_data ? $edit_data['tanggal'] : (isset($_POST['tanggal']) ? $_POST['tanggal'] : date('Y-m-d')) ?>" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><strong>Jenis Izin</strong></label>
                            <div>
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input" type="radio" name="jenis_izin" id="izin" value="I" 
                                           <?= ($edit_data && $edit_data['jenis_izin'] == 'I') || (isset($_POST['jenis_izin']) && $_POST['jenis_izin'] == 'I') || (!$edit_data && !isset($_POST['jenis_izin'])) ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="izin">Izin (I)</label>
                                </div>
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input" type="radio" name="jenis_izin" id="sakit" value="S"
                                           <?= ($edit_data && $edit_data['jenis_izin'] == 'S') || (isset($_POST['jenis_izin']) && $_POST['jenis_izin'] == 'S') ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="sakit">Sakit (S)</label>
                                </div>
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input" type="radio" name="jenis_izin" id="alpha" value="A"
                                           <?= ($edit_data && $edit_data['jenis_izin'] == 'A') || (isset($_POST['jenis_izin']) && $_POST['jenis_izin'] == 'A') ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="alpha">Alpha (A)</label>
                                </div>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="keterangan" class="form-label"><strong>Keterangan</strong></label>
                            <textarea class="form-control" id="keterangan" name="keterangan" rows="3" 
                                      placeholder="Alasan izin/sakit/alpha"><?= $edit_data ? htmlspecialchars($edit_data['keterangan']) : (isset($_POST['keterangan']) ? htmlspecialchars($_POST['keterangan']) : '') ?></textarea>
                        </div>

                        <div class="d-grid gap-2">
                            <?php if ($edit_data): ?>
                                <button type="submit" name="update_izin" class="btn btn-primary">
                                    <i class="bi bi-check-circle"></i> Update Data Izin
                                </button>
                                <a href="input_izin_guru.php" class="btn btn-outline-secondary">
                                    <i class="bi bi-x-circle"></i> Batal Edit
                                </a>
                            <?php else: ?>
                                <button type="submit" name="submit_izin" class="btn btn-primary">
                                    <i class="bi bi-check-circle"></i> Simpan Data Izin
                                </button>
                            <?php endif; ?>
                            <a href="rekap_bulanan_guru.php" class="btn btn-outline-secondary">
                                <i class="bi bi-arrow-left"></i> Kembali ke Rekap Bulanan
                            </a>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Daftar Izin Terbaru -->
            <?php if ($izin_table_exists && $guru_table_exists): ?>
            <div class="card mt-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="bi bi-clock-history"></i> Izin Terbaru</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped table-bordered">
                            <thead>
                                <tr>
                                    <th>Tanggal</th>
                                    <th>NIP</th>
                                    <th>Nama Guru</th>
                                    <th>Jenis</th>
                                    <th>Keterangan</th>
                                    <th>Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                // Query tanpa kolom status untuk menghindari error
                                $recent_query = "
                                    SELECT i.id, i.tanggal, i.jenis_izin, i.keterangan, g.nip, g.nama 
                                    FROM izin_guru i 
                                    JOIN guru g ON i.guru_id = g.id 
                                    ORDER BY i.tanggal DESC, i.created_at DESC 
                                    LIMIT 5
                                ";
                                $recent_result = mysqli_query($conn, $recent_query);
                                
                                if (mysqli_num_rows($recent_result) > 0) {
                                    while ($row = mysqli_fetch_assoc($recent_result)) {
                                        $badge_class = '';
                                        if ($row['jenis_izin'] == 'I') $badge_class = 'badge-izin';
                                        if ($row['jenis_izin'] == 'S') $badge_class = 'badge-sakit';
                                        if ($row['jenis_izin'] == 'A') $badge_class = 'badge-alpha';
                                        
                                        echo "<tr>";
                                        echo "<td>" . date("d/m/Y", strtotime($row['tanggal'])) . "</td>";
                                        echo "<td>" . htmlspecialchars($row['nip']) . "</td>";
                                        echo "<td>" . htmlspecialchars($row['nama']) . "</td>";
                                        echo "<td><span class='badge $badge_class'>";
                                        if ($row['jenis_izin'] == 'I') echo 'Izin';
                                        if ($row['jenis_izin'] == 'S') echo 'Sakit';
                                        if ($row['jenis_izin'] == 'A') echo 'Alpha';
                                        echo "</span></td>";
                                        echo "<td>" . (!empty($row['keterangan']) ? htmlspecialchars($row['keterangan']) : '-') . "</td>";
                                        echo "<td>
                                            <a href='input_izin_guru.php?edit={$row['id']}' class='btn btn-sm btn-outline-primary me-1 btn-action'>
                                                <i class='bi bi-pencil'></i> Edit
                                            </a>
                                            <a href='input_izin_guru.php?hapus={$row['id']}' class='btn btn-sm btn-outline-danger btn-action' onclick='return confirm(\"Yakin ingin menghapus data ini?\")'>
                                                <i class='bi bi-trash'></i> Hapus
                                            </a>
                                        </td>";
                                        echo "</tr>";
                                    }
                                } else {
                                    echo "<tr><td colspan='6' class='text-center'>Tidak ada data izin</td></tr>";
                                }
                                ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Set tanggal default ke hari ini
        document.addEventListener('DOMContentLoaded', function() {
            if (!document.getElementById('tanggal').value) {
                document.getElementById('tanggal').value = new Date().toISOString().substr(0, 10);
            }
        });
    </script>
</body>
</html>