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

// Cek login
checkLogin();

$current_user = getCurrentUser();
$tahun_ajaran_aktif = getTahunAjaranAktif();

if (!$tahun_ajaran_aktif) {
    $_SESSION['modal_title'] = 'Tahun Ajaran Tidak Aktif!';
    $_SESSION['modal_message'] = 'Tidak ada tahun ajaran yang aktif. Silakan aktifkan tahun ajaran terlebih dahulu.';
    $_SESSION['modal_type'] = 'warning';
    $_SESSION['modal_redirect'] = 'index.php';
    header('Location: index.php');
    exit;
}

// Ambil data siswa aktif
$siswa_query = "SELECT s.*, sk.id_kelas, k.nama_kelas 
                FROM bkcare_siswa s
                LEFT JOIN bkcare_siswa_kelas sk ON s.id_siswa = sk.id_siswa AND sk.status = 'aktif'
                LEFT JOIN bkcare_kelas k ON sk.id_kelas = k.id_kelas
                WHERE s.status = 'aktif'
                ORDER BY s.nama ASC";
$siswa_result = mysqli_query($conn, $siswa_query);

// Ambil data guru BK
$guru_query = "SELECT g.*, u.nama, u.id_user 
               FROM bkcare_guru g
               LEFT JOIN bkcare_users u ON g.id_user = u.id_user
               WHERE u.role = 'guru_bk' AND u.is_active = 1
               ORDER BY g.nama_guru ASC";
$guru_result = mysqli_query($conn, $guru_query);

// Ambil data jadwal yang sudah disetujui
$jadwal_query = "SELECT j.*, s.nama as nama_siswa, g.nama_guru
                 FROM bkcare_jadwal_konseling j
                 LEFT JOIN bkcare_siswa s ON j.id_siswa = s.id_siswa
                 LEFT JOIN bkcare_guru g ON j.id_guru_bk = g.id_guru
                 WHERE j.status = 'disetujui'
                 ORDER BY j.tanggal DESC, j.jam DESC";
$jadwal_result = mysqli_query($conn, $jadwal_query);

