<?php
// delete_section.php
session_start();
require 'db.php';
require 'helpers.php';
require_committee();

// Set content type to JSON for AJAX responses
header('Content-Type: application/json');

// Check if it's a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

// Validate CSRF token
if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'CSRF token validation failed']);
    exit;
}

// Validate ID
$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
if ($id <= 0) {
    echo json_encode(['success' => false, 'message' => 'معرف القسم غير صالح']);
    exit;
}

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

// Get section's college and name
$stmt = $mysqli1->prepare("SELECT parent, name FROM sections WHERE id = ? AND deleted_at IS NULL");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$section = $result->fetch_assoc();

if (!$section) {
    echo json_encode(['success' => false, 'message' => 'القسم غير موجود']);
    exit;
}

// Check permission
if (!$canAll && $scopeCollege !== null && $scopeCollege != $section['parent']) {
    echo json_encode(['success' => false, 'message' => 'ليس لديك صلاحية لحذف هذا القسم']);
    exit;
}

// Check if section has any specializations
$check_specializations = $mysqli1->prepare("
    SELECT COUNT(*) as count FROM specializations 
    WHERE section_id = ? AND deleted_at IS NULL
");
$check_specializations->bind_param("i", $id);
$check_specializations->execute();
$spec_result = $check_specializations->get_result();
$spec_count = $spec_result->fetch_assoc()['count'];

if ($spec_count > 0) {
    echo json_encode([
        'success' => false, 
        'message' => "لا يمكن حذف القسم لأنه مرتبط بـ {$spec_count} تخصص. يجب حذف أو نقل التخصصات أولاً."
    ]);
    exit;
}

// Soft delete section
$delete_stmt = $mysqli1->prepare("UPDATE sections SET deleted_at = NOW(), updated_at = NOW() WHERE id = ?");
$delete_stmt->bind_param("i", $id);

if ($delete_stmt->execute() && $delete_stmt->affected_rows > 0) {
    $_SESSION['success_message'] = 'تم حذف القسم بنجاح';
    echo json_encode(['success' => true, 'message' => 'تم حذف القسم بنجاح']);
} else {
    error_log("Delete failed: " . $delete_stmt->error);
    echo json_encode(['success' => false, 'message' => 'حدث خطأ أثناء حذف القسم']);
}

exit;