<?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 laporan
$query = "SELECT l.*, s.nis, s.nama as nama_siswa 
          FROM bkcare_laporan_masalah l
          LEFT JOIN bkcare_siswa s ON l.id_siswa = s.id_siswa
          WHERE l.id_laporan = $id";
$result = mysqli_query($conn, $query);
$data = mysqli_fetch_assoc($result);

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

// Cek apakah laporan sudah selesai (tidak bisa diedit)
if ($data['status'] == 'selesai') {
    $_SESSION['modal_title'] = 'Tidak Dapat Diedit!';
    $_SESSION['modal_message'] = 'Laporan dengan status Selesai tidak dapat diedit';
    $_SESSION['modal_type'] = 'warning';
    $_SESSION['modal_redirect'] = 'detail.php?id=' . $id;
    header('Location: detail.php?id=' . $id);
    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);

// Proses update data
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $id_siswa = (int)$_POST['id_siswa'];
    $tanggal = mysqli_real_escape_string($conn, $_POST['tanggal']);
    $jenis_masalah = mysqli_real_escape_string($conn, $_POST['jenis_masalah']);
    $deskripsi = mysqli_real_escape_string($conn, $_POST['deskripsi']);
    $status = mysqli_real_escape_string($conn, $_POST['status']);
    
    // Validasi
    $errors = [];
    
    if ($id_siswa <= 0) {
        $errors[] = 'Siswa harus dipilih';
    }
    
    if (empty($tanggal)) {
        $errors[] = 'Tanggal laporan harus diisi';
    }
    
    if (empty($jenis_masalah)) {
        $errors[] = 'Jenis masalah harus diisi';
    }
    
    if (empty($deskripsi)) {
        $errors[] = 'Deskripsi masalah harus diisi';
    }
    
    // Validasi perubahan status
    if ($status != $data['status']) {
        // Jika status diubah menjadi selesai, tambahkan validasi
        if ($status == 'selesai') {
            // Bisa ditambahkan validasi khusus jika diperlukan
        }
    }
    
    // Jika tidak ada error
    if (empty($errors)) {
        $query = "UPDATE bkcare_laporan_masalah 
                  SET id_siswa = $id_siswa,
                      tanggal = '$tanggal',
                      jenis_masalah = '$jenis_masalah',
                      deskripsi = '$deskripsi',
                      status = '$status'
                  WHERE id_laporan = $id";
        
        if (mysqli_query($conn, $query)) {
            // Jika status berubah, buat notifikasi
            if ($status != $data['status']) {
                $status_text = [
                    'baru' => 'Baru',
                    'diproses' => 'Diproses',
                    'selesai' => 'Selesai'
                ];
                
                $pesan = "Status laporan masalah #$id berubah menjadi " . $status_text[$status];
                $notif_query = "INSERT INTO bkcare_notifikasi (id_user, pesan, status) 
                               SELECT id_user, '$pesan', 'belum_dibaca' 
                               FROM bkcare_users 
                               WHERE id_user = {$data['id_pelapor']} OR role IN ('guru_bk', 'admin')";
                mysqli_query($conn, $notif_query);
            }
            
            $_SESSION['modal_title'] = 'Berhasil!';
            $_SESSION['modal_message'] = 'Data laporan 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-red-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-red-600 mr-3"></i>
                    Edit Laporan Masalah
                </h1>
                <p class="text-gray-600 text-sm mt-1">Edit laporan masalah #<?= $id ?></p>
            </div>
        </div>

        <!-- Status Info -->
        <div class="bg-<?= $data['status'] == 'baru' ? 'yellow' : ($data['status'] == 'diproses' ? 'blue' : 'green') ?>-50 border-l-4 border-<?= $data['status'] == 'baru' ? 'yellow' : ($data['status'] == 'diproses' ? 'blue' : 'green') ?>-500 p-4 mb-6 rounded-lg">
            <div class="flex items-start">
                <i class="fas fa-<?= $data['status'] == 'baru' ? 'exclamation-circle' : ($data['status'] == 'diproses' ? 'spinner' : 'check-circle') ?> text-<?= $data['status'] == 'baru' ? 'yellow' : ($data['status'] == 'diproses' ? 'blue' : 'green') ?>-500 mt-1 mr-3"></i>
                <div>
                    <p class="text-sm font-medium text-<?= $data['status'] == 'baru' ? 'yellow' : ($data['status'] == 'diproses' ? 'blue' : 'green') ?>-800">
                        Status Saat Ini: 
                        <span class="font-bold">
                            <?= $data['status'] == 'baru' ? 'Baru' : ($data['status'] == 'diproses' ? 'Diproses' : 'Selesai') ?>
                        </span>
                    </p>
                    <p class="text-xs text-<?= $data['status'] == 'baru' ? 'yellow' : ($data['status'] == 'diproses' ? 'blue' : 'green') ?>-600 mt-1">
                        Anda dapat mengubah status laporan sesuai dengan perkembangannya
                    </p>
                </div>
            </div>
        </div>

        <!-- Form -->
        <div class="card-stat p-8">
            <form action="" method="POST" id="editForm">
                <!-- 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-red-600 mr-2"></i>
                        Siswa <span class="text-red-500">*</span>
                    </label>
                    <select name="id_siswa" 
                            class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-red-600 focus:border-transparent outline-none transition bg-gray-50"
                            required>
                        <option value="">-- Pilih Siswa --</option>
                        <?php 
                        mysqli_data_seek($siswa_result, 0);
                        while($siswa = mysqli_fetch_assoc($siswa_result)): 
                        ?>
                            <option value="<?= $siswa['id_siswa'] ?>" 
                                    <?= $data['id_siswa'] == $siswa['id_siswa'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($siswa['nama']) ?> (NIS: <?= $siswa['nis'] ?>) - Kelas: <?= $siswa['nama_kelas'] ?: '-' ?>
                            </option>
                        <?php endwhile; ?>
                    </select>
                </div>

                <!-- Tanggal dan Jenis Masalah -->
                <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-red-600 mr-2"></i>
                            Tanggal Laporan <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-red-600 focus:border-transparent outline-none transition bg-gray-50"
                               value="<?= $data['tanggal'] ?>"
                               required>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-tag text-red-600 mr-2"></i>
                            Jenis Masalah <span class="text-red-500">*</span>
                        </label>
                        <select name="jenis_masalah" 
                                class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-red-600 focus:border-transparent outline-none transition bg-gray-50"
                                required>
                            <option value="">-- Pilih Jenis Masalah --</option>
                            <option value="Akademik" <?= $data['jenis_masalah'] == 'Akademik' ? 'selected' : '' ?>>Akademik</option>
                            <option value="Perilaku" <?= $data['jenis_masalah'] == 'Perilaku' ? 'selected' : '' ?>>Perilaku</option>
                            <option value="Kedisiplinan" <?= $data['jenis_masalah'] == 'Kedisiplinan' ? 'selected' : '' ?>>Kedisiplinan</option>
                            <option value="Sosial" <?= $data['jenis_masalah'] == 'Sosial' ? 'selected' : '' ?>>Sosial</option>
                            <option value="Keluarga" <?= $data['jenis_masalah'] == 'Keluarga' ? 'selected' : '' ?>>Keluarga</option>
                            <option value="Kesehatan" <?= $data['jenis_masalah'] == 'Kesehatan' ? 'selected' : '' ?>>Kesehatan</option>
                            <option value="Lainnya" <?= $data['jenis_masalah'] == 'Lainnya' ? 'selected' : '' ?>>Lainnya</option>
                        </select>
                    </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-red-600 mr-2"></i>
                        Status Laporan
                    </label>
                    <div class="flex space-x-4">
                        <label class="flex items-center p-3 border border-gray-300 rounded-xl hover:bg-yellow-50 transition cursor-pointer flex-1">
                            <input type="radio" 
                                   name="status" 
                                   value="baru" 
                                   class="mr-2 text-yellow-600 focus:ring-yellow-500"
                                   <?= $data['status'] == 'baru' ? 'checked' : '' ?>
                                   required>
                            <i class="fas fa-exclamation-circle text-yellow-500 mr-2"></i>
                            <span class="text-sm font-medium text-gray-700">Baru</span>
                        </label>
                        <label class="flex items-center p-3 border border-gray-300 rounded-xl hover:bg-blue-50 transition cursor-pointer flex-1">
                            <input type="radio" 
                                   name="status" 
                                   value="diproses" 
                                   class="mr-2 text-blue-600 focus:ring-blue-500"
                                   <?= $data['status'] == 'diproses' ? 'checked' : '' ?>
                                   required>
                            <i class="fas fa-spinner text-blue-500 mr-2"></i>
                            <span class="text-sm font-medium text-gray-700">Diproses</span>
                        </label>
                        <label class="flex items-center p-3 border border-gray-300 rounded-xl hover:bg-green-50 transition cursor-pointer flex-1">
                            <input type="radio" 
                                   name="status" 
                                   value="selesai" 
                                   class="mr-2 text-green-600 focus:ring-green-500"
                                   <?= $data['status'] == 'selesai' ? 'checked' : '' ?>
                                   required>
                            <i class="fas fa-check-circle text-green-500 mr-2"></i>
                            <span class="text-sm font-medium text-gray-700">Selesai</span>
                        </label>
                    </div>
                </div>

                <!-- Deskripsi Masalah -->
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-align-left text-red-600 mr-2"></i>
                        Deskripsi Masalah <span class="text-red-500">*</span>
                    </label>
                    <textarea name="deskripsi" 
                              rows="5" 
                              class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-red-600 focus:border-transparent outline-none transition bg-gray-50"
                              placeholder="Jelaskan secara detail masalah yang terjadi..."
                              required><?= htmlspecialchars($data['deskripsi']) ?></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 deskripsi = $('textarea[name="deskripsi"]').val();
        
        if (deskripsi.length < 10) {
            e.preventDefault();
            alert('Deskripsi masalah minimal 10 karakter');
            $('textarea[name="deskripsi"]').addClass('border-red-500 focus:ring-red-500');
        }
    });
});
</script>

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