// Proses tambah data
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $id_siswa = (int)$_POST['id_siswa'];
    $id_guru_bk = (int)$_POST['id_guru_bk'];
    $id_jadwal = !empty($_POST['id_jadwal']) ? (int)$_POST['id_jadwal'] : 'NULL';
    $tanggal = mysqli_real_escape_string($conn, $_POST['tanggal']);
    $jenis_konseling = mysqli_real_escape_string($conn, $_POST['jenis_konseling']);
    $lokasi = mysqli_real_escape_string($conn, $_POST['lokasi']);
    $status = 'proses';
    
    // Validasi
    $errors = [];
    
    if ($id_siswa <= 0) {
        $errors[] = 'Siswa harus dipilih';
    }
    
    if ($id_guru_bk <= 0) {
        $errors[] = 'Guru BK harus dipilih';
    }
    
    if (empty($tanggal)) {
        $errors[] = 'Tanggal konseling harus diisi';
    }
    
    if (empty($jenis_konseling)) {
        $errors[] = 'Jenis konseling harus diisi';
    }
    
    if (empty($lokasi)) {
        $errors[] = 'Lokasi konseling harus diisi';
    }
    
    // Jika tidak ada error
    if (empty($errors)) {
        // Mulai transaksi
        mysqli_begin_transaction($conn);
        
        try {
            // Insert ke tabel konseling
            $query = "INSERT INTO bkcare_konseling (id_siswa, id_guru_bk, id_jadwal, id_tahun_ajaran, tanggal, jenis_konseling, lokasi, status) 
                      VALUES ($id_siswa, $id_guru_bk, $id_jadwal, {$tahun_ajaran_aktif['id_tahun_ajaran']}, '$tanggal', '$jenis_konseling', '$lokasi', '$status')";
            
            if (!mysqli_query($conn, $query)) {
                throw new Exception('Gagal menyimpan data konseling: ' . mysqli_error($conn));
            }
            
            $id_konseling = mysqli_insert_id($conn);
            
            // Buat notifikasi untuk guru BK yang dipilih
            $get_guru_user = "SELECT id_user FROM bkcare_guru WHERE id_guru = $id_guru_bk";
            $result_guru_user = mysqli_query($conn, $get_guru_user);
            $guru_data = mysqli_fetch_assoc($result_guru_user);
            
            if ($guru_data && $guru_data['id_user']) {
                $pesan_guru = "Konseling baru telah dimulai untuk siswa. Jenis: $jenis_konseling";
                $notif_guru = "INSERT INTO bkcare_notifikasi (id_user, pesan, status) 
                               VALUES ({$guru_data['id_user']}, '$pesan_guru', 'belum_dibaca')";
                
                if (!mysqli_query($conn, $notif_guru)) {
                    throw new Exception('Gagal menyimpan notifikasi untuk guru: ' . mysqli_error($conn));
                }
            }
            
            // Notifikasi untuk siswa
            $get_siswa_user = "SELECT id_user FROM bkcare_siswa WHERE id_siswa = $id_siswa";
            $result_siswa_user = mysqli_query($conn, $get_siswa_user);
            $siswa_data = mysqli_fetch_assoc($result_siswa_user);
            
            if ($siswa_data && $siswa_data['id_user']) {
                $pesan_siswa = "Konseling Anda telah dimulai. Jenis: $jenis_konseling, Lokasi: $lokasi";
                $notif_siswa = "INSERT INTO bkcare_notifikasi (id_user, pesan, status) 
                               VALUES ({$siswa_data['id_user']}, '$pesan_siswa', 'belum_dibaca')";
                
                if (!mysqli_query($conn, $notif_siswa)) {
                    throw new Exception('Gagal menyimpan notifikasi untuk siswa: ' . mysqli_error($conn));
                }
            }
            
            // Notifikasi untuk admin
            $notif_admin = "INSERT INTO bkcare_notifikasi (id_user, pesan, status) 
                            SELECT id_user, 'Konseling baru telah dibuat', 'belum_dibaca'
                            FROM bkcare_users 
                            WHERE role = 'admin' AND is_active = 1";
            
            if (!mysqli_query($conn, $notif_admin)) {
                throw new Exception('Gagal menyimpan notifikasi untuk admin: ' . mysqli_error($conn));
            }
            
            // Commit transaksi
            mysqli_commit($conn);
            
            // Set session untuk modal
            $_SESSION['modal_title'] = 'Berhasil!';
            $_SESSION['modal_message'] = 'Data konseling berhasil ditambahkan';
            $_SESSION['modal_type'] = 'success';
            $_SESSION['modal_redirect'] = 'detail.php?id=' . $id_konseling;
            
            // Redirect ke halaman detail
            header('Location: detail.php?id=' . $id_konseling);
            exit;
            
        } catch (Exception $e) {
            mysqli_rollback($conn);
            $_SESSION['modal_title'] = 'Gagal!';
            $_SESSION['modal_message'] = $e->getMessage();
            $_SESSION['modal_type'] = 'danger';
            $_SESSION['modal_redirect'] = 'tambah.php';
            header('Location: tambah.php');
            exit;
        }
    } else {
        $_SESSION['modal_title'] = 'Validasi Gagal!';
        $_SESSION['modal_message'] = implode('<br>', $errors);
        $_SESSION['modal_type'] = 'warning';
        $_SESSION['modal_redirect'] = 'tambah.php';
        header('Location: tambah.php');
        exit;
    }
}

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

<style>
    .card-stat {
        background: white;
        border-radius: 1rem;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    }
    
    .form-icon {
        position: absolute;
        left: 15px;
        top: 50%;
        transform: translateY(-50%);
        color: #9ca3af;
    }
    
    .form-input-icon {
        padding-left: 40px;
    }
</style>

