<?php
// academic_plan_edit.php - نسخة محسنة مع RTL وتصميم أفضل وإضافة التخصصات
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
require 'helpers.php';
require_committee();

$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;

$plan_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$plan_id) {
    $_SESSION['error_message'] = "معرف الخطة غير موجود";
    header("Location: academic_plans_list.php");
    exit;
}

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

// Get filter data for dropdowns
$colleges = $mysqli1->query("SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name")->fetch_all(MYSQLI_ASSOC);
$programs = $mysqli1->query("SELECT id, name FROM programs WHERE deleted_at IS NULL ORDER BY name")->fetch_all(MYSQLI_ASSOC);
$sections = $mysqli1->query("SELECT id, name, parent FROM sections WHERE deleted_at IS NULL ORDER BY name")->fetch_all(MYSQLI_ASSOC);

// Get active batches
$batches = $mysqli1->query("SELECT id, value FROM batches WHERE deleted_at IS NULL AND status = 1 ORDER BY value DESC")->fetch_all(MYSQLI_ASSOC);

// Fetch plan data
$stmt = $mysqli1->prepare("
    SELECT * FROM academic_plans 
    WHERE id = ? AND deleted_at IS NULL
");
$stmt->bind_param('i', $plan_id);
$stmt->execute();
$plan = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$plan) {
    $_SESSION['error_message'] = "الخطة الدراسية غير موجودة";
    header("Location: academic_plans_list.php");
    exit;
}

// Check permissions
if (!$canAll && $scopeCollege !== null && $plan['college_id'] != $scopeCollege) {
    $_SESSION['error_message'] = "ليس لديك صلاحية لتعديل هذه الخطة";
    header("Location: academic_plans_list.php");
    exit;
}

// Set form values from database
$plan_name = $plan['plan_name'];
$plan_code = $plan['plan_code'];
$college_id = $plan['college_id'];
$section_id = $plan['section_id'];
$program_id = $plan['program_id'];
$specialization_id = $plan['specialization_id'] ?? 0;
$total_semesters = $plan['total_semesters'] ?? 8;
$total_credit_hours = $plan['total_credit_hours'] ?? 0;
$description = $plan['description'] ?? '';
$is_active = $plan['is_active'];

// Get specialization name if exists
$specialization_name = '';
if ($specialization_id) {
    $specStmt = $mysqli1->prepare("SELECT specialization_name_ar FROM specializations WHERE specialization_id = ? AND deleted_at IS NULL");
    $specStmt->bind_param('i', $specialization_id);
    $specStmt->execute();
    $specResult = $specStmt->get_result();
    if ($specRow = $specResult->fetch_assoc()) {
        $specialization_name = $specRow['specialization_name_ar'];
    }
    $specStmt->close();
}

// 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[$row['batch_id']] = [
        'start_date' => $row['start_date'],
        'end_date' => $row['end_date'],
        'is_current' => $row['is_current']
    ];
}
$batchStmt->close();

