<?php
// academic_plan_add.php - نسخة محسنة مع تصميم موحد
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
require 'helpers.php';
require_committee();

// إنشاء CSRF token
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf_token = $_SESSION['csrf_token'];

$committeeId = (int)($_SESSION['committee_id'] ?? 0);
$committeeName = (string)($_SESSION['committee_name'] ?? '');
$canAll = (bool)($_SESSION['committee_can_all'] ?? false);
$scopeCollege = isset($_SESSION['committee_college_id']) ? (int)$_SESSION['committee_college_id'] : null;

// دوال التحقق
function validateInt($value, $default = 0) {
    if ($value === null || $value === '') return $default;
    return filter_var($value, FILTER_VALIDATE_INT) !== false ? (int)$value : $default;
}

function validateString($value, $default = '', $maxLength = 255) {
    if ($value === null) return $default;
    $value = trim((string)$value);
    $value = strip_tags($value);
    $value = htmlspecialchars_decode($value, ENT_QUOTES);
    $value = substr($value, 0, $maxLength);
    return $value === '' ? $default : $value;
}

function validateDate($date, $default = null) {
    if (empty($date)) return $default;
    $timestamp = strtotime($date);
    return $timestamp ? date('Y-m-d', $timestamp) : $default;
}

function validateArray($array, $default = []) {
    return is_array($array) ? $array : $default;
}

$plan_id = isset($_GET['id']) ? validateInt($_GET['id']) : 0;
$isEdit = $plan_id > 0;

// Initialize variables
$plan_name = $plan_code = $description = '';
$college_id = $section_id = $program_id = $specialization_id = 0;
$total_semesters = 8;
$total_credit_hours = 0.00;
$is_active = 1;
$selected_batches = []; // Array to store selected batch IDs
$errors = [];

// الحصول على بيانات القوائم
function getColleges($mysqli, $canAll, $scopeCollege) {
    if (!$canAll && $scopeCollege !== null) {
        $stmt = $mysqli->prepare("SELECT id, name FROM colleges WHERE id = ? AND deleted_at IS NULL ORDER BY name");
        $stmt->bind_param('i', $scopeCollege);
        $stmt->execute();
        return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    } else {
        $result = $mysqli->query("SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name");
        return $result->fetch_all(MYSQLI_ASSOC);
    }
}

function getPrograms($mysqli) {
    $result = $mysqli->query("SELECT id, name FROM programs WHERE deleted_at IS NULL ORDER BY name");
    return $result->fetch_all(MYSQLI_ASSOC);
}

function getSections($mysqli) {
    $result = $mysqli->query("SELECT id, name, parent FROM sections WHERE deleted_at IS NULL ORDER BY name");
    return $result->fetch_all(MYSQLI_ASSOC);
}

function getSpecializations($mysqli) {
    $result = $mysqli->query("SELECT specialization_id as id, specialization_name_ar as name, section_id, program_id FROM specializations WHERE deleted_at IS NULL ORDER BY specialization_name_ar");
    return $result->fetch_all(MYSQLI_ASSOC);
}

function getBatches($mysqli) {
    $result = $mysqli->query("SELECT id, value FROM batches WHERE deleted_at IS NULL AND status = 1 ORDER BY value DESC");
    return $result->fetch_all(MYSQLI_ASSOC);
}

$colleges = getColleges($mysqli1, $canAll, $scopeCollege);
$programs = getPrograms($mysqli1);
$sections = getSections($mysqli1);
$specializations = getSpecializations($mysqli1);
$batches = getBatches($mysqli1);

