<?php
session_start();
require_once '../../config/database.php';
require_once '../../config/function.php';

// Cek login
checkLogin();

$current_user = getCurrentUser();
$tahun_ajaran = getTahunAjaranAktif();
$tahun_ajaran_id = $tahun_ajaran ? $tahun_ajaran['id_tahun_ajaran'] : 0;

if (!$tahun_ajaran) {
    $_SESSION['modal_title'] = 'Peringatan!';
    $_SESSION['modal_message'] = 'Belum ada tahun ajaran aktif. Silakan aktifkan tahun ajaran terlebih dahulu.';
    $_SESSION['modal_type'] = 'warning';
    $_SESSION['modal_redirect'] = '../tahun_ajaran/';
    header('Location: index.php');
    exit;
}

// PERBAIKAN: Ambil semua guru yang aktif, kecuali yang sudah menjadi wali kelas di tahun ajaran aktif
$guru_query = "SELECT g.id_guru, g.nama_guru, u.username, u.role 
               FROM bkcare_guru g
               JOIN bkcare_users u ON g.id_user = u.id_user
               WHERE u.is_active = '1' 
               AND g.id_guru NOT IN (
                   SELECT wali_kelas FROM bkcare_kelas 
                   WHERE id_tahun_ajaran = '$tahun_ajaran_id' 
                   AND wali_kelas IS NOT NULL
               )
               ORDER BY 
               CASE u.role 
                   WHEN 'guru_bk' THEN 1 
                   WHEN 'wali_kelas' THEN 2 
                   ELSE 3 
               END, 
               g.nama_guru ASC";
$guru_result = mysqli_query($conn, $guru_query);