<div class="container mx-auto px-4 py-6">
    <div class="max-w-3xl 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 Konseling
                </h1>
                <p class="text-gray-600 text-sm mt-1">Isi form berikut untuk menambahkan data konseling baru</p>
            </div>
        </div>

        <!-- Info Tahun Ajaran -->
        <div class="bg-blue-50 border-l-4 border-blue-500 p-4 mb-6 rounded-lg">
            <div class="flex items-start">
                <i class="fas fa-info-circle text-blue-500 mt-1 mr-3"></i>
                <div>
                    <p class="text-sm text-blue-700">
                        <span class="font-semibold">Tahun Ajaran Aktif:</span> 
                        <?= $tahun_ajaran_aktif['tahun_ajaran'] ?> - Semester <?= ucfirst($tahun_ajaran_aktif['semester']) ?>
                    </p>
                    <p class="text-xs text-blue-600 mt-1">Konseling akan dibuat untuk tahun ajaran aktif saat ini</p>
                </div>
            </div>
        </div>

        <!-- Form -->
        <div class="card-stat p-8">
            <form action="" method="POST" id="tambahForm">
                <!-- Pilih Siswa -->
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-user-graduate text-purple-600 mr-2"></i>
                        Siswa <span class="text-red-500">*</span>
                    </label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <i class="fas fa-user text-gray-400"></i>
                        </div>
                        <select name="id_siswa" 
                                class="w-full pl-10 pr-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"
                                required>
                            <option value="">-- Pilih Siswa --</option>
                            <?php while($siswa = mysqli_fetch_assoc($siswa_result)): ?>
                                <option value="<?= $siswa['id_siswa'] ?>" 
                                        <?= (isset($_POST['id_siswa']) && $_POST['id_siswa'] == $siswa['id_siswa']) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($siswa['nama']) ?> (NIS: <?= $siswa['nis'] ?>) - Kelas: <?= $siswa['nama_kelas'] ?: '-' ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                </div>

                <!-- Pilih Guru BK -->
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-chalkboard-teacher text-purple-600 mr-2"></i>
                        Guru BK <span class="text-red-500">*</span>
                    </label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <i class="fas fa-chalkboard-teacher text-gray-400"></i>
                        </div>
                        <select name="id_guru_bk" 
                                class="w-full pl-10 pr-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"
                                required>
                            <option value="">-- Pilih Guru BK --</option>
                            <?php while($guru = mysqli_fetch_assoc($guru_result)): ?>
                                <option value="<?= $guru['id_guru'] ?>" 
                                        <?= (isset($_POST['id_guru_bk']) && $_POST['id_guru_bk'] == $guru['id_guru']) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($guru['nama_guru']) ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                </div>

                <!-- Pilih Jadwal (Opsional) -->
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-calendar-alt text-purple-600 mr-2"></i>
                        Jadwal Konseling (Opsional)
                    </label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <i class="fas fa-calendar text-gray-400"></i>
                        </div>
                        <select name="id_jadwal" 
                                class="w-full pl-10 pr-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 Jadwal --</option>
                            <?php while($jadwal = mysqli_fetch_assoc($jadwal_result)): ?>
                                <option value="<?= $jadwal['id_jadwal'] ?>" 
                                        <?= (isset($_POST['id_jadwal']) && $_POST['id_jadwal'] == $jadwal['id_jadwal']) ? 'selected' : '' ?>>
                                    <?= tgl_indonesia($jadwal['tanggal']) ?> - <?= date('H:i', strtotime($jadwal['jam'])) ?> | 
                                    <?= htmlspecialchars($jadwal['nama_siswa']) ?> | 
                                    <?= htmlspecialchars($jadwal['nama_guru']) ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <p class="text-xs text-gray-500 mt-2">
                        <i class="fas fa-info-circle mr-1"></i>
                        Pilih jadwal yang sudah disetujui (kosongkan jika tidak menggunakan jadwal)
                    </p>
                </div>

                <!-- Tanggal -->
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-calendar-day text-purple-600 mr-2"></i>
                        Tanggal Konseling <span class="text-red-500">*</span>
                    </label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <i class="fas fa-calendar-alt text-gray-400"></i>
                        </div>
                        <input type="date" 
                               name="tanggal" 
                               class="w-full pl-10 pr-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"
                               value="<?= isset($_POST['tanggal']) ? $_POST['tanggal'] : date('Y-m-d') ?>"
                               required>
                    </div>
                </div>

                <!-- Jenis Konseling -->
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-tag text-purple-600 mr-2"></i>
                        Jenis Konseling <span class="text-red-500">*</span>
                    </label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <i class="fas fa-tag text-gray-400"></i>
                        </div>
                        <select name="jenis_konseling" 
                                class="w-full pl-10 pr-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"
                                required>
                            <option value="">-- Pilih Jenis Konseling --</option>
                            <option value="Individual" <?= (isset($_POST['jenis_konseling']) && $_POST['jenis_konseling'] == 'Individual') ? 'selected' : '' ?>>Individual</option>
                            <option value="Kelompok" <?= (isset($_POST['jenis_konseling']) && $_POST['jenis_konseling'] == 'Kelompok') ? 'selected' : '' ?>>Kelompok</option>
                            <option value="Krisis" <?= (isset($_POST['jenis_konseling']) && $_POST['jenis_konseling'] == 'Krisis') ? 'selected' : '' ?>>Krisis</option>
                            <option value="Karir" <?= (isset($_POST['jenis_konseling']) && $_POST['jenis_konseling'] == 'Karir') ? 'selected' : '' ?>>Karir</option>
                            <option value="Belajar" <?= (isset($_POST['jenis_konseling']) && $_POST['jenis_konseling'] == 'Belajar') ? 'selected' : '' ?>>Belajar</option>
                        </select>
                    </div>
                </div>

                <!-- Lokasi -->
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-map-marker-alt text-purple-600 mr-2"></i>
                        Lokasi Konseling <span class="text-red-500">*</span>
                    </label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <i class="fas fa-location-dot text-gray-400"></i>
                        </div>
                        <input type="text" 
                               name="lokasi" 
                               class="w-full pl-10 pr-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: Ruang BK, Ruang Kelas, dll"
                               value="<?= isset($_POST['lokasi']) ? htmlspecialchars($_POST['lokasi']) : '' ?>"
                               required>
                    </div>
                </div>

                <!-- Informasi Tambahan -->
                <div class="mb-8 bg-purple-50 p-4 rounded-xl">
                    <div class="flex items-start">
                        <i class="fas fa-lightbulb text-purple-600 mt-1 mr-3"></i>
                        <div>
                            <p class="text-sm font-medium text-purple-800">Informasi Penting:</p>
                            <ul class="text-xs text-purple-700 mt-2 list-disc list-inside">
                                <li>Status awal konseling adalah "Proses"</li>
                                <li>Anda dapat menambahkan sesi konseling setelah data tersimpan</li>
                                <li>Pastikan data siswa dan guru BK sudah terdaftar</li>
                            </ul>
                        </div>
                    </div>
                </div>

                <!-- Tombol -->
                <div class="flex justify-end space-x-3">
                    <a href="index.php" class="px-6 py-3 border border-gray-300 text-gray-700 rounded-xl hover:bg-gray-50 transition text-sm">
                        <i class="fas fa-times mr-2"></i>Batal
                    </a>
                    <button type="submit" class="bg-purple-600 text-white px-6 py-3 rounded-xl hover:bg-purple-700 transition text-sm flex items-center">
                        <i class="fas fa-save mr-2"></i>Simpan Konseling
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
$(document).ready(function() {
    // Validasi form
    $('#tambahForm').on('submit', function(e) {
        let id_siswa = $('select[name="id_siswa"]').val();
        let id_guru_bk = $('select[name="id_guru_bk"]').val();
        let tanggal = $('input[name="tanggal"]').val();
        let jenis_konseling = $('select[name="jenis_konseling"]').val();
        let lokasi = $('input[name="lokasi"]').val();
        let errors = [];
        
        if (!id_siswa) {
            errors.push('Siswa harus dipilih');
            $('select[name="id_siswa"]').addClass('border-red-500');
        } else {
            $('select[name="id_siswa"]').removeClass('border-red-500');
        }
        
        if (!id_guru_bk) {
            errors.push('Guru BK harus dipilih');
            $('select[name="id_guru_bk"]').addClass('border-red-500');
        } else {
            $('select[name="id_guru_bk"]').removeClass('border-red-500');
        }
        
        if (!tanggal) {
            errors.push('Tanggal konseling harus diisi');
            $('input[name="tanggal"]').addClass('border-red-500');
        } else {
            $('input[name="tanggal"]').removeClass('border-red-500');
        }
        
        if (!jenis_konseling) {
            errors.push('Jenis konseling harus dipilih');
            $('select[name="jenis_konseling"]').addClass('border-red-500');
        } else {
            $('select[name="jenis_konseling"]').removeClass('border-red-500');
        }
        
        if (!lokasi) {
            errors.push('Lokasi konseling harus diisi');
            $('input[name="lokasi"]').addClass('border-red-500');
        } else {
            $('input[name="lokasi"]').removeClass('border-red-500');
        }
        
        if (errors.length > 0) {
            e.preventDefault();
            alert('Validasi Gagal:\n- ' + errors.join('\n- '));
        }
    });
    
    // Hapus border merah saat input berubah
    $('select[name="id_siswa"], select[name="id_guru_bk"], select[name="id_jadwal"], input[name="tanggal"], select[name="jenis_konseling"], input[name="lokasi"]').on('change input', function() {
        if ($(this).val()) {
            $(this).removeClass('border-red-500');
        }
    });
});

