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

// Cek login
checkLogin();

$current_user = getCurrentUser();

// Ambil ID dari URL
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// Ambil data jadwal
$query = "SELECT j.*, s.nis, 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.id_jadwal = $id";
$result = mysqli_query($conn, $query);
$data = mysqli_fetch_assoc($result);

if (!$data) {
    $_SESSION['modal_title'] = 'Error!';
    $_SESSION['modal_message'] = 'Data jadwal tidak ditemukan';
    $_SESSION['modal_type'] = 'danger';
    $_SESSION['modal_redirect'] = 'index.php';
    header('Location: index.php');
    exit;
}

// Cek apakah jadwal sudah selesai atau dibatalkan
if ($data['status'] == 'selesai' || $data['status'] == 'dibatalkan') {
    $_SESSION['modal_title'] = 'Tidak Dapat Diedit!';
    $_SESSION['modal_message'] = 'Jadwal dengan status ' . ucfirst($data['status']) . ' tidak dapat diedit';
    $_SESSION['modal_type'] = 'warning';
    $_SESSION['modal_redirect'] = 'detail.php?id=' . $id;
    header('Location: detail.php?id=' . $id);
    exit;
}

// Ambil data guru BK
$guru_query = "SELECT g.*, u.nama 
               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);

// Proses update data
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $id_guru_bk = (int)$_POST['id_guru_bk'];
    $tanggal = mysqli_real_escape_string($conn, $_POST['tanggal']);
    $jam = mysqli_real_escape_string($conn, $_POST['jam']);
    $status = mysqli_real_escape_string($conn, $_POST['status']);
    $keterangan = mysqli_real_escape_string($conn, $_POST['keterangan']);
    
    // Validasi
    $errors = [];
    
    if ($id_guru_bk <= 0) {
        $errors[] = 'Guru BK harus dipilih';
    }
    
    if (empty($tanggal)) {
        $errors[] = 'Tanggal konseling harus diisi';
    }
    
    if (empty($jam)) {
        $errors[] = 'Jam konseling harus diisi';
    }
    
    // Cek jadwal bentrok (kecuali data sendiri)
    if (empty($errors)) {
        $check_query = "SELECT COUNT(*) as total FROM bkcare_jadwal_konseling 
                        WHERE id_guru_bk = $id_guru_bk 
                        AND tanggal = '$tanggal' 
                        AND jam = '$jam'
                        AND id_jadwal != $id
                        AND status NOT IN ('selesai', 'dibatalkan')";
        $check_result = mysqli_query($conn, $check_query);
        $check = mysqli_fetch_assoc($check_result);
        
        if ($check['total'] > 0) {
            $errors[] = 'Jadwal bentrok dengan jadwal lain untuk guru BK yang sama';
        }
    }
    
    // Jika tidak ada error
    if (empty($errors)) {
        $query = "UPDATE bkcare_jadwal_konseling 
                  SET id_guru_bk = $id_guru_bk,
                      tanggal = '$tanggal',
                      jam = '$jam',
                      status = '$status',
                      keterangan = '$keterangan'
                  WHERE id_jadwal = $id";
        
        if (mysqli_query($conn, $query)) {
            // Jika status berubah, buat notifikasi
            if ($status != $data['status']) {
                $status_text = [
                    'diajukan' => 'Diajukan',
                    'disetujui' => 'Disetujui',
                    'ditolak' => 'Ditolak',
                    'selesai' => 'Selesai',
                    'dibatalkan' => 'Dibatalkan'
                ];
                
                $pesan_siswa = "Status jadwal konseling Anda berubah menjadi " . $status_text[$status];
                $notif_siswa = "INSERT INTO bkcare_notifikasi (id_user, pesan, status) 
                               SELECT id_user, '$pesan_siswa', 'belum_dibaca' 
                               FROM bkcare_users u
                               LEFT JOIN bkcare_siswa s ON u.id_user = s.id_user
                               WHERE s.id_siswa = {$data['id_siswa']} AND u.is_active = 1";
                mysqli_query($conn, $notif_siswa);
                
                $pesan_guru = "Status jadwal konseling berubah menjadi " . $status_text[$status] . " untuk siswa " . $data['nama_siswa'];
                $notif_guru = "INSERT INTO bkcare_notifikasi (id_user, pesan, status) 
                               SELECT id_user, '$pesan_guru', 'belum_dibaca' 
                               FROM bkcare_users u
                               LEFT JOIN bkcare_guru g ON u.id_user = g.id_user
                               WHERE g.id_guru = $id_guru_bk AND u.is_active = 1";
                mysqli_query($conn, $notif_guru);
            }
            
            $_SESSION['modal_title'] = 'Berhasil!';
            $_SESSION['modal_message'] = 'Jadwal konseling berhasil diperbarui';
            $_SESSION['modal_type'] = 'success';
            $_SESSION['modal_redirect'] = 'detail.php?id=' . $id;
        } else {
            $_SESSION['modal_title'] = 'Gagal!';
            $_SESSION['modal_message'] = 'Gagal memperbarui data: ' . mysqli_error($conn);
            $_SESSION['modal_type'] = 'danger';
            $_SESSION['modal_redirect'] = 'edit.php?id=' . $id;
        }
    } else {
        $_SESSION['modal_title'] = 'Validasi Gagal!';
        $_SESSION['modal_message'] = implode('<br>', $errors);
        $_SESSION['modal_type'] = 'warning';
        $_SESSION['modal_redirect'] = 'edit.php?id=' . $id;
    }
    
    header('Location: ' . $_SESSION['modal_redirect']);
    exit;
}

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