// If committee has restricted access, filter colleges
if (!$canAll && $scopeCollege !== null) {
    $colleges = array_filter($colleges, function($college) use ($scopeCollege) {
        return $college['id'] == $scopeCollege;
    });
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get form data
    $plan_name = trim($_POST['plan_name'] ?? '');
    $plan_code = trim($_POST['plan_code'] ?? '');
    $college_id = isset($_POST['college_id']) ? (int)$_POST['college_id'] : 0;
    $section_id = isset($_POST['section_id']) ? (int)$_POST['section_id'] : 0;
    $program_id = isset($_POST['program_id']) ? (int)$_POST['program_id'] : 0;
    $specialization_id = isset($_POST['specialization_id']) ? (int)$_POST['specialization_id'] : 0;
    $total_semesters = isset($_POST['total_semesters']) ? (int)$_POST['total_semesters'] : 8;
    $total_credit_hours = isset($_POST['total_credit_hours']) ? (float)$_POST['total_credit_hours'] : 0;
    $description = trim($_POST['description'] ?? '');
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    
    // Get selected batches
    $batch_ids = $_POST['batch_ids'] ?? [];
    $batch_start_dates = $_POST['batch_start_date'] ?? [];
    $batch_end_dates = $_POST['batch_end_date'] ?? [];
    $batch_is_current = $_POST['batch_is_current'] ?? [];
    
    // Validation
    if (empty($plan_name)) {
        $errors['plan_name'] = 'اسم الخطة مطلوب';
    }
    
    if (empty($plan_code)) {
        $errors['plan_code'] = 'رمز الخطة مطلوب';
    }
    
    if (empty($college_id)) {
        $errors['college_id'] = 'الكلية مطلوبة';
    }
    
    if (empty($section_id)) {
        $errors['section_id'] = 'القسم مطلوب';
    }
    
    if (empty($program_id)) {
        $errors['program_id'] = 'البرنامج مطلوب';
    }
    
    if (empty($batch_ids)) {
        $errors['batches'] = 'يجب اختيار دفعة واحدة على الأقل';
    }
    
    // Check if plan code exists (excluding current plan)
    if (empty($errors['plan_code'])) {
        $checkStmt = $mysqli1->prepare("
            SELECT id FROM academic_plans 
            WHERE plan_code = ? AND deleted_at IS NULL AND id != ?
        ");
        $checkStmt->bind_param('si', $plan_code, $plan_id);
        $checkStmt->execute();
        $checkStmt->store_result();
        
        if ($checkStmt->num_rows > 0) {
            $errors['plan_code'] = 'رمز الخطة هذا موجود بالفعل';
        }
        $checkStmt->close();
    }
    
    // If no errors, update database
    if (empty($errors)) {
        $mysqli1->begin_transaction();
        
        try {
            // Update plan
            $updateStmt = $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 = ?
                WHERE id = ?
            ");
            
            $updateStmt->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
            );
            $updateStmt->execute();
            $updateStmt->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();
            
            // Insert new batch associations
            if (!empty($batch_ids)) {
                $insertBatchStmt = $mysqli1->prepare("
                    INSERT INTO academic_plan_batches 
                    (plan_id, batch_id, start_date, end_date, is_current)
                    VALUES (?, ?, ?, ?, ?)
                ");
                
                foreach ($batch_ids as $batch_id) {
                    $start_date = !empty($batch_start_dates[$batch_id]) ? $batch_start_dates[$batch_id] : null;
                    $end_date = !empty($batch_end_dates[$batch_id]) ? $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'] = "تم تحديث الخطة الدراسية بنجاح";
            
            // Check if user wants to continue to subjects management
            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();
            $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>تعديل الخطة الدراسية - <?= e($plan_name) ?></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-edit ms-3"></i>
                        تعديل الخطة الدراسية
                    </h1>
                    <p class="mb-0">
                        <i class="fas fa-layer-group ms-2"></i>
                        تعديل بيانات الخطة: <?= e($plan_name) ?>
                    </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>
                    
                    <!-- زر عرض الخطة -->
                    <a href="academic_plan_view.php?id=<?= $plan_id ?>" class="btn-view">
                        <i class="fas fa-eye ms-2"></i>
                        عرض الخطة
                    </a>
                </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>
                    <?= e($_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 (isset($errors['general'])): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-circle ms-2"></i>
                    <?= e($errors['general']) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>

            <!-- Plan Statistics -->
            <?php
            // Get plan statistics
            $statsStmt = $mysqli1->prepare("
                SELECT 
                    COUNT(*) as total_subjects,
                    SUM(CASE WHEN is_core = 1 THEN 1 ELSE 0 END) as core_subjects,
                    SUM(credit_hours) as total_hours,
                    COUNT(DISTINCT semester_id) as semesters_used
                FROM academic_plan_subjects 
                WHERE plan_id = ?
            ");
            $statsStmt->bind_param('i', $plan_id);
            $statsStmt->execute();
            $stats = $statsStmt->get_result()->fetch_assoc();
            $statsStmt->close();
            
            // Get batch statistics
            $batchStatsStmt = $mysqli1->prepare("
                SELECT COUNT(*) as total_batches
                FROM academic_plan_batches 
                WHERE plan_id = ?
            ");
            $batchStatsStmt->bind_param('i', $plan_id);
            $batchStatsStmt->execute();
            $batchStats = $batchStatsStmt->get_result()->fetch_assoc();
            $batchStatsStmt->close();
            ?>
            
            <div class="row g-4 mb-4">
                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-book"></i>
                        </div>
                        <div class="stat-value"><?= number_format($stats['total_subjects'] ?? 0) ?></div>
                        <div class="stat-label">إجمالي المقررات</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-star"></i>
                        </div>
                        <div class="stat-value"><?= number_format($stats['core_subjects'] ?? 0) ?></div>
                        <div class="stat-label">المقررات الأساسية</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-clock"></i>
                        </div>
                        <div class="stat-value"><?= number_format($stats['total_hours'] ?? 0, 2) ?></div>
                        <div class="stat-label">الساعات المعتمدة</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-users"></i>
                        </div>
                        <div class="stat-value"><?= number_format($batchStats['total_batches'] ?? 0) ?></div>
                        <div class="stat-label">الدفعات المرتبطة</div>
                    </div>
                </div>
            </div>

            <!-- Main Form -->
            <form method="POST" action="" id="planForm">
                <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="<?= e($plan_name) ?>" 
                                           required
                                           maxlength="255"
                                           placeholder="مثل: خطة بكالوريوس علوم الحاسوب">
                                    <?php if (isset($errors['plan_name'])): ?>
                                        <span class="error-message"><?= e($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="<?= e($plan_code) ?>" 
                                           required
                                           maxlength="50"
                                           placeholder="مثل: CS-BSC-2024">
                                    <?php if (isset($errors['plan_code'])): ?>
                                        <span class="error-message"><?= e($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="<?= e($college['id']) ?>" 
                                                <?= ($college_id == $college['id']) || (!$canAll && $scopeCollege == $college['id']) ? 'selected' : '' ?>>
                                                <?= e($college['name']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <?php if (!$canAll && $scopeCollege !== null): ?>
                                        <input type="hidden" name="college_id" value="<?= $scopeCollege ?>">
                                        <span class="form-help">يتم تعيين الكلية بناءً على صلاحياتك</span>
                                    <?php endif; ?>
                                    <?php if (isset($errors['college_id'])): ?>
                                        <span class="error-message"><?= e($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-layer-group 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="' . e($section['id']) . '" ' . $selected . '>' . e($section['name']) . '</option>';
                                            }
                                        }
                                        ?>
                                    </select>
                                    <?php if (isset($errors['section_id'])): ?>
                                        <span class="error-message"><?= e($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="<?= e($program['id']) ?>" 
                                                <?= ($program_id == $program['id']) ? 'selected' : '' ?>>
                                                <?= e($program['name']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <?php if (isset($errors['program_id'])): ?>
                                        <span class="error-message"><?= e($errors['program_id']) ?></span>
                                    <?php endif; ?>
                                </div>
                                
                                <!-- Specialization -->
                                <div class="col-md-6">
                                    <label for="specialization_id" class="form-label">
                                        <i class="fas fa-tag ms-1"></i>
                                        التخصص
                                    </label>
                                    <select class="form-select" id="specialization_id" name="specialization_id">
                                        <option value="">اختر القسم والبرنامج أولاً</option>
                                        <?php if ($specialization_id && $specialization_name): ?>
                                            <option value="<?= $specialization_id ?>" selected>
                                                <?= e($specialization_name) ?>
                                            </option>
                                        <?php endif; ?>
                                    </select>
                                    <span class="form-help" id="specializationStatus"></span>
                                </div>
                                
                                <!-- Total Semesters -->
                                <div class="col-md-3">
                                    <label for="total_semesters" class="form-label">
                                        <i class="fas fa-calendar-alt ms-1"></i>
                                        عدد الفصول
                                    </label>
                                    <input type="number" 
                                           class="form-control" 
                                           id="total_semesters" 
                                           name="total_semesters" 
                                           value="<?= e($total_semesters) ?>" 
                                           min="1"
                                           max="12"
                                           step="1">
                                    <span class="form-help">عادة 8 فصول</span>
                                </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="<?= e($total_credit_hours) ?>" 
                                           min="0"
                                           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"
                                              placeholder="وصف مختصر للخطة الدراسية..."><?= e($description) ?></textarea>
                                </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-info-circle ms-1"></i>
                                    معلومات سريعة
                                </h6>
                                <p class="small mb-1">
                                    <i class="fas fa-calendar-plus text-primary ms-1"></i>
                                    تاريخ الإضافة: <?= date('Y-m-d', strtotime($plan['created_at'])) ?>
                                </p>
                                <p class="small mb-0">
                                    <i class="fas fa-clock text-warning ms-1"></i>
                                    آخر تحديث: <?= date('Y-m-d', strtotime($plan['updated_at'])) ?>
                                </p>
                            </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>
                                    تحديث الخطة
                                </button>
                                
                                <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>
                                
                                <a href="academic_plan_subjects.php?id=<?= $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>
                                
                                <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>
                        
                        <!-- Warning if subjects exist -->
                        <?php if (($stats['total_subjects'] ?? 0) > 0): ?>
                        <div class="alert alert-warning mt-3">
                            <i class="fas fa-exclamation-triangle ms-2"></i>
                            <strong>تنبيه:</strong> تغيير الكلية أو القسم أو البرنامج قد يؤثر على المقررات المرتبطة بالخطة.
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <!-- Batches Selection Section -->
                <div class="form-section mt-4">
                    <h5>
                        <i class="fas fa-users"></i>
                        الدفعات المرتبطة بالخطة
                        <?php if (isset($errors['batches'])): ?>
                            <span class="error-message me-3"><?= e($errors['batches']) ?></span>
                        <?php endif; ?>
                    </h5>
                    
                    <div class="row g-4">
                        <?php if (empty($batches)): ?>
                            <div class="col-12">
                                <div class="alert alert-warning">
                                    <i class="fas fa-exclamation-triangle ms-2"></i>
                                    لا توجد دفعات نشطة. الرجاء إضافة دفعات أولاً.
                                    <a href="batch_add.php" class="btn btn-warning btn-sm ms-3">
                                        <i class="fas fa-plus ms-1"></i>إضافة دفعة
                                    </a>
                                </div>
                            </div>
                        <?php else: ?>
                            <?php foreach ($batches as $batch): ?>
                                <?php 
                                $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'] ?>">
                                                    <?= e($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 ? e($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 ? e($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; ?>
                        <?php endif; ?>
                    </div>
                    
                    <div class="mt-4 text-muted small">
                        <i class="fas fa-info-circle ms-1"></i>
                        اختر الدفعات التي ستدرس هذه الخطة. يمكنك تحديد تواريخ البدء والانتهاء لكل دفعة، وتحديد الدفعة الحالية.
                    </div>
                </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
    let allSections = <?= json_encode($sections) ?>;
    let allPrograms = <?= json_encode($programs) ?>;
    let currentSpecialization = <?= $specialization_id ? $specialization_id : 'null' ?>;
    
    // Load sections based on college
    function loadSectionsAndPrograms() {
        const collegeId = document.getElementById('college_id').value;
        const sectionSelect = document.getElementById('section_id');
        
        if (!collegeId) {
            sectionSelect.innerHTML = '<option value="">اختر الكلية أولاً</option>';
            sectionSelect.disabled = true;
            return;
        }
        
        sectionSelect.disabled = false;
        
        // Filter sections by college
        const filteredSections = allSections.filter(s => {
            return (s.parent || s.college_id) == 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;
                if (section.id == <?= $section_id ?>) {
                    option.selected = true;
                }
                sectionSelect.appendChild(option);
            });
        } else {
            sectionSelect.innerHTML = '<option value="">لا توجد أقسام</option>';
        }
        
        // Load specializations after sections change
        loadSpecializations();
    }
    
    // Load specializations based on section and program
    function loadSpecializations() {
        const sectionId = document.getElementById('section_id').value;
        const programId = document.getElementById('program_id').value;
        const specSelect = document.getElementById('specialization_id');
        const specStatus = document.getElementById('specializationStatus');
        
        if (sectionId && programId && sectionId !== '' && programId !== '') {
            specSelect.disabled = true;
            specStatus.innerHTML = '<span class="loading-spinner"></span> جاري تحميل التخصصات...';
            
            fetch(`ajax/get_specializations.php?section_id=${sectionId}&program_id=${programId}`)
                .then(response => response.json())
                .then(specializations => {
                    let options = '<option value="">اختر التخصص (اختياري)</option>';
                    
                    if (specializations.length > 0) {
                        specializations.forEach(spec => {
                            const selected = (currentSpecialization == spec.specialization_id) ? 'selected' : '';
                            options += `<option value="${spec.specialization_id}" ${selected}>${spec.specialization_name_ar}</option>`;
                        });
                        specStatus.innerHTML = '<span class="text-success"><i class="fas fa-check-circle ms-1"></i> ' + specializations.length + ' تخصص</span>';
                    } else {
                        options = '<option value="">لا توجد تخصصات</option>';
                        specStatus.innerHTML = '<span class="text-muted"><i class="fas fa-info-circle ms-1"></i> لا توجد تخصصات</span>';
                    }
                    
                    specSelect.innerHTML = options;
                    specSelect.disabled = false;
                })
                .catch(error => {
                    console.error('Error:', error);
                    specSelect.innerHTML = '<option value="">خطأ في التحميل</option>';
                    specSelect.disabled = false;
                    specStatus.innerHTML = '<span class="text-danger"><i class="fas fa-exclamation-circle ms-1"></i> خطأ في التحميل</span>';
                });
        } else {
            specSelect.innerHTML = '<option value="">اختر القسم والبرنامج أولاً</option>';
            specSelect.disabled = true;
            specStatus.innerHTML = '<span class="text-muted"><i class="fas fa-info-circle ms-1"></i> يجب اختيار القسم والبرنامج</span>';
        }
    }
    
    // Toggle batch selection
    function toggleBatch(batchId) {
        const checkbox = document.getElementById('batch_' + batchId);
        checkbox.checked = !checkbox.checked;
        toggleBatchDetails(batchId);
    }
    
    // Toggle batch details visibility
    function toggleBatchDetails(batchId) {
        const checkbox = document.getElementById('batch_' + batchId);
        const details = document.getElementById('details-' + batchId);
        const batchItem = document.getElementById('batch-' + batchId);
        
        if (checkbox.checked) {
            details.style.display = 'block';
            batchItem.classList.add('selected');
        } else {
            details.style.display = 'none';
            batchItem.classList.remove('selected');
        }
    }
    
    // Initialize on page load
    document.addEventListener('DOMContentLoaded', function() {
        const collegeSelect = document.getElementById('college_id');
        
        // If college is selected, load sections and programs
        if (collegeSelect.value) {
            loadSectionsAndPrograms();
        }
        
        // Load specializations if both section and program are selected
        <?php if ($section_id && $program_id): ?>
            loadSpecializations();
        <?php endif; ?>
        
        // Initialize batch details visibility
        document.querySelectorAll('.batch-checkbox').forEach(checkbox => {
            if (checkbox.checked) {
                const batchId = checkbox.value;
                document.getElementById('details-' + batchId).style.display = 'block';
            }
        });
        
        // Form validation
        const form = document.getElementById('planForm');
        form.addEventListener('submit', function(e) {
            let isValid = true;
            
            // Check required fields
            const requiredFields = ['plan_name', 'plan_code', 'college_id', 'section_id', 'program_id'];
            requiredFields.forEach(fieldId => {
                const field = document.getElementById(fieldId);
                if (!field || !field.value) {
                    if (field) field.classList.add('is-invalid');
                    isValid = false;
                } else {
                    if (field) field.classList.remove('is-invalid');
                }
            });
            
            // Check if at least one batch is selected
            const batchCheckboxes = document.querySelectorAll('.batch-checkbox:checked');
            if (batchCheckboxes.length === 0) {
                alert('⚠️ يجب اختيار دفعة واحدة على الأقل للخطة');
                isValid = false;
            }
            
            if (!isValid) {
                e.preventDefault();
            }
        });
        
        // Auto-hide alerts
        setTimeout(function() {
            $('.alert').fadeOut(500, function() {
                $(this).remove();
            });
        }, 5000);
        
        // Warn before changing critical fields if subjects exist
        const hasSubjects = <?= ($stats['total_subjects'] ?? 0) > 0 ? 'true' : 'false' ?>;
        
        if (hasSubjects) {
            const warningFields = ['college_id', 'section_id', 'program_id'];
            warningFields.forEach(fieldId => {
                const field = document.getElementById(fieldId);
                if (field) {
                    field.addEventListener('change', function(e) {
                        if (!confirm('⚠️ تحذير: تغيير هذا الحقل قد يؤثر على المقررات المرتبطة بالخطة. هل أنت متأكد؟')) {
                            e.preventDefault();
                            this.value = this.getAttribute('data-previous') || this.value;
                            if (fieldId === 'college_id') {
                                loadSectionsAndPrograms();
                            }
                        } else {
                            this.setAttribute('data-previous', this.value);
                        }
                    });
                    
                    // Store initial value
                    field.setAttribute('data-previous', field.value);
                }
            });
        }
        
        // Add loading state to form submission
        form.addEventListener('submit', function() {
            const submitButtons = form.querySelectorAll('button[type="submit"]');
            submitButtons.forEach(button => {
                button.disabled = true;
                button.innerHTML = '<span class="loading-spinner"></span> جاري الحفظ...';
            });
        });
    });
    </script>
</body>
</html>
<?php include 'footer.php'; ?>