<?php if (isset($_SESSION['modal_title'])): ?>
    $(document).ready(function() {
        let modalType = '<?= $_SESSION['modal_type'] ?>';
        let modalTitle = '<?= $_SESSION['modal_title'] ?>';
        let modalMessage = '<?= addslashes($_SESSION['modal_message']) ?>';
        let modalRedirect = '<?= $_SESSION['modal_redirect'] ?? '' ?>';
        
        let bgColor = modalType == 'success' ? 'bg-success' : (modalType == 'danger' ? 'bg-danger' : 'bg-warning');
        let icon = modalType == 'success' ? 'check-circle' : (modalType == 'danger' ? 'exclamation-circle' : 'info-circle');
        let iconModal = modalType == 'success' ? 'check-circle' : (modalType == 'danger' ? 'times-circle' : 'exclamation-triangle');
        
        let modalHtml = `
            <div class="modal fade" id="notificationModal" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content rounded-2xl">
                        <div class="modal-header ${bgColor} text-white rounded-t-2xl">
                            <h5 class="modal-title">
                                <i class="fas fa-${icon} me-2"></i>
                                ${modalTitle}
                            </h5>
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body text-center py-5">
                            <div class="modal-icon mb-3">
                                <i class="fas fa-${iconModal} fa-3x text-${modalType}"></i>
                            </div>
                            <p class="mb-0 text-gray-700">${modalMessage}</p>
                        </div>
                        <div class="modal-footer justify-content-center border-t border-gray-100 pt-4">
                            <button type="button" class="btn btn-${modalType == 'success' ? 'success' : (modalType == 'danger' ? 'danger' : 'warning')}" data-bs-dismiss="modal">
                                <i class="fas fa-check me-2"></i>OK
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        if ($('#notificationModal').length === 0) {
            $('body').append(modalHtml);
        }
        
        $('#notificationModal').modal('show');
        
        $('#notificationModal').on('hidden.bs.modal', function() {
            $(this).remove();
            if (modalRedirect && modalRedirect !== window.location.pathname.split('/').pop()) {
                window.location.href = modalRedirect;
            }
        });
    });
    <?php unset($_SESSION['modal_title'], $_SESSION['modal_message'], $_SESSION['modal_type'], $_SESSION['modal_redirect']); ?>
<?php endif; ?>
</script>

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