<?php
// delete_specialization.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();

require 'db.php';
require 'helpers.php';
require_committee();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: manage-specializations.php');
    exit;
}

$specialization_id = isset($_POST['specialization_id']) ? (int)$_POST['specialization_id'] : 0;

if (!$specialization_id) {
    $_SESSION['error_message'] = 'معرف التخصص غير صالح';
    header('Location: manage-specializations.php');
    exit;
}

// Get college_id for permission check
$check_stmt = $mysqli1->prepare("SELECT college_id FROM specializations WHERE specialization_id = ?");
$check_stmt->bind_param("i", $specialization_id);
$check_stmt->execute();
$result = $check_stmt->get_result();
$specialization = $result->fetch_assoc();

if (!$specialization) {
    $_SESSION['error_message'] = 'التخصص غير موجود';
    header('Location: manage-specializations.php');
    exit;
}

// Check committee permissions
$committeeId = (int)($_SESSION['committee_id'] ?? 0);
$canAll = (bool)($_SESSION['committee_can_all'] ?? false);
$scopeCollege = isset($_SESSION['committee_college_id']) ? (int)$_SESSION['committee_college_id'] : null;

if (!$canAll && $scopeCollege !== null && $scopeCollege != $specialization['college_id']) {
    $_SESSION['error_message'] = 'لا تملك صلاحية حذف هذا التخصص';
    header('Location: manage-specializations.php');
    exit;
}

// Check if specialization is used in students table (if exists)
// Uncomment if you have a students table with specialization_id
/*
$usage_stmt = $mysqli1->prepare("SELECT COUNT(*) as count FROM students WHERE specialization_id = ?");
$usage_stmt->bind_param("i", $specialization_id);
$usage_stmt->execute();
$usage_result = $usage_stmt->get_result();
$usage = $usage_result->fetch_assoc();

if ($usage['count'] > 0) {
    $_SESSION['error_message'] = 'لا يمكن حذف هذا التخصص لأنه مرتبط بعدد من الطلاب';
    header('Location: manage-specializations.php');
    exit;
}
*/

// Soft delete (update deleted_at)
$delete_stmt = $mysqli1->prepare("UPDATE specializations SET deleted_at = NOW() WHERE specialization_id = ?");
$delete_stmt->bind_param("i", $specialization_id);

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

header('Location: manage-specializations.php');
exit;