// If edit, fetch plan data and selected batches
if ($isEdit) {
    // التحقق من وجود الخطة وصلاحيات الوصول
    $checkSql = "SELECT * FROM academic_plans WHERE id = ? AND deleted_at IS NULL";
    $types = "i";
    $params = [$plan_id];
    
    if (!$canAll && $scopeCollege !== null) {
        $checkSql .= " AND college_id = ?";
        $types .= "i";
        $params[] = $scopeCollege;
    }
    
    $checkStmt = $mysqli1->prepare($checkSql);
    $checkStmt->bind_param($types, ...$params);
    $checkStmt->execute();
    $plan = $checkStmt->get_result()->fetch_assoc();
    $checkStmt->close();
    
    if (!$plan) {
        $_SESSION['error_message'] = "الخطة الدراسية غير موجودة أو ليس لديك صلاحية للوصول إليها";
        header("Location: academic_plans_list.php");
        exit;
    }
    
    $plan_name = $plan['plan_name'];
    $plan_code = $plan['plan_code'];
    $college_id = (int)$plan['college_id'];
    $section_id = (int)$plan['section_id'];
    $program_id = (int)$plan['program_id'];
    $specialization_id = (int)($plan['specialization_id'] ?? 0);
    $total_semesters = (int)$plan['total_semesters'];
    $total_credit_hours = (float)($plan['total_credit_hours'] ?? 0);
    $description = $plan['description'] ?? '';
    $is_active = (int)$plan['is_active'];
    
    // Get selected batches for this plan
    $batchStmt = $mysqli1->prepare("
        SELECT batch_id, start_date, end_date, is_current 
        FROM academic_plan_batches 
        WHERE plan_id = ?
    ");
    $batchStmt->bind_param('i', $plan_id);
    $batchStmt->execute();
    $batchResult = $batchStmt->get_result();
    while ($row = $batchResult->fetch_assoc()) {
        $selected_batches[(int)$row['batch_id']] = [
            'start_date' => $row['start_date'],
            'end_date' => $row['end_date'],
            'is_current' => (int)$row['is_current']
        ];
    }
    $batchStmt->close();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // التحقق من CSRF
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $errors['general'] = 'خطأ في التحقق من الأمان. الرجاء تحديث الصفحة والمحاولة مرة أخرى.';
    } else {
        // Get and validate form data
        $plan_name = validateString($_POST['plan_name'] ?? '');
        $plan_code = validateString($_POST['plan_code'] ?? '');
        $college_id = validateInt($_POST['college_id'] ?? 0);
        $section_id = validateInt($_POST['section_id'] ?? 0);
        $program_id = validateInt($_POST['program_id'] ?? 0);
        $specialization_id = validateInt($_POST['specialization_id'] ?? 0);
        $total_semesters = validateInt($_POST['total_semesters'] ?? 8);
        $total_credit_hours = isset($_POST['total_credit_hours']) ? (float)$_POST['total_credit_hours'] : 0;
        $description = validateString($_POST['description'] ?? '', '', 1000);
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        // Get and validate batch data
        $batch_ids = isset($_POST['batch_ids']) && is_array($_POST['batch_ids']) ? $_POST['batch_ids'] : [];
        $batch_start_dates = isset($_POST['batch_start_date']) && is_array($_POST['batch_start_date']) ? $_POST['batch_start_date'] : [];
        $batch_end_dates = isset($_POST['batch_end_date']) && is_array($_POST['batch_end_date']) ? $_POST['batch_end_date'] : [];
        $batch_is_current = isset($_POST['batch_is_current']) && is_array($_POST['batch_is_current']) ? $_POST['batch_is_current'] : [];
        
        // Sanitize batch data
        $valid_batch_ids = [];
        foreach ($batch_ids as $bid) {
            $valid_id = validateInt($bid);
            if ($valid_id > 0) {
                $valid_batch_ids[] = $valid_id;
            }
        }
        
        // التحقق من الصلاحيات
        if (!$canAll && $scopeCollege !== null && $college_id != $scopeCollege) {
            $errors['college_id'] = 'ليس لديك صلاحية لاختيار هذه الكلية';
        }
        
        // Validation
        if (empty($plan_name)) {
            $errors['plan_name'] = 'اسم الخطة مطلوب';
        } elseif (strlen($plan_name) < 3) {
            $errors['plan_name'] = 'اسم الخطة يجب أن يكون 3 أحرف على الأقل';
        }
        
        if (empty($plan_code)) {
            $errors['plan_code'] = 'رمز الخطة مطلوب';
        } elseif (!preg_match('/^[A-Za-z0-9\-_]+$/', $plan_code)) {
            $errors['plan_code'] = 'رمز الخطة يجب أن يحتوي على أحرف إنجليزية وأرقام وشرطة فقط';
        }
        
        if ($college_id <= 0) {
            $errors['college_id'] = 'الكلية مطلوبة';
        }
        
        if ($section_id <= 0) {
            $errors['section_id'] = 'القسم مطلوب';
        }
        
        if ($program_id <= 0) {
            $errors['program_id'] = 'البرنامج مطلوب';
        }
        
        if ($specialization_id <= 0) {
            $errors['specialization_id'] = 'التخصص مطلوب';
        }
        
        if (empty($valid_batch_ids)) {
            $errors['batches'] = 'يجب اختيار دفعة واحدة على الأقل';
        }
        
        if ($total_semesters < 1 || $total_semesters > 12) {
            $errors['total_semesters'] = 'عدد الفصول يجب أن يكون بين 1 و 12';
        }
        
        // Check if plan code exists (for new plans or if code changed in edit)
        if (empty($errors['plan_code'])) {
            $checkSql = "SELECT id FROM academic_plans WHERE plan_code = ? AND deleted_at IS NULL";
            $checkTypes = "s";
            $checkParams = [$plan_code];
            
            if ($isEdit) {
                $checkSql .= " AND id != ?";
                $checkTypes .= "i";
                $checkParams[] = $plan_id;
            }
            
            $checkStmt = $mysqli1->prepare($checkSql);
            $checkStmt->bind_param($checkTypes, ...$checkParams);
            $checkStmt->execute();
            $checkStmt->store_result();
            
            if ($checkStmt->num_rows > 0) {
                $errors['plan_code'] = 'رمز الخطة هذا موجود بالفعل';
            }
            $checkStmt->close();
        }
        
        // Validate batch dates
        foreach ($valid_batch_ids as $bid) {
            $start_date = isset($batch_start_dates[$bid]) ? validateDate($batch_start_dates[$bid]) : null;
            $end_date = isset($batch_end_dates[$bid]) ? validateDate($batch_end_dates[$bid]) : null;
            
            if ($start_date && $end_date && $start_date > $end_date) {
                $errors['batches'] = 'تاريخ البدء يجب أن يكون قبل تاريخ الانتهاء';
                break;
            }
        }
        
        // If no errors, save to database
        if (empty($errors)) {
            $mysqli1->begin_transaction();
            
            try {
                if ($isEdit) {
                    // Update existing plan
                    $stmt = $mysqli1->prepare("
                        UPDATE academic_plans SET
                            plan_name = ?,
                            plan_code = ?,
                            college_id = ?,
                            section_id = ?,
                            program_id = ?,
                            specialization_id = ?,
                            total_semesters = ?,
                            total_credit_hours = ?,
                            description = ?,
                            is_active = ?,
                            updated_at = NOW()
                        WHERE id = ?
                    ");
                    
                    $stmt->bind_param(
                        'ssiiiiidisi',
                        $plan_name,
                        $plan_code,
                        $college_id,
                        $section_id,
                        $program_id,
                        $specialization_id,
                        $total_semesters,
                        $total_credit_hours,
                        $description,
                        $is_active,
                        $plan_id
                    );
                    
                    if (!$stmt->execute()) {
                        throw new Exception("فشل في تحديث الخطة: " . $stmt->error);
                    }
                    $stmt->close();
                    
                    // Delete old batch associations
                    $deleteStmt = $mysqli1->prepare("DELETE FROM academic_plan_batches WHERE plan_id = ?");
                    $deleteStmt->bind_param('i', $plan_id);
                    $deleteStmt->execute();
                    $deleteStmt->close();
                    
                } else {
                    // Insert new plan
                    $stmt = $mysqli1->prepare("
                        INSERT INTO academic_plans (
                            plan_name, plan_code, college_id, section_id, program_id, specialization_id,
                            total_semesters, total_credit_hours, description, is_active, created_by
                        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ");
                    
                    $created_by = (int)($_SESSION['user_id'] ?? 0);
                    
                    $stmt->bind_param(
                        'ssiiiiidisi',
                        $plan_name,
                        $plan_code,
                        $college_id,
                        $section_id,
                        $program_id,
                        $specialization_id,
                        $total_semesters,
                        $total_credit_hours,
                        $description,
                        $is_active,
                        $created_by
                    );
                    
                    if (!$stmt->execute()) {
                        throw new Exception("فشل في إضافة الخطة: " . $stmt->error);
                    }
                    $plan_id = $stmt->insert_id;
                    $stmt->close();
                    
                    // Create semesters automatically
                    for ($i = 1; $i <= $total_semesters; $i++) {
                        $semester_name = "الفصل " . $i;
                        $semesterStmt = $mysqli1->prepare("
                            INSERT INTO academic_plan_semesters (plan_id, semester_number, semester_name) 
                            VALUES (?, ?, ?)
                        ");
                        $semesterStmt->bind_param('iis', $plan_id, $i, $semester_name);
                        $semesterStmt->execute();
                        $semesterStmt->close();
                    }
                }
                
                // Insert batch associations
                if (!empty($valid_batch_ids)) {
                    $insertBatchStmt = $mysqli1->prepare("
                        INSERT INTO academic_plan_batches 
                        (plan_id, batch_id, start_date, end_date, is_current)
                        VALUES (?, ?, ?, ?, ?)
                    ");
                    
                    foreach ($valid_batch_ids as $batch_id) {
                        $start_date = isset($batch_start_dates[$batch_id]) ? validateDate($batch_start_dates[$batch_id]) : null;
                        $end_date = isset($batch_end_dates[$batch_id]) ? validateDate($batch_end_dates[$batch_id]) : null;
                        $is_current = isset($batch_is_current[$batch_id]) ? 1 : 0;
                        
                        $insertBatchStmt->bind_param('iisss', $plan_id, $batch_id, $start_date, $end_date, $is_current);
                        $insertBatchStmt->execute();
                    }
                    $insertBatchStmt->close();
                }
                
                $mysqli1->commit();
                
                $_SESSION['success_message'] = $isEdit ? "تم تحديث الخطة الدراسية بنجاح" : "تم إضافة الخطة الدراسية بنجاح";
                
                if (isset($_POST['save_and_continue'])) {
                    header("Location: academic_plan_subjects.php?id=" . $plan_id);
                } else {
                    header("Location: academic_plans_list.php");
                }
                exit;
                
            } catch (Exception $e) {
                $mysqli1->rollback();
                error_log("خطأ في حفظ الخطة: " . $e->getMessage());
                $errors['general'] = "حدث خطأ في حفظ البيانات: " . $e->getMessage();
            }
        }
    }
}

include 'header.php';
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $isEdit ? 'تعديل' : 'إضافة' ?> خطة دراسية</title>
    <link rel="stylesheet" href="css/style4.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        /* RTL Specific Styles */
        body {
            font-family: 'Cairo', sans-serif;
            background-color: #f8fafc;
            min-height: 100vh;
        }
        
        .main-wrapper {
            padding: 30px 20px;
        }
        
        /* Header Styles */
        .page-header {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            border-radius: 30px;
            padding: 40px;
            margin-bottom: 30px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
            position: relative;
            overflow: hidden;
        }
        
        .page-header h1 {
            color: white;
            font-size: 2.5rem;
            font-weight: 800;
            margin: 0;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
            position: relative;
            z-index: 2;
        }
        
        .page-header p {
            color: rgba(255,255,255,0.9);
            font-size: 1.1rem;
            margin-top: 10px;
            position: relative;
            z-index: 2;
        }
        
        /* Header Buttons - بدون أي تأثيرات حركة */
        .header-buttons {
            display: flex;
            gap: 10px;
            position: relative;
            z-index: 2;
        }
        
        .btn-back {
            background: rgba(255, 255, 255, 0.15);
            border: 2px solid rgba(255, 255, 255, 0.5);
            color: white;
            padding: 12px 30px;
            border-radius: 50px;
            font-weight: 600;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            backdrop-filter: blur(5px);
        }
        
        .btn-back:hover {
            background: white;
            color: #1e3c72;
            border-color: white;
            transform: translateY(-2px);
        }
        
        .btn-back i {
            transition: transform 0.3s ease;
        }
        
        .btn-back:hover i {
            transform: translateX(-3px);
        }
        
        .btn-view {
            background: linear-gradient(135deg, #00b09b, #96c93d);
            border: none;
            color: white;
            padding: 12px 30px;
            border-radius: 50px;
            font-weight: 600;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(0, 176, 155, 0.4);
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .btn-view:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0, 176, 155, 0.6);
            color: white;
        }
        
        .btn-view i {
            transition: transform 0.3s ease;
        }
        
        .btn-view:hover i {
            transform: translateX(-3px);
        }
        
        /* Form Sections */
        .form-section {
            background: white;
            border-radius: 30px;
            padding: 30px;
            margin-bottom: 25px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
            border-right: 5px solid #667eea;
        }
        
        .form-section h5 {
            color: #2d3748;
            font-weight: 700;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 2px solid #e2e8f0;
            position: relative;
        }
        
        .form-section h5::after {
            content: '';
            position: absolute;
            bottom: -2px;
            right: 0;
            width: 100px;
            height: 2px;
            background: linear-gradient(135deg, #667eea, #764ba2);
        }
        
        .form-section h5 i {
            color: #667eea;
            margin-left: 10px;
        }
        
        /* Form Controls */
        .form-label {
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 8px;
            font-size: 0.95rem;
        }
        
        .required-field::after {
            content: " *";
            color: #e53e3e;
            font-weight: bold;
        }
        
        .form-control, .form-select {
            border: 2px solid #e2e8f0;
            border-radius: 15px;
            padding: 12px 15px;
            font-size: 0.95rem;
            transition: all 0.3s ease;
            background: white;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
            outline: none;
        }
        
        .form-control.is-invalid, .form-select.is-invalid {
            border-color: #e53e3e;
            background-image: none;
        }
        
        .error-message {
            color: #e53e3e;
            font-size: 0.85rem;
            margin-top: 5px;
            display: block;
        }
        
        .form-help {
            font-size: 0.85rem;
            color: #718096;
            margin-top: 5px;
            display: block;
        }
        
        /* Stats Cards */
        .stat-card {
            background: linear-gradient(135deg, #f5f7fa 0%, #e9edf5 100%);
            border-radius: 20px;
            padding: 25px;
            text-align: center;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
            transition: all 0.3s ease;
            border: 1px solid rgba(102, 126, 234, 0.1);
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 30px rgba(102, 126, 234, 0.2);
        }
        
        .stat-icon {
            font-size: 2rem;
            color: #667eea;
            margin-bottom: 10px;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 800;
            color: #2d3748;
            margin-bottom: 5px;
        }
        
        .stat-label {
            color: #718096;
            font-weight: 600;
            font-size: 0.9rem;
        }
        
        /* Batch Items */
        .batch-item {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-radius: 20px;
            padding: 20px;
            margin-bottom: 15px;
            border: 2px solid transparent;
            transition: all 0.3s ease;
            cursor: pointer;
        }
        
        .batch-item:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
            border-color: #667eea;
        }
        
        .batch-item.selected {
            background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
            border-color: #2196f3;
        }
        
        .batch-checkbox {
            transform: scale(1.3);
            margin-left: 15px;
        }
        
        .batch-details {
            margin-top: 15px;
            padding-top: 15px;
            border-top: 2px dashed #cbd5e0;
        }
        
        .current-badge {
            background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
            color: #1e4620;
            padding: 5px 12px;
            border-radius: 50px;
            font-size: 0.8rem;
            font-weight: 600;
        }
        
        /* Alert Styles */
        .alert {
            border-radius: 20px;
            border: none;
            padding: 20px 30px;
            font-weight: 600;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
            animation: slideIn 0.5s ease;
        }
        
        @keyframes slideIn {
            from {
                transform: translateY(-20px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }
        
        .alert-success {
            background: linear-gradient(135deg, #84fab0, #8fd3f4);
            color: #1e4620;
        }
        
        .alert-danger {
            background: linear-gradient(135deg, #fc6767, #ec008c);
            color: white;
        }
        
        .alert-info {
            background: linear-gradient(135deg, #89f7fe, #66a6ff);
            color: #1e3c72;
        }
        
        .alert-warning {
            background: linear-gradient(135deg, #f6d365, #fda085);
            color: #7f4f24;
        }
        
        /* Loading Spinner */
        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(102, 126, 234, 0.3);
            border-radius: 50%;
            border-top-color: #667eea;
            animation: spin 1s ease-in-out infinite;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        /* RTL Specific Adjustments */
        .me-1 { margin-left: 0.25rem !important; margin-right: 0 !important; }
        .me-2 { margin-left: 0.5rem !important; margin-right: 0 !important; }
        .me-3 { margin-left: 1rem !important; margin-right: 0 !important; }
        .ms-1 { margin-right: 0.25rem !important; margin-left: 0 !important; }
        .ms-2 { margin-right: 0.5rem !important; margin-left: 0 !important; }
        .ms-3 { margin-right: 1rem !important; margin-left: 0 !important; }
        
        .float-start { float: right !important; }
        .text-start { text-align: right !important; }
        .text-end { text-align: left !important; }
        
        /* Custom Scrollbar */
        ::-webkit-scrollbar {
            width: 12px;
        }
        
        ::-webkit-scrollbar-track {
            background: linear-gradient(135deg, #f5f7fa 0%, #e9edf5 100%);
        }
        
        ::-webkit-scrollbar-thumb {
            background: linear-gradient(135deg, #667eea, #764ba2);
            border-radius: 6px;
        }
        
        ::-webkit-scrollbar-thumb:hover {
            background: linear-gradient(135deg, #764ba2, #667eea);
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .page-header h1 {
                font-size: 1.8rem;
            }
            
            .header-buttons {
                flex-direction: column;
            }
            
            .form-section {
                padding: 20px;
            }
            
            .stat-card {
                padding: 15px;
            }
            
            .stat-value {
                font-size: 1.5rem;
            }
        }
    </style>
</head>
<body dir="rtl">
    <div class="main-wrapper">
        <div class="container">
            <!-- Header -->
            <div class="page-header d-flex align-items-center justify-content-between">
                <div>
                    <h1 class="mb-2">
                        <i class="fas fa-<?= $isEdit ? 'edit' : 'plus-circle' ?> ms-3"></i>
                        <?= $isEdit ? 'تعديل الخطة الدراسية' : 'إضافة خطة دراسية جديدة' ?>
                    </h1>
                    <p class="mb-0">
                        <i class="fas fa-layer-group ms-2"></i>
                        <?= $isEdit ? 'تعديل بيانات الخطة الدراسية' : 'أدخل بيانات الخطة الدراسية' ?>
                    </p>
                </div>
                <div class="header-buttons">
                    <!-- زر العودة ثابت بدون أي تأثيرات حركة -->
                    <a href="academic_plans_list.php" class="btn-back">
                        <i class="fas fa-arrow-right ms-2"></i> 
                        العودة للقائمة
                    </a>
                    
                    <?php if ($isEdit): ?>
                        <a href="academic_plan_view.php?id=<?= $plan_id ?>" class="btn-view">
                            <i class="fas fa-eye ms-2"></i>
                            عرض الخطة
                        </a>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Alerts -->
            <?php if (isset($_SESSION['success_message'])): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="fas fa-check-circle ms-2"></i>
                    <?= htmlspecialchars($_SESSION['success_message']) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php unset($_SESSION['success_message']); ?>
            <?php endif; ?>

            <?php if (!empty($errors['general'])): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-circle ms-2"></i>
                    <?= htmlspecialchars($errors['general']) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>

            <?php if (!empty($errors) && empty($errors['general'])): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-triangle ms-2"></i>
                    <strong>يرجى تصحيح الأخطاء التالية:</strong>
                    <ul class="mb-0 mt-2">
                        <?php foreach ($errors as $key => $error): ?>
                            <?php if ($key !== 'general'): ?>
                                <li><?= htmlspecialchars($error) ?></li>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </ul>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>

            <!-- Main Form -->
            <form method="POST" action="" id="planForm" novalidate>
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf_token) ?>">
                
                <div class="row">
                    <div class="col-lg-8">
                        <!-- Basic Information -->
                        <div class="form-section">
                            <h5>
                                <i class="fas fa-info-circle"></i>
                                المعلومات الأساسية
                            </h5>
                            
                            <div class="row g-4">
                                <!-- Plan Name -->
                                <div class="col-md-6">
                                    <label for="plan_name" class="form-label required-field">
                                        <i class="fas fa-heading ms-1"></i>
                                        اسم الخطة
                                    </label>
                                    <input type="text" 
                                           class="form-control <?= isset($errors['plan_name']) ? 'is-invalid' : '' ?>" 
                                           id="plan_name" 
                                           name="plan_name" 
                                           value="<?= htmlspecialchars($plan_name) ?>" 
                                           required
                                           maxlength="255"
                                           placeholder="مثل: خطة بكالوريوس علوم الحاسوب">
                                    <?php if (isset($errors['plan_name'])): ?>
                                        <span class="error-message"><?= htmlspecialchars($errors['plan_name']) ?></span>
                                    <?php endif; ?>
                                </div>
                                
                                <!-- Plan Code -->
                                <div class="col-md-6">
                                    <label for="plan_code" class="form-label required-field">
                                        <i class="fas fa-hashtag ms-1"></i>
                                        رمز الخطة
                                    </label>
                                    <input type="text" 
                                           class="form-control <?= isset($errors['plan_code']) ? 'is-invalid' : '' ?>" 
                                           id="plan_code" 
                                           name="plan_code" 
                                           value="<?= htmlspecialchars($plan_code) ?>" 
                                           required
                                           maxlength="50"
                                           placeholder="مثل: CS-BSC-2024"
                                           pattern="[A-Za-z0-9\-_]+"
                                           title="أحرف إنجليزية وأرقام وشرطة فقط"
                                           dir="ltr">
                                    <?php if (isset($errors['plan_code'])): ?>
                                        <span class="error-message"><?= htmlspecialchars($errors['plan_code']) ?></span>
                                    <?php else: ?>
                                        <span class="form-help">رمز فريد للخطة - أحرف إنجليزية وأرقام وشرطة فقط</span>
                                    <?php endif; ?>
                                </div>
                                
                                <!-- College -->
                                <div class="col-md-4">
                                    <label for="college_id" class="form-label required-field">
                                        <i class="fas fa-university ms-1"></i>
                                        الكلية
                                    </label>
                                    <select class="form-select <?= isset($errors['college_id']) ? 'is-invalid' : '' ?>" 
                                            id="college_id" 
                                            name="college_id" 
                                            required
                                            <?= (!$canAll && $scopeCollege !== null) ? 'disabled' : '' ?>
                                            onchange="loadSectionsAndPrograms()">
                                        <option value="">اختر الكلية</option>
                                        <?php foreach ($colleges as $college): ?>
                                            <option value="<?= (int)$college['id'] ?>" 
                                                <?= ($college_id == $college['id']) || (!$canAll && $scopeCollege == $college['id']) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($college['name']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <?php if (!$canAll && $scopeCollege !== null): ?>
                                        <input type="hidden" name="college_id" value="<?= (int)$scopeCollege ?>">
                                        <span class="form-help">يتم تعيين الكلية بناءً على صلاحياتك</span>
                                    <?php endif; ?>
                                    <?php if (isset($errors['college_id'])): ?>
                                        <span class="error-message"><?= htmlspecialchars($errors['college_id']) ?></span>
                                    <?php endif; ?>
                                </div>
                                
                                <!-- Section -->
                                <div class="col-md-4">
                                    <label for="section_id" class="form-label required-field">
                                        <i class="fas fa-building ms-1"></i>
                                        القسم
                                    </label>
                                    <select class="form-select <?= isset($errors['section_id']) ? 'is-invalid' : '' ?>" 
                                            id="section_id" 
                                            name="section_id" 
                                            required
                                            onchange="loadSpecializations()">
                                        <option value="">اختر الكلية أولاً</option>
                                        <?php
                                        if ($college_id) {
                                            $filteredSections = array_filter($sections, function($s) use ($college_id) {
                                                return ($s['parent'] ?? 0) == $college_id;
                                            });
                                            
                                            foreach ($filteredSections as $section) {
                                                $selected = ($section_id == $section['id']) ? 'selected' : '';
                                                echo '<option value="' . htmlspecialchars($section['id']) . '" ' . $selected . '>' . htmlspecialchars($section['name']) . '</option>';
                                            }
                                        }
                                        ?>
                                    </select>
                                    <?php if (isset($errors['section_id'])): ?>
                                        <span class="error-message"><?= htmlspecialchars($errors['section_id']) ?></span>
                                    <?php endif; ?>
                                </div>
                                
                                <!-- Program -->
                                <div class="col-md-4">
                                    <label for="program_id" class="form-label required-field">
                                        <i class="fas fa-graduation-cap ms-1"></i>
                                        البرنامج
                                    </label>
                                    <select class="form-select <?= isset($errors['program_id']) ? 'is-invalid' : '' ?>" 
                                            id="program_id" 
                                            name="program_id" 
                                            required
                                            onchange="loadSpecializations()">
                                        <option value="">اختر البرنامج</option>
                                        <?php foreach ($programs as $program): ?>
                                            <option value="<?= htmlspecialchars($program['id']) ?>" 
                                                <?= ($program_id == $program['id']) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($program['name']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <?php if (isset($errors['program_id'])): ?>
                                        <span class="error-message"><?= htmlspecialchars($errors['program_id']) ?></span>
                                    <?php endif; ?>
                                </div>
                                
                                <!-- Specialization -->
                                <div class="col-md-6">
                                    <label for="specialization_id" class="form-label required-field">
                                        <i class="fas fa-tag ms-1"></i>
                                        التخصص
                                    </label>
                                    <select class="form-select <?= isset($errors['specialization_id']) ? 'is-invalid' : '' ?>" 
                                            id="specialization_id" 
                                            name="specialization_id" 
                                            required>
                                        <option value="">اختر القسم والبرنامج أولاً</option>
                                    </select>
                                    <?php if (isset($errors['specialization_id'])): ?>
                                        <span class="error-message"><?= htmlspecialchars($errors['specialization_id']) ?></span>
                                    <?php endif; ?>
                                </div>
                                
                                <!-- Total Semesters -->
                                <div class="col-md-3">
                                    <label for="total_semesters" class="form-label required-field">
                                        <i class="fas fa-calendar-alt ms-1"></i>
                                        عدد الفصول
                                    </label>
                                    <input type="number" 
                                           class="form-control <?= isset($errors['total_semesters']) ? 'is-invalid' : '' ?>" 
                                           id="total_semesters" 
                                           name="total_semesters" 
                                           value="<?= (int)$total_semesters ?>" 
                                           min="1"
                                           max="12"
                                           step="1"
                                           required>
                                    <?php if (isset($errors['total_semesters'])): ?>
                                        <span class="error-message"><?= htmlspecialchars($errors['total_semesters']) ?></span>
                                    <?php else: ?>
                                        <span class="form-help">عدد الفصول (عادة 8 فصول)</span>
                                    <?php endif; ?>
                                </div>
                                
                                <!-- Total Credit Hours -->
                                <div class="col-md-3">
                                    <label for="total_credit_hours" class="form-label">
                                        <i class="fas fa-clock ms-1"></i>
                                        إجمالي الساعات
                                    </label>
                                    <input type="number" 
                                           class="form-control" 
                                           id="total_credit_hours" 
                                           name="total_credit_hours" 
                                           value="<?= (float)$total_credit_hours ?>" 
                                           min="0"
                                           max="200"
                                           step="0.5">
                                    <span class="form-help">يمكن تركه فارغاً ليتم حسابه تلقائياً</span>
                                </div>
                                
                                <!-- Description -->
                                <div class="col-12">
                                    <label for="description" class="form-label">
                                        <i class="fas fa-align-left ms-1"></i>
                                        وصف الخطة
                                    </label>
                                    <textarea class="form-control" 
                                              id="description" 
                                              name="description" 
                                              rows="4"
                                              maxlength="1000"
                                              placeholder="وصف مختصر للخطة الدراسية..."><?= htmlspecialchars($description) ?></textarea>
                                    <span class="form-help">يمكنك إضافة أي معلومات إضافية عن الخطة</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-lg-4">
                        <!-- Status & Actions -->
                        <div class="form-section">
                            <h5>
                                <i class="fas fa-cog"></i>
                                الحالة والإجراءات
                            </h5>
                            
                            <!-- Status -->
                            <div class="mb-4">
                                <label class="form-label d-block">
                                    <i class="fas fa-toggle-on ms-1"></i>
                                    حالة الخطة
                                </label>
                                <div class="form-check form-switch">
                                    <input class="form-check-input" 
                                           type="checkbox" 
                                           id="is_active" 
                                           name="is_active" 
                                           value="1"
                                           <?= $is_active ? 'checked' : '' ?>
                                           style="transform: scale(1.3);">
                                    <label class="form-check-label me-2" for="is_active">
                                        <span class="badge bg-<?= $is_active ? 'success' : 'secondary' ?> p-2">
                                            <i class="fas fa-<?= $is_active ? 'check-circle' : 'pause-circle' ?> ms-1"></i>
                                            <?= $is_active ? 'نشط' : 'غير نشط' ?>
                                        </span>
                                    </label>
                                </div>
                                <span class="form-help">الخطة النشطة تظهر في القوائم والاختيارات</span>
                            </div>
                            
                            <!-- Quick Info -->
                            <div class="alert alert-info mb-4">
                                <h6 class="fw-bold mb-2">
                                    <i class="fas fa-lightbulb ms-1"></i>
                                    نصائح سريعة
                                </h6>
                                <ul class="list-unstyled mb-0 small">
                                    <li class="mb-2">
                                        <i class="fas fa-check-circle text-success ms-1"></i>
                                        تأكد من اختيار التخصص الصحيح
                                    </li>
                                    <li class="mb-2">
                                        <i class="fas fa-check-circle text-success ms-1"></i>
                                        اختر الدفعات المرتبطة بالخطة
                                    </li>
                                    <li class="mb-2">
                                        <i class="fas fa-check-circle text-success ms-1"></i>
                                        بعد الحفظ يمكنك إضافة المقررات
                                    </li>
                                </ul>
                            </div>
                            
                            <!-- Save Buttons -->
                            <div class="d-grid gap-3">
                                <button type="submit" name="save" class="btn-view w-100" style="justify-content: center;">
                                    <i class="fas fa-save ms-2"></i>
                                    <?= $isEdit ? 'تحديث الخطة' : 'حفظ الخطة' ?>
                                </button>
                                
                                <?php if (!$isEdit): ?>
                                    <button type="submit" name="save_and_continue" class="btn-back w-100" style="justify-content: center; background: transparent; border: 2px solid #00b09b; color: #00b09b;">
                                        <i class="fas fa-arrow-left ms-2"></i>
                                        حفظ وإضافة المقررات
                                    </button>
                                <?php endif; ?>
                                
                                <?php if ($isEdit): ?>
                                    <a href="academic_plan_subjects.php?id=<?= (int)$plan_id ?>" class="btn-back w-100" style="justify-content: center; background: transparent; border: 2px solid #8b5cf6; color: #8b5cf6;">
                                        <i class="fas fa-book ms-2"></i>
                                        إدارة المقررات
                                    </a>
                                <?php endif; ?>
                                
                                <a href="academic_plans_list.php" class="btn-back w-100" style="justify-content: center; background: transparent; border: 2px solid #6b7280; color: #6b7280;">
                                    <i class="fas fa-times ms-2"></i>
                                    إلغاء
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Batches Selection -->
                <div class="form-section mt-4">
                    <h5>
                        <i class="fas fa-users"></i>
                        الدفعات المرتبطة بالخطة
                        <?php if (isset($errors['batches'])): ?>
                            <span class="badge bg-danger me-3">
                                <i class="fas fa-exclamation-circle ms-1"></i>
                                <?= htmlspecialchars($errors['batches']) ?>
                            </span>
                        <?php endif; ?>
                    </h5>
                    
                    <?php if (empty($batches)): ?>
                        <div class="alert alert-warning">
                            <div class="d-flex align-items-center">
                                <i class="fas fa-exclamation-triangle fa-2x me-3"></i>
                                <div>
                                    <h6 class="fw-bold mb-1">لا توجد دفعات نشطة</h6>
                                    <p class="mb-0">الرجاء إضافة دفعات أولاً من <a href="batches.php">صفحة الدفعات</a></p>
                                </div>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="row g-4">
                            <?php foreach ($batches as $batch): ?>
                                <?php 
                                $batch_id = (int)$batch['id'];
                                $isSelected = isset($selected_batches[$batch_id]);
                                $batchData = $isSelected ? $selected_batches[$batch_id] : null;
                                ?>
                                <div class="col-md-6">
                                    <div class="batch-item <?= $isSelected ? 'selected' : '' ?>" 
                                         id="batch-<?= $batch_id ?>"
                                         onclick="toggleBatch(<?= $batch_id ?>)">
                                        <div class="d-flex align-items-start">
                                            <input class="form-check-input batch-checkbox" 
                                                   type="checkbox" 
                                                   name="batch_ids[]" 
                                                   value="<?= $batch_id ?>"
                                                   id="batch_<?= $batch_id ?>"
                                                   <?= $isSelected ? 'checked' : '' ?>
                                                   onclick="event.stopPropagation()"
                                                   onchange="toggleBatchDetails(<?= $batch_id ?>)">
                                            <div class="flex-grow-1 me-3">
                                                <label class="fw-bold mb-2" for="batch_<?= $batch_id ?>">
                                                    <?= htmlspecialchars($batch['value']) ?>
                                                    <?php if ($batchData && $batchData['is_current']): ?>
                                                        <span class="current-badge ms-2">
                                                            <i class="fas fa-check-circle ms-1"></i>حالي
                                                        </span>
                                                    <?php endif; ?>
                                                </label>
                                                
                                                <div class="batch-details" id="details-<?= $batch_id ?>" style="<?= $isSelected ? 'display: block;' : 'display: none;' ?>">
                                                    <div class="row g-3">
                                                        <div class="col-md-5">
                                                            <label class="form-label small fw-bold">تاريخ البدء</label>
                                                            <input type="date" 
                                                                   class="form-control form-control-sm" 
                                                                   name="batch_start_date[<?= $batch_id ?>]"
                                                                   value="<?= $batchData ? htmlspecialchars($batchData['start_date']) : '' ?>"
                                                                   onclick="event.stopPropagation()">
                                                        </div>
                                                        <div class="col-md-5">
                                                            <label class="form-label small fw-bold">تاريخ الانتهاء</label>
                                                            <input type="date" 
                                                                   class="form-control form-control-sm" 
                                                                   name="batch_end_date[<?= $batch_id ?>]"
                                                                   value="<?= $batchData ? htmlspecialchars($batchData['end_date']) : '' ?>"
                                                                   onclick="event.stopPropagation()">
                                                        </div>
                                                        <div class="col-md-2 d-flex align-items-center">
                                                            <div class="form-check">
                                                                <input class="form-check-input" 
                                                                       type="checkbox" 
                                                                       name="batch_is_current[<?= $batch_id ?>]"
                                                                       id="current_<?= $batch_id ?>"
                                                                       <?= ($batchData && $batchData['is_current']) ? 'checked' : '' ?>
                                                                       onclick="event.stopPropagation()">
                                                                <label class="form-check-label small fw-bold" for="current_<?= $batch_id ?>">
                                                                    حالي
                                                                </label>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        
                        <div class="mt-4 text-muted small">
                            <i class="fas fa-info-circle me-1"></i>
                            اختر الدفعات التي ستدرس هذه الخطة. يمكنك تحديد تواريخ البدء والانتهاء لكل دفعة، وتحديد الدفعة الحالية.
                        </div>
                    <?php endif; ?>
                </div>
            </form>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
    // Store data
    const allSections = <?= json_encode($sections, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>;
    const allPrograms = <?= json_encode($programs, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>;
    const allSpecializations = <?= json_encode($specializations, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>;
    let currentSpecialization = <?= $specialization_id ? $specialization_id : 'null' ?>;
    
    function loadSectionsAndPrograms() {
        const collegeId = document.getElementById('college_id').value;
        const sectionSelect = document.getElementById('section_id');
        const programSelect = document.getElementById('program_id');
        const specSelect = document.getElementById('specialization_id');
        
        if (!collegeId) {
            sectionSelect.innerHTML = '<option value="">اختر الكلية أولاً</option>';
            programSelect.innerHTML = '<option value="">اختر الكلية أولاً</option>';
            specSelect.innerHTML = '<option value="">اختر القسم والبرنامج أولاً</option>';
            sectionSelect.disabled = true;
            programSelect.disabled = true;
            specSelect.disabled = true;
            return;
        }
        
        sectionSelect.disabled = false;
        programSelect.disabled = false;
        
        // Filter sections by college
        const filteredSections = allSections.filter(s => {
            const parentValue = s.parent || s.college_id || null;
            return parentValue && parseInt(parentValue) === parseInt(collegeId);
        });
        
        sectionSelect.innerHTML = '<option value="">اختر القسم</option>';
        if (filteredSections.length > 0) {
            filteredSections.forEach(section => {
                const option = document.createElement('option');
                option.value = section.id;
                option.textContent = section.name;
                <?php if ($section_id > 0): ?>
                if (section.id == <?= (int)$section_id ?>) {
                    option.selected = true;
                }
                <?php endif; ?>
                sectionSelect.appendChild(option);
            });
        } else {
            sectionSelect.innerHTML = '<option value="">لا توجد أقسام لهذه الكلية</option>';
        }
        
        programSelect.innerHTML = '<option value="">اختر البرنامج</option>';
        allPrograms.forEach(program => {
            const option = document.createElement('option');
            option.value = program.id;
            option.textContent = program.name;
            <?php if ($program_id > 0): ?>
            if (program.id == <?= (int)$program_id ?>) {
                option.selected = true;
            }
            <?php endif; ?>
            programSelect.appendChild(option);
        });
        
        if (sectionSelect.value && programSelect.value) {
            loadSpecializations();
        } else {
            specSelect.innerHTML = '<option value="">اختر القسم والبرنامج أولاً</option>';
            specSelect.disabled = true;
        }
    }
    
    function loadSpecializations() {
        const sectionId = document.getElementById('section_id').value;
        const programId = document.getElementById('program_id').value;
        const specSelect = document.getElementById('specialization_id');
        
        if (!sectionId || !programId) {
            specSelect.innerHTML = '<option value="">اختر القسم والبرنامج أولاً</option>';
            specSelect.disabled = true;
            return;
        }
        
        specSelect.disabled = false;
        
        const filteredSpecs = allSpecializations.filter(s => 
            parseInt(s.section_id) === parseInt(sectionId) && 
            parseInt(s.program_id) === parseInt(programId)
        );
        
        specSelect.innerHTML = '<option value="">اختر التخصص</option>';
        
        if (filteredSpecs.length > 0) {
            filteredSpecs.forEach(spec => {
                const option = document.createElement('option');
                option.value = spec.id;
                option.textContent = spec.name;
                <?php if ($specialization_id > 0): ?>
                if (spec.id == <?= (int)$specialization_id ?>) {
                    option.selected = true;
                }
                <?php endif; ?>
                specSelect.appendChild(option);
            });
        } else {
            specSelect.innerHTML = '<option value="">لا توجد تخصصات</option>';
        }
    }
    
    function toggleBatch(batchId) {
        const checkbox = document.getElementById('batch_' + batchId);
        checkbox.checked = !checkbox.checked;
        toggleBatchDetails(batchId);
    }
    
    function toggleBatchDetails(batchId) {
        const checkbox = document.getElementById('batch_' + batchId);
        const details = document.getElementById('details-' + batchId);
        const batchItem = document.getElementById('batch-' + batchId);
        
        if (checkbox && details && batchItem) {
            if (checkbox.checked) {
                details.style.display = 'block';
                batchItem.classList.add('selected');
            } else {
                details.style.display = 'none';
                batchItem.classList.remove('selected');
            }
        }
    }
    
    document.addEventListener('DOMContentLoaded', function() {
        const collegeSelect = document.getElementById('college_id');
        
        if (collegeSelect && collegeSelect.value) {
            loadSectionsAndPrograms();
        } else {
            const sectionSelect = document.getElementById('section_id');
            const programSelect = document.getElementById('program_id');
            const specSelect = document.getElementById('specialization_id');
            
            if (sectionSelect) sectionSelect.disabled = true;
            if (programSelect) programSelect.disabled = true;
            if (specSelect) specSelect.disabled = true;
        }
        
        <?php if ($section_id && $program_id): ?>
            loadSpecializations();
        <?php endif; ?>
        
        document.querySelectorAll('.batch-checkbox').forEach(checkbox => {
            if (checkbox.checked) {
                const batchId = checkbox.value;
                const details = document.getElementById('details-' + batchId);
                if (details) {
                    details.style.display = 'block';
                }
            }
        });
        
        const form = document.getElementById('planForm');
        if (form) {
            form.addEventListener('submit', function(e) {
                let isValid = true;
                const requiredFields = form.querySelectorAll('[required]');
                
                requiredFields.forEach(field => {
                    if (!field.value.trim() || (field.tagName === 'SELECT' && field.value === '')) {
                        field.classList.add('is-invalid');
                        isValid = false;
                    } else {
                        field.classList.remove('is-invalid');
                    }
                });
                
                const batchCheckboxes = document.querySelectorAll('.batch-checkbox:checked');
                if (batchCheckboxes.length === 0) {
                    alert('⚠️ الرجاء اختيار دفعة واحدة على الأقل');
                    isValid = false;
                }
                
                if (!isValid) {
                    e.preventDefault();
                }
            });
        }
        
        setTimeout(function() {
            document.querySelectorAll('.alert').forEach(function(alert) {
                alert.style.transition = 'opacity 0.5s';
                alert.style.opacity = '0';
                setTimeout(function() {
                    if (alert.parentNode) alert.remove();
                }, 500);
            });
        }, 5000);
    });
    </script>
</body>
</html>
<?php include 'footer.php'; ?>