<?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['error_message'] = 'Akses tidak valid';
    $_SESSION['error_title'] = 'Error!';
    header('Location: index.php');
    exit;
}

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

// Ambil data untuk informasi
$query = "SELECT s.nama, s.nis, s.id_user, s.status 
          FROM bkcare_siswa s 
          WHERE s.id_siswa = $id";
$result = mysqli_query($conn, $query);
$data = mysqli_fetch_assoc($result);

if (!$data) {
    $_SESSION['error_message'] = 'Data siswa tidak ditemukan';
    $_SESSION['error_title'] = 'Error!';
    header('Location: index.php');
    exit;
}

// Cek apakah siswa sudah tidak aktif
if ($data['status'] != 'aktif') {
    $_SESSION['warning_message'] = 'Siswa <strong>' . htmlspecialchars($data['nama']) . '</strong> sudah tidak aktif (status: ' . $data['status'] . ')';
    $_SESSION['warning_title'] = 'Peringatan!';
    header('Location: index.php');
    exit;
}

// Mulai transaksi
mysqli_begin_transaction($conn);

try {
    // Update status siswa menjadi 'pindah'
    $update = mysqli_query($conn, "UPDATE bkcare_siswa SET status = 'pindah' WHERE id_siswa = $id");
    
    if (!$update) {
        throw new Exception('Gagal menonaktifkan data siswa: ' . mysqli_error($conn));
    }
    
    // Nonaktifkan user account jika ada
    if ($data['id_user']) {
        $update_user = mysqli_query($conn, "UPDATE bkcare_users SET is_active = '0' WHERE id_user = {$data['id_user']}");
        if (!$update_user) {
            throw new Exception('Gagal menonaktifkan akun user: ' . mysqli_error($conn));
        }
    }
    
    // Nonaktifkan riwayat kelas yang aktif
    mysqli_query($conn, "UPDATE bkcare_siswa_kelas SET status = 'pindah' WHERE id_siswa = $id AND status = 'aktif'");
    
    mysqli_commit($conn);
    
    $_SESSION['success_message'] = 'Data siswa <strong>' . htmlspecialchars($data['nama']) . ' (NIS: ' . $data['nis'] . ')</strong> berhasil dinonaktifkan';
    $_SESSION['success_title'] = 'Berhasil!';
    
} catch (Exception $e) {
    mysqli_rollback($conn);
    
    $_SESSION['error_message'] = $e->getMessage();
    $_SESSION['error_title'] = 'Gagal!';
}

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