<?php
// update_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
$id = isset($_POST['id']) ? filter_var($_POST['id'], FILTER_VALIDATE_INT) : 0;
$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 inputs
if ($id === false || $id <= 0) {
    echo json_encode(['success' => false, 'message' => 'معرف القسم غير صالح']);
    exit;
}

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;

// Get current section data to verify ownership
$check_section = $mysqli1->prepare("SELECT parent, name FROM sections WHERE id = ? AND deleted_at IS NULL");
if (!$check_section) {
    error_log("Prepare failed: " . $mysqli1->error);
    echo json_encode(['success' => false, 'message' => 'حدث خطأ في النظام']);
    exit;
}
$check_section->bind_param("i", $id);
$check_section->execute();
$section_result = $check_section->get_result();
$current_section = $section_result->fetch_assoc();
$check_section->close();

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

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

// If changing college, verify new college exists and user has permission
if ($parent != $current_section['parent']) {
    if (!$canAll && $scopeCollege !== null && $scopeCollege != $parent) {
        echo json_encode(['success' => false, 'message' => 'ليس لديك صلاحية لنقل القسم إلى هذه الكلية']);
        exit;
    }
    
    // Verify that the new 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 name (excluding current section)
$check_duplicate = $mysqli1->prepare("
    SELECT id FROM sections 
    WHERE name = ? AND parent = ? AND deleted_at IS NULL AND id != ?
");
if (!$check_duplicate) {
    error_log("Prepare failed: " . $mysqli1->error);
    echo json_encode(['success' => false, 'message' => 'حدث خطأ في النظام']);
    exit;
}
$check_duplicate->bind_param("sii", $name, $parent, $id);
$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();

// Update section
$stmt = $mysqli1->prepare("
    UPDATE sections 
    SET name = ?, parent = ?, DepartmentNameE = ?, updated_at = NOW()
    WHERE id = ? AND deleted_at IS NULL
");

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

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

if ($stmt->execute()) {
    $affected_rows = $stmt->affected_rows;
    $stmt->close();
    
    if ($affected_rows > 0) {
        // Log the action (optional)
        if (function_exists('log_activity')) {
            log_activity($_SESSION['committee_id'] ?? 0, 'update', 'sections', $id, "Updated section: " . $name . " (was: " . $current_section['name'] . ")");
        }
        
        echo json_encode(['success' => true, 'message' => 'تم تحديث القسم بنجاح']);
    } else {
        echo json_encode(['success' => false, 'message' => 'لم يتم إجراء أي تغييرات']);
    }
} else {
    error_log("Execute failed: " . $stmt->error);
    echo json_encode(['success' => false, 'message' => 'حدث خطأ أثناء تحديث القسم']);
}

exit;