// Proses tambah data
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $nama_kelas = mysqli_real_escape_string($conn, $_POST['nama_kelas']);
    $wali_kelas = !empty($_POST['wali_kelas']) ? (int)$_POST['wali_kelas'] : 'NULL';
    
    // Validasi
    $errors = [];
    
    if (empty($nama_kelas)) {
        $errors[] = 'Nama kelas harus diisi';
    }
    
    // Cek duplikat nama kelas di tahun ajaran yang sama
    $check = mysqli_query($conn, "SELECT * FROM bkcare_kelas 
                                   WHERE nama_kelas = '$nama_kelas' 
                                   AND id_tahun_ajaran = '$tahun_ajaran_id'");
    if (mysqli_num_rows($check) > 0) {
        $errors[] = 'Nama kelas sudah ada di tahun ajaran ini';
    }
    
    // Jika wali_kelas diisi, pastikan guru ada dan active
    if (!empty($_POST['wali_kelas'])) {
        $check_wali = mysqli_query($conn, "SELECT g.id_guru FROM bkcare_guru g
                                           JOIN bkcare_users u ON g.id_user = u.id_user
                                           WHERE g.id_guru = '$wali_kelas' 
                                           AND u.is_active = '1'");
        if (mysqli_num_rows($check_wali) == 0) {
            $errors[] = 'Wali kelas yang dipilih tidak valid atau tidak aktif';
        } else {
            // Cek apakah guru sudah menjadi wali kelas di kelas lain di tahun ajaran yang sama
            $check_exists = mysqli_query($conn, "SELECT * FROM bkcare_kelas 
                                                  WHERE wali_kelas = '$wali_kelas' 
                                                  AND id_tahun_ajaran = '$tahun_ajaran_id'");
            if (mysqli_num_rows($check_exists) > 0) {
                $errors[] = 'Guru ini sudah menjadi wali kelas di kelas lain pada tahun ajaran yang sama';
            }
        }
    }
    
    // Jika tidak ada error
    if (empty($errors)) {
        $query = "INSERT INTO bkcare_kelas (nama_kelas, wali_kelas, id_tahun_ajaran) 
                  VALUES ('$nama_kelas', $wali_kelas, '$tahun_ajaran_id')";
        
        if (mysqli_query($conn, $query)) {
            $_SESSION['success_message'] = 'Data kelas <strong>' . $nama_kelas . '</strong> berhasil ditambahkan';
            $_SESSION['success_title'] = 'Berhasil!';
            
            header('Location: index.php');
            exit;
        } else {
            $_SESSION['error_message'] = 'Gagal menambahkan data: ' . mysqli_error($conn);
            $_SESSION['error_title'] = 'Gagal!';
            
            header('Location: tambah.php');
            exit;
        }
    } else {
        $_SESSION['warning_message'] = implode('<br>', $errors);
        $_SESSION['warning_title'] = 'Validasi Gagal!';
        
        header('Location: tambah.php');
        exit;
    }
}

include '../../includes/header.php';
include '../../includes/navbar.php';
?>

<!-- Main Content -->
<main class="container mx-auto px-4 py-6">
    <div class="max-w-2xl mx-auto">
        <!-- Header -->
        <div class="flex items-center mb-6">
            <a href="index.php" class="text-gray-600 hover:text-purple-600 transition mr-4">
                <i class="fas fa-arrow-left text-xl"></i>
            </a>
            <div>
                <h1 class="text-2xl font-bold text-gray-800 flex items-center">
                    <i class="fas fa-plus-circle text-purple-600 mr-3"></i>
                    Tambah Kelas
                </h1>
                <p class="text-gray-600 text-sm mt-1">Tambahkan data kelas baru</p>
            </div>
        </div>

        <!-- Alert Notification untuk halaman tambah.php -->
        <?php if (isset($_SESSION['warning_message'])): ?>
        <div id="alert-notification" class="mb-6 rounded-lg p-4 bg-yellow-50 border-l-4 border-yellow-500 shadow-md">
            <div class="flex items-start">
                <div class="flex-shrink-0">
                    <i class="fas fa-exclamation-triangle text-yellow-500 text-xl"></i>
                </div>
                <div class="ml-3 flex-1">
                    <h3 class="text-sm font-medium text-yellow-800"><?= $_SESSION['warning_title'] ?></h3>
                    <div class="mt-1 text-sm text-yellow-700"><?= $_SESSION['warning_message'] ?></div>
                </div>
                <div class="ml-auto pl-3">
                    <button onclick="this.parentElement.parentElement.parentElement.remove()" class="inline-flex text-yellow-500 hover:text-yellow-600">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
        </div>
        <?php 
        unset($_SESSION['warning_message']);
        unset($_SESSION['warning_title']);
        endif; 
        ?>

        <?php if (isset($_SESSION['error_message'])): ?>
        <div id="alert-notification" class="mb-6 rounded-lg p-4 bg-red-50 border-l-4 border-red-500 shadow-md">
            <div class="flex items-start">
                <div class="flex-shrink-0">
                    <i class="fas fa-exclamation-circle text-red-500 text-xl"></i>
                </div>
                <div class="ml-3 flex-1">
                    <h3 class="text-sm font-medium text-red-800"><?= $_SESSION['error_title'] ?></h3>
                    <div class="mt-1 text-sm text-red-700"><?= $_SESSION['error_message'] ?></div>
                </div>
                <div class="ml-auto pl-3">
                    <button onclick="this.parentElement.parentElement.parentElement.remove()" class="inline-flex text-red-500 hover:text-red-600">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
        </div>
        <?php 
        unset($_SESSION['error_message']);
        unset($_SESSION['error_title']);
        endif; 
        ?>

        <!-- Info Tahun Ajaran -->
        <div class="bg-purple-50 p-4 rounded-xl mb-6">
            <div class="flex items-center">
                <i class="fas fa-calendar-alt text-purple-600 mr-3"></i>
                <div>
                    <span class="text-sm text-gray-600">Tahun Ajaran Aktif:</span>
                    <span class="font-semibold text-gray-800 ml-2">
                        <?= htmlspecialchars($tahun_ajaran['tahun_ajaran']) ?> - Semester <?= ucfirst($tahun_ajaran['semester']) ?>
                    </span>
                </div>
            </div>
        </div>

        <!-- Form -->
        <div class="card-stat p-8">
            <form action="" method="POST" id="tambahForm">
                <!-- Nama Kelas -->
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-school text-purple-600 mr-2"></i>
                        Nama Kelas <span class="text-red-500">*</span>
                    </label>
                    <input type="text" 
                           name="nama_kelas" 
                           class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-600 focus:border-transparent outline-none transition bg-gray-50"
                           placeholder="Contoh: X IPA 1, XI IPS 2, XII MIPA 3"
                           value="<?= isset($_POST['nama_kelas']) ? htmlspecialchars($_POST['nama_kelas']) : '' ?>"
                           required>
                    <p class="text-xs text-gray-500 mt-2">
                        <i class="fas fa-info-circle mr-1"></i>
                        Gunakan format yang konsisten, contoh: X IPA 1, XI IPS 2, XII MIPA 3
                    </p>
                </div>

                <!-- Wali Kelas (Select dari guru yang tersedia) -->
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-user-tie text-purple-600 mr-2"></i>
                        Wali Kelas
                    </label>
                    <select name="wali_kelas" class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-600 focus:border-transparent outline-none transition bg-gray-50">
                        <option value="">-- Pilih Wali Kelas --</option>
                        <?php 
                        if (mysqli_num_rows($guru_result) > 0):
                            $guru_bk_options = [];
                            $wali_kelas_options = [];
                            $guru_lain_options = [];
                            
                            // Reset pointer
                            mysqli_data_seek($guru_result, 0);
                            
                            while($guru = mysqli_fetch_assoc($guru_result)) {
                                if ($guru['role'] == 'guru_bk') {
                                    $guru_bk_options[] = $guru;
                                } else if ($guru['role'] == 'wali_kelas') {
                                    $wali_kelas_options[] = $guru;
                                } else {
                                    $guru_lain_options[] = $guru;
                                }
                            }
                            
                            // Tampilkan Guru BK
                            if (count($guru_bk_options) > 0):
                        ?>
                                <optgroup label="Guru BK">
                                    <?php foreach($guru_bk_options as $guru): ?>
                                        <option value="<?= $guru['id_guru'] ?>" 
                                            <?= (isset($_POST['wali_kelas']) && $_POST['wali_kelas'] == $guru['id_guru']) ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($guru['nama_guru']) ?> (<?= htmlspecialchars($guru['username']) ?>)
                                        </option>
                                    <?php endforeach; ?>
                                </optgroup>
                            <?php 
                            endif;
                            
                            // Tampilkan Wali Kelas
                            if (count($wali_kelas_options) > 0):
                            ?>
                                <optgroup label="Wali Kelas">
                                    <?php foreach($wali_kelas_options as $wali): ?>
                                        <option value="<?= $wali['id_guru'] ?>" 
                                            <?= (isset($_POST['wali_kelas']) && $_POST['wali_kelas'] == $wali['id_guru']) ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($wali['nama_guru']) ?> (<?= htmlspecialchars($wali['username']) ?>)
                                        </option>
                                    <?php endforeach; ?>
                                </optgroup>
                            <?php 
                            endif;
                            
                            // Tampilkan Guru Lain
                            if (count($guru_lain_options) > 0):
                            ?>
                                <optgroup label="Guru Lainnya">
                                    <?php foreach($guru_lain_options as $guru): ?>
                                        <option value="<?= $guru['id_guru'] ?>" 
                                            <?= (isset($_POST['wali_kelas']) && $_POST['wali_kelas'] == $guru['id_guru']) ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($guru['nama_guru']) ?> (<?= htmlspecialchars($guru['username']) ?> - <?= ucfirst(str_replace('_', ' ', $guru['role'])) ?>)
                                        </option>
                                    <?php endforeach; ?>
                                </optgroup>
                        <?php 
                            endif;
                        else: 
                        ?>
                            <option value="" disabled>Tidak ada guru aktif tersedia</option>
                        <?php endif; ?>
                    </select>
                    <p class="text-xs text-gray-500 mt-2">
                        <i class="fas fa-info-circle mr-1"></i>
                        Hanya menampilkan guru yang belum menjadi wali kelas di tahun ajaran aktif
                    </p>
                </div>

                <!-- Tombol -->
                <div class="flex justify-end space-x-3 pt-4 border-t border-gray-200">
                    <a href="index.php" class="btn-outline-primary text-sm px-6 py-3">
                        <i class="fas fa-times mr-2"></i>Batal
                    </a>
                    <button type="submit" class="btn-primary text-sm px-6 py-3">
                        <i class="fas fa-save mr-2"></i>Simpan Data
                    </button>
                </div>
            </form>
        </div>
    </div>
</main>

<script>
$(document).ready(function() {
    // Auto hide alert after 5 seconds
    if ($('#alert-notification').length) {
        setTimeout(function() {
            $('#alert-notification').fadeOut('slow');
        }, 5000);
    }

    // Validasi form
    $('#tambahForm').on('submit', function(e) {
        let namaKelas = $('input[name="nama_kelas"]').val();
        let errors = [];
        
        if (!namaKelas) {
            errors.push('Nama kelas harus diisi');
            $('input[name="nama_kelas"]').addClass('border-red-500');
        }
        
        if (errors.length > 0) {
            e.preventDefault();
            alert('Validasi Gagal:\n- ' + errors.join('\n- '));
        }
    });

    // Remove red border on input
    $('input').on('input', function() {
        $(this).removeClass('border-red-500');
    });
});
</script>

<?php include '../../includes/footer.php'; ?>