<?php
// committee_delete_student.php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
require 'helpers.php';
require_committee();

// التحقق من وجود student_id
if (!isset($_GET['student_id']) || empty($_GET['student_id'])) {
    $_SESSION['error_message'] = 'رقم الطالب مطلوب';
    header('Location: committee_dashboard.php');
    exit();
}

$student_id = $_GET['student_id'];

// التحقق من وجود الطالب
$checkStmt = $mysqli1->prepare("SELECT student_id, college_id FROM students WHERE student_id = ?");
$checkStmt->bind_param("s", $student_id);
$checkStmt->execute();
$student = $checkStmt->get_result()->fetch_assoc();

if (!$student) {
    $_SESSION['error_message'] = 'الطالب غير موجود';
    header('Location: committee_dashboard.php');
    exit();
}

// التحقق من الصلاحيات
$canAll = (bool)($_SESSION['committee_can_all'] ?? false);
$scopeCollege = isset($_SESSION['committee_college_id']) ? (int)$_SESSION['committee_college_id'] : null;

if (!$canAll && $scopeCollege !== null && $student['college_id'] != $scopeCollege) {
    $_SESSION['error_message'] = 'ليس لديك صلاحية لحذف هذا الطالب';
    header('Location: committee_dashboard.php');
    exit();
}

// التحقق من وجود مدفوعات - هذا هو الشرط الوحيد
$checkPayments = $mysqli1->prepare("SELECT COUNT(*) as payment_count FROM payments WHERE student_id = ? AND deleted_at IS NULL");
$checkPayments->bind_param("s", $student_id);
$checkPayments->execute();
$paymentResult = $checkPayments->get_result()->fetch_assoc();

if ($paymentResult['payment_count'] > 0) {
    $_SESSION['error_message'] = 'لا يمكن حذف الطالب لأنه لديه ' . $paymentResult['payment_count'] . ' مدفوعات مرتبطة';
    header('Location: committee_student_profile.php?student_id=' . urlencode($student_id));
    exit();
}

// ⭐⭐ هنا يتم الحذف من جدول students فقط ⭐⭐
$deleteStmt = $mysqli1->prepare("DELETE FROM students WHERE student_id = ?");
$deleteStmt->bind_param("s", $student_id);

if ($deleteStmt->execute()) {
    $_SESSION['success_message'] = "تم حذف الطالب ($student_id) بنجاح";
} else {
    $_SESSION['error_message'] = 'حدث خطأ أثناء حذف الطالب: ' . $mysqli1->error;
}

// العودة إلى لوحة التحكم
header('Location: committee_dashboard.php');
exit();
?>