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

// Set content type to JSON
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;
}

// Check if it's an AJAX request
$is_ajax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
           strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';

if (!$is_ajax) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    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;
}

// Sanitize and validate inputs
$name = trim($_POST['name'] ?? '');
$parent = isset($_POST['parent']) ? filter_var($_POST['parent'], FILTER_VALIDATE_INT) : 0;
$departmentNameE = isset($_POST['DepartmentNameE']) ? trim($_POST['DepartmentNameE']) : null;

// Validate required fields
if (empty($name)) {
    echo json_encode(['success' => false, 'message' => 'اسم القسم مطلوب']);
    exit;
}

if (strlen($name) < 2 || strlen($name) > 191) {
    echo json_encode(['success' => false, 'message' => 'اسم القسم يجب أن يكون بين 2 و 191 حرف']);
    exit;
}

if ($parent === false || $parent <= 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;

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

// Verify that the college exists
$check_college = $mysqli1->prepare("SELECT id FROM colleges WHERE id = ? AND deleted_at IS NULL");
if (!$check_college) {
    error_log("Prepare failed: " . $mysqli1->error);
    echo json_encode(['success' => false, 'message' => 'حدث خطأ في النظام']);
    exit;
}
$check_college->bind_param("i", $parent);
$check_college->execute();
$college_result = $check_college->get_result();
if ($college_result->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'الكلية المحددة غير موجودة']);
    $check_college->close();
    exit;
}
$check_college->close();

// Check for duplicate section name in the same college
$check_duplicate = $mysqli1->prepare("
    SELECT id FROM sections 
    WHERE name = ? AND parent = ? AND deleted_at IS NULL
");
if (!$check_duplicate) {
    error_log("Prepare failed: " . $mysqli1->error);
    echo json_encode(['success' => false, 'message' => 'حدث خطأ في النظام']);
    exit;
}
$check_duplicate->bind_param("si", $name, $parent);
$check_duplicate->execute();
$duplicate_result = $check_duplicate->get_result();
if ($duplicate_result->num_rows > 0) {
    echo json_encode(['success' => false, 'message' => 'يوجد قسم بنفس الاسم في هذه الكلية بالفعل']);
    $check_duplicate->close();
    exit;
}
$check_duplicate->close();

// Insert section
$stmt = $mysqli1->prepare("
    INSERT INTO sections (
        name, parent, DepartmentNameE, created_at, updated_at
    ) VALUES (?, ?, ?, NOW(), NOW())
");

if (!$stmt) {
    error_log("Prepare failed: " . $mysqli1->error);
    echo json_encode(['success' => false, 'message' => 'حدث خطأ في النظام']);
    exit;
}

$stmt->bind_param("sis", $name, $parent, $departmentNameE);

if ($stmt->execute()) {
    $new_id = $stmt->insert_id;
    $stmt->close();
    
    // Log the action (optional)
    if (function_exists('log_activity')) {
        log_activity($_SESSION['committee_id'] ?? 0, 'insert', 'sections', $new_id, "Added new section: " . $name);
    }
    
    echo json_encode(['success' => true, 'message' => 'تم إضافة القسم بنجاح', 'id' => $new_id]);
} else {
    error_log("Execute failed: " . $stmt->error);
    echo json_encode(['success' => false, 'message' => 'حدث خطأ أثناء إضافة القسم']);
}

exit;