<!-- Main Content -->
<main 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="detail.php?id=<?= $id ?>" class="text-gray-600 hover:text-blue-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-edit text-blue-600 mr-3"></i>
                    Edit Jadwal Konseling
                </h1>
                <p class="text-gray-600 text-sm mt-1">Edit jadwal konseling #<?= $id ?></p>
            </div>
        </div>

        <!-- Status Info -->
        <div class="bg-<?= $data['status'] == 'diajukan' ? 'yellow' : ($data['status'] == 'disetujui' ? 'green' : 'blue') ?>-50 border-l-4 border-<?= $data['status'] == 'diajukan' ? 'yellow' : ($data['status'] == 'disetujui' ? 'green' : 'blue') ?>-500 p-4 mb-6 rounded-lg">
            <div class="flex items-start">
                <i class="fas fa-info-circle mt-1 mr-3 text-<?= $data['status'] == 'diajukan' ? 'yellow' : ($data['status'] == 'disetujui' ? 'green' : 'blue') ?>-500"></i>
                <div>
                    <p class="text-sm font-medium text-<?= $data['status'] == 'diajukan' ? 'yellow' : ($data['status'] == 'disetujui' ? 'green' : 'blue') ?>-800">
                        Status Saat Ini: 
                        <span class="font-bold">
                            <?= $data['status'] == 'diajukan' ? 'Diajukan' : ($data['status'] == 'disetujui' ? 'Disetujui' : ($data['status'] == 'ditolak' ? 'Ditolak' : ucfirst($data['status']))) ?>
                        </span>
                    </p>
                    <p class="text-xs text-<?= $data['status'] == 'diajukan' ? 'yellow' : ($data['status'] == 'disetujui' ? 'green' : 'blue') ?>-600 mt-1">
                        Informasi siswa: <?= $data['nama_siswa'] ?> (NIS: <?= $data['nis'] ?>)
                    </p>
                </div>
            </div>
        </div>

        <!-- Form -->
        <div class="card-stat p-8">
            <form action="" method="POST" id="editForm">
                <!-- 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-blue-600 mr-2"></i>
                        Guru BK <span class="text-red-500">*</span>
                    </label>
                    <select name="id_guru_bk" class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-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'] ?>" <?= $data['id_guru_bk'] == $guru['id_guru'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($guru['nama_guru']) ?>
                            </option>
                        <?php endwhile; ?>
                    </select>
                </div>

                <!-- Tanggal dan Jam -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-calendar-alt text-blue-600 mr-2"></i>
                            Tanggal Konseling <span class="text-red-500">*</span>
                        </label>
                        <input type="date" 
                               name="tanggal" 
                               class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-600 focus:border-transparent outline-none transition bg-gray-50"
                               value="<?= $data['tanggal'] ?>"
                               min="<?= date('Y-m-d') ?>"
                               required>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-clock text-blue-600 mr-2"></i>
                            Jam Konseling <span class="text-red-500">*</span>
                        </label>
                        <input type="time" 
                               name="jam" 
                               class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-600 focus:border-transparent outline-none transition bg-gray-50"
                               value="<?= $data['jam'] ?>"
                               required>
                    </div>
                </div>

                <!-- Status -->
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-chart-line text-blue-600 mr-2"></i>
                        Status Jadwal
                    </label>
                    <div class="grid grid-cols-2 md:grid-cols-5 gap-2">
                        <label class="flex items-center p-3 border border-gray-300 rounded-xl hover:bg-yellow-50 transition cursor-pointer">
                            <input type="radio" 
                                   name="status" 
                                   value="diajukan" 
                                   class="mr-2 text-yellow-600 focus:ring-yellow-500"
                                   <?= $data['status'] == 'diajukan' ? 'checked' : '' ?>
                                   required>
                            <i class="fas fa-clock text-yellow-500 mr-1"></i>
                            <span class="text-sm">Diajukan</span>
                        </label>
                        <label class="flex items-center p-3 border border-gray-300 rounded-xl hover:bg-green-50 transition cursor-pointer">
                            <input type="radio" 
                                   name="status" 
                                   value="disetujui" 
                                   class="mr-2 text-green-600 focus:ring-green-500"
                                   <?= $data['status'] == 'disetujui' ? 'checked' : '' ?>>
                            <i class="fas fa-check-circle text-green-500 mr-1"></i>
                            <span class="text-sm">Disetujui</span>
                        </label>
                        <label class="flex items-center p-3 border border-gray-300 rounded-xl hover:bg-red-50 transition cursor-pointer">
                            <input type="radio" 
                                   name="status" 
                                   value="ditolak" 
                                   class="mr-2 text-red-600 focus:ring-red-500"
                                   <?= $data['status'] == 'ditolak' ? 'checked' : '' ?>>
                            <i class="fas fa-times-circle text-red-500 mr-1"></i>
                            <span class="text-sm">Ditolak</span>
                        </label>
                        <label class="flex items-center p-3 border border-gray-300 rounded-xl hover:bg-blue-50 transition cursor-pointer">
                            <input type="radio" 
                                   name="status" 
                                   value="selesai" 
                                   class="mr-2 text-blue-600 focus:ring-blue-500"
                                   <?= $data['status'] == 'selesai' ? 'checked' : '' ?>>
                            <i class="fas fa-flag-checkered text-blue-500 mr-1"></i>
                            <span class="text-sm">Selesai</span>
                        </label>
                        <label class="flex items-center p-3 border border-gray-300 rounded-xl hover:bg-gray-50 transition cursor-pointer">
                            <input type="radio" 
                                   name="status" 
                                   value="dibatalkan" 
                                   class="mr-2 text-gray-600 focus:ring-gray-500"
                                   <?= $data['status'] == 'dibatalkan' ? 'checked' : '' ?>>
                            <i class="fas fa-ban text-gray-500 mr-1"></i>
                            <span class="text-sm">Dibatalkan</span>
                        </label>
                    </div>
                </div>

                <!-- Keterangan -->
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-sticky-note text-blue-600 mr-2"></i>
                        Keterangan
                    </label>
                    <textarea name="keterangan" 
                              rows="4" 
                              class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-600 focus:border-transparent outline-none transition bg-gray-50"
                              placeholder="Tambahkan keterangan jika diperlukan"><?= htmlspecialchars($data['keterangan']) ?></textarea>
                </div>

                <!-- Tombol -->
                <div class="flex justify-end space-x-3">
                    <a href="detail.php?id=<?= $id ?>" 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>Update Data
                    </button>
                </div>
            </form>
        </div>
    </div>
</main>

<script>
$(document).ready(function() {
    $('#editForm').on('submit', function(e) {
        let tanggal = $('input[name="tanggal"]').val();
        let jam = $('input[name="jam"]').val();
        let errors = [];
        
        if (!tanggal) {
            errors.push('Tanggal konseling harus diisi');
        }
        
        if (!jam) {
            errors.push('Jam konseling harus diisi');
        }
        
        if (errors.length > 0) {
            e.preventDefault();
            alert('Validasi Gagal:\n- ' + errors.join('\n- '));
        }
    });
});
</script>

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