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

// Cek login
checkLogin();

// Cek method dan ID
if ($_SERVER['REQUEST_METHOD'] != 'GET' || !isset($_GET['id'])) {
    $_SESSION['modal_title'] = 'Error!';
    $_SESSION['modal_message'] = 'Akses tidak valid';
    $_SESSION['modal_type'] = 'danger';
    header('Location: index.php');
    exit;
}

$id = (int)$_GET['id'];

// Ambil data laporan
$query = "SELECT l.*, 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';
    header('Location: index.php');
    exit;
}

// Cek apakah laporan sudah selesai
if ($data['status'] == 'selesai') {
    $_SESSION['modal_title'] = 'Tidak Dapat Dihapus!';
    $_SESSION['modal_message'] = 'Laporan dengan status Selesai tidak dapat dihapus';
    $_SESSION['modal_type'] = 'warning';
    header('Location: index.php');
    exit;
}

// Proses hapus
$delete = mysqli_query($conn, "DELETE FROM bkcare_laporan_masalah WHERE id_laporan = $id");

if ($delete) {
    // Buat notifikasi
    $pesan = "Laporan masalah #$id telah dihapus oleh " . $_SESSION['nama'];
    $notif_query = "INSERT INTO bkcare_notifikasi (id_user, pesan, status) 
                   SELECT id_user, '$pesan', 'belum_dibaca' 
                   FROM bkcare_users 
                   WHERE role IN ('guru_bk', 'admin')";
    mysqli_query($conn, $notif_query);
    
    $_SESSION['modal_title'] = 'Berhasil!';
    $_SESSION['modal_message'] = 'Data laporan berhasil dihapus';
    $_SESSION['modal_type'] = 'success';
} else {
    $_SESSION['modal_title'] = 'Gagal!';
    $_SESSION['modal_message'] = 'Gagal menghapus data: ' . mysqli_error($conn);
    $_SESSION['modal_type'] = 'danger';
}

header('Location: index.php');
exit;
?>