<?php
// subjects_edit.php - Edit subject
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;

// Check if subject ID is provided
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    $_SESSION['error_message'] = "معرف المادة غير صحيح";
    header("Location: subjects_list.php");
    exit;
}

$subjectId = (int)$_GET['id'];

// Initialize variables
$subjectcode = $subjectnamea = $subjectnamee = '';
$subjecthours = 3;
$credit_hours = 3.00;
$program_id = $college_id = $section_id = '';
$is_active = 1;
$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);

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

// Fetch subject data
$subjectQuery = "
    SELECT 
        s.*,
        p.name as program_name,
        c.name as college_name,
        sec.name as section_name
    FROM subjects s
    LEFT JOIN programs p ON p.id = s.program_id
    LEFT JOIN colleges c ON c.id = s.college_id
    LEFT JOIN sections sec ON sec.id = s.section_id
    WHERE s.id = ? AND s.deleted_at IS NULL
";

$subjectStmt = $mysqli1->prepare($subjectQuery);
$subjectStmt->bind_param('i', $subjectId);
$subjectStmt->execute();
$subjectResult = $subjectStmt->get_result();

if ($subjectResult->num_rows === 0) {
    $_SESSION['error_message'] = "المادة الدراسية غير موجودة أو تم حذفها";
    header("Location: subjects_list.php");
    exit;
}

$subject = $subjectResult->fetch_assoc();
$subjectStmt->close();

// Check if committee has access to this subject
if (!$canAll && $scopeCollege !== null && $subject['college_id'] != $scopeCollege) {
    $_SESSION['error_message'] = "ليس لديك صلاحية لتعديل هذه المادة الدراسية";
    header("Location: subjects_list.php");
    exit;
}

// Initialize form data with existing values
$subjectcode = $subject['subjectcode'];
$subjectnamea = $subject['subjectnamea'];
$subjectnamee = $subject['subjectnamee'];
$subjecthours = $subject['subjecthours'];
$credit_hours = $subject['credit_hours'];
$program_id = $subject['program_id'];
$college_id = $subject['college_id'];
$section_id = $subject['section_id'];
$is_active = $subject['is_active'];

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get form data
    $subjectcode = trim($_POST['subjectcode'] ?? '');
    $subjectnamea = trim($_POST['subjectnamea'] ?? '');
    $subjectnamee = trim($_POST['subjectnamee'] ?? '');
    $subjecthours = isset($_POST['subjecthours']) ? (int)$_POST['subjecthours'] : 3;
    $credit_hours = isset($_POST['credit_hours']) ? floatval($_POST['credit_hours']) : 3.00;
    $program_id = isset($_POST['program_id']) ? (int)$_POST['program_id'] : 0;
    $college_id = isset($_POST['college_id']) ? (int)$_POST['college_id'] : 0;
    $section_id = isset($_POST['section_id']) ? (int)$_POST['section_id'] : 0;
    $is_active = isset($_POST['is_active']) ? (int)$_POST['is_active'] : 1;
    
    // Validation
    if (empty($subjectcode)) {
        $errors['subjectcode'] = 'رمز المادة مطلوب';
    } elseif (strlen($subjectcode) > 20) {
        $errors['subjectcode'] = 'رمز المادة يجب أن لا يتجاوز 20 حرف';
    }
    
    if (empty($subjectnamea)) {
        $errors['subjectnamea'] = 'اسم المادة بالعربية مطلوب';
    }
    
    if (empty($subjectnamee)) {
        $errors['subjectnamee'] = 'اسم المادة بالإنجليزية مطلوب';
    }
    
    if ($subjecthours <= 0) {
        $errors['subjecthours'] = 'عدد الساعات يجب أن يكون أكبر من صفر';
    }
    
    if ($credit_hours <= 0) {
        $errors['credit_hours'] = 'الساعات المعتمدة يجب أن تكون أكبر من صفر';
    }
    
    if (empty($program_id)) {
        $errors['program_id'] = 'البرنامج مطلوب';
    }
    
    if (empty($college_id)) {
        $errors['college_id'] = 'الكلية مطلوبة';
    }
    
    if (empty($section_id)) {
        $errors['section_id'] = 'القسم مطلوب';
    }
    
    // Check if subject code already exists for this program+college+section (excluding current subject)
    if (empty($errors)) {
        $checkStmt = $mysqli1->prepare("
            SELECT id FROM subjects 
            WHERE subjectcode = ? 
            AND program_id = ? 
            AND college_id = ? 
            AND section_id = ?
            AND id != ?
            AND deleted_at IS NULL
        ");
        $checkStmt->bind_param('siiii', $subjectcode, $program_id, $college_id, $section_id, $subjectId);
        $checkStmt->execute();
        $checkStmt->store_result();
        
        if ($checkStmt->num_rows > 0) {
            $errors['subjectcode'] = 'رمز المادة هذا موجود بالفعل لنفس البرنامج والكلية والقسم';
        }
        $checkStmt->close();
    }
    
    // If no errors, update database
    if (empty($errors)) {
        try {
            $updateStmt = $mysqli1->prepare("
                UPDATE subjects SET
                    subjectcode = ?,
                    program_id = ?,
                    college_id = ?,
                    section_id = ?,
                    subjecthours = ?,
                    subjectnamea = ?,
                    subjectnamee = ?,
                    credit_hours = ?,
                    is_active = ?,
                    updated_at = NOW()
                WHERE id = ?
            ");
            
            $updateStmt->bind_param(
                'siiiisdsii',
                $subjectcode,
                $program_id,
                $college_id,
                $section_id,
                $subjecthours,
                $subjectnamea,
                $subjectnamee,
                $credit_hours,
                $is_active,
                $subjectId
            );
            
            if ($updateStmt->execute()) {
                $_SESSION['success_message'] = "تم تحديث المادة الدراسية بنجاح!";
                header("Location: subjects_list.php");
                exit;
            } else {
                $_SESSION['error_message'] = "حدث خطأ أثناء تحديث البيانات: " . $updateStmt->error;
            }
            
            $updateStmt->close();
        } catch (Exception $e) {
            $_SESSION['error_message'] = "حدث خطأ: " . $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>تعديل المادة الدراسية - لوحة اللجنة</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;600;700;800&display=swap" rel="stylesheet">
    <style>
        /* Override green navbar */
        .navbar {
            background-color: white !important;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .navbar-brand {
            color: #1F3A2E !important;
        }
        
        .nav-link {
            color: #333 !important;
        }
        
        .nav-link:hover, .nav-link.active {
            color: #1F3A2E !important;
            background-color: rgba(31, 58, 46, 0.1);
        }
        
        .form-section {
            background: white;
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            border-right: 4px solid #1F3A2E;
        }
        
        .form-section h5 {
            color: #1F3A2E;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid #e5e7eb;
        }
        
        .error-message {
            color: #e74c3c;
            font-size: 0.85rem;
            margin-top: 4px;
            display: block;
        }
        
        .form-help {
            font-size: 0.85rem;
            color: #6c757d;
            margin-top: 4px;
            display: block;
        }
        
        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 6px 12px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.9rem;
        }
        
        .status-active {
            background-color: rgba(39, 174, 96, 0.1);
            color: #27ae60;
            border: 1px solid rgba(39, 174, 96, 0.3);
        }
        
        .status-inactive {
            background-color: rgba(108, 117, 125, 0.1);
            color: #6c757d;
            border: 1px solid rgba(108, 117, 125, 0.3);
        }
        
        .form-switch {
            padding-right: 2.5rem;
            padding-left: 0;
        }
        
        .form-switch .form-check-input {
            float: right;
            margin-right: -2.5rem;
            margin-left: 0;
        }
        
        .required-field::after {
            content: " *";
            color: #e74c3c;
        }
        
        .form-actions {
            background: #f8f9fa;
            border-radius: 16px;
            padding: 20px;
            margin-top: 20px;
            border-top: 2px solid #e5e7eb;
        }
        
        .preview-card {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 15px;
            margin-top: 15px;
            border: 1px dashed #e5e7eb;
        }
        
        .bg-light {
            background-color: #f8fafc !important;
        }
        
        .container-rtl {
            padding-right: 15px;
            padding-left: 15px;
            margin-right: auto;
            margin-left: auto;
        }
        
        .subject-info {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 20px;
            border-left: 4px solid #1F3A2E;
        }
        
        .info-item {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid #e5e7eb;
        }
        
        .info-item:last-child {
            border-bottom: none;
        }
        
        .info-label {
            font-weight: 600;
            color: #1F3A2E;
        }
        
        .info-value {
            color: #6c757d;
        }
    </style>
</head>
<body class="bg-light">
    <div class="container py-4">
        <!-- Header -->
        <div class="d-flex align-items-center justify-content-between mb-4">
            <div>
                <h3 class="fw-bold text-dark mb-1">
                    <i class="fas fa-edit me-2"></i>تعديل المادة الدراسية
                </h3>
                <p class="text-muted mb-0">تعديل بيانات المادة الدراسية: <strong><?= e($subject['subjectcode']) ?></strong></p>
            </div>
            <div>
                <a href="subjects_list.php" class="btn btn-outline-secondary">
                    <i class="fas fa-arrow-right me-2"></i>العودة للقائمة
                </a>
            </div>
        </div>

        <?php if (isset($_SESSION['success_message'])): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle me-2"></i>
                <?= e($_SESSION['success_message']) ?>
                <button type="button" class="btn-close float-start" data-bs-dismiss="alert"></button>
            </div>
            <?php unset($_SESSION['success_message']); ?>
        <?php endif; ?>

        <?php if (isset($_SESSION['error_message'])): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-circle me-2"></i>
                <?= e($_SESSION['error_message']) ?>
                <button type="button" class="btn-close float-start" data-bs-dismiss="alert"></button>
            </div>
            <?php unset($_SESSION['error_message']); ?>
        <?php endif; ?>

        <!-- Subject Information Card -->
        <div class="subject-info">
            <h6 class="fw-bold mb-3">معلومات المادة الحالية</h6>
            <div class="row">
                <div class="col-md-4">
                    <div class="info-item">
                        <span class="info-label">الكلية:</span>
                        <span class="info-value"><?= e($subject['college_name'] ?? 'غير محدد') ?></span>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="info-item">
                        <span class="info-label">البرنامج:</span>
                        <span class="info-value"><?= e($subject['program_name'] ?? 'غير محدد') ?></span>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="info-item">
                        <span class="info-label">القسم:</span>
                        <span class="info-value"><?= e($subject['section_name'] ?? 'غير محدد') ?></span>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="info-item">
                        <span class="info-label">تاريخ الإنشاء:</span>
                        <span class="info-value"><?= date('Y/m/d H:i', strtotime($subject['created_at'])) ?></span>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="info-item">
                        <span class="info-label">آخر تحديث:</span>
                        <span class="info-value"><?= date('Y/m/d H:i', strtotime($subject['updated_at'])) ?></span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Main Form -->
        <form method="POST" action="" id="subjectForm">
            <input type="hidden" name="subject_id" value="<?= e($subjectId) ?>">
            
            <div class="row">
                <div class="col-lg-8">
                    <!-- Basic Information -->
                    <div class="form-section">
                        <h5>
                            <i class="fas fa-info-circle me-2"></i>
                            المعلومات الأساسية
                        </h5>
                        
                        <div class="row g-3">
                            <!-- Subject Code -->
                            <div class="col-md-6">
                                <label for="subjectcode" class="form-label required-field">
                                    <i class="fas fa-hashtag me-1"></i>رمز المادة
                                </label>
                                <input type="text" 
                                       class="form-control <?= isset($errors['subjectcode']) ? 'is-invalid' : '' ?>" 
                                       id="subjectcode" 
                                       name="subjectcode" 
                                       value="<?= e($subjectcode) ?>" 
                                       required
                                       maxlength="20"
                                       placeholder="مثل: CS101">
                                <?php if (isset($errors['subjectcode'])): ?>
                                    <span class="error-message"><?= e($errors['subjectcode']) ?></span>
                                <?php else: ?>
                                    <span class="form-help">رمز فريد للمادة (حد أقصى 20 حرف)</span>
                                <?php endif; ?>
                            </div>
                            
                            <!-- Subject Hours -->
                            <div class="col-md-3">
                                <label for="subjecthours" class="form-label required-field">
                                    <i class="fas fa-clock me-1"></i>ساعات المادة
                                </label>
                                <input type="number" 
                                       class="form-control <?= isset($errors['subjecthours']) ? 'is-invalid' : '' ?>" 
                                       id="subjecthours" 
                                       name="subjecthours" 
                                       value="<?= e($subjecthours) ?>" 
                                       required
                                       min="1"
                                       max="20"
                                       step="1">
                                <?php if (isset($errors['subjecthours'])): ?>
                                    <span class="error-message"><?= e($errors['subjecthours']) ?></span>
                                <?php else: ?>
                                    <span class="form-help">عدد الساعات الأسبوعية</span>
                                <?php endif; ?>
                            </div>
                            
                            <!-- Credit Hours -->
                            <div class="col-md-3">
                                <label for="credit_hours" class="form-label required-field">
                                    <i class="fas fa-graduation-cap me-1"></i>ساعات معتمدة
                                </label>
                                <input type="number" 
                                       class="form-control <?= isset($errors['credit_hours']) ? 'is-invalid' : '' ?>" 
                                       id="credit_hours" 
                                       name="credit_hours" 
                                       value="<?= e($credit_hours) ?>" 
                                       required
                                       min="0.5"
                                       max="10"
                                       step="0.5">
                                <?php if (isset($errors['credit_hours'])): ?>
                                    <span class="error-message"><?= e($errors['credit_hours']) ?></span>
                                <?php else: ?>
                                    <span class="form-help">الساعات المعتمدة للمادة</span>
                                <?php endif; ?>
                            </div>
                            
                            <!-- Subject Name (Arabic) -->
                            <div class="col-md-12">
                                <label for="subjectnamea" class="form-label required-field">
                                    <i class="fas fa-font me-1"></i>اسم المادة (عربي)
                                </label>
                                <input type="text" 
                                       class="form-control <?= isset($errors['subjectnamea']) ? 'is-invalid' : '' ?>" 
                                       id="subjectnamea" 
                                       name="subjectnamea" 
                                       value="<?= e($subjectnamea) ?>" 
                                       required
                                       maxlength="255"
                                       placeholder="أدخل اسم المادة باللغة العربية">
                                <?php if (isset($errors['subjectnamea'])): ?>
                                    <span class="error-message"><?= e($errors['subjectnamea']) ?></span>
                                <?php else: ?>
                                    <span class="form-help">الاسم الكامل للمادة باللغة العربية</span>
                                <?php endif; ?>
                            </div>
                            
                            <!-- Subject Name (English) -->
                            <div class="col-md-12">
                                <label for="subjectnamee" class="form-label required-field">
                                    <i class="fas fa-font me-1"></i>اسم المادة (إنجليزي)
                                </label>
                                <input type="text" 
                                       class="form-control <?= isset($errors['subjectnamee']) ? 'is-invalid' : '' ?>" 
                                       id="subjectnamee" 
                                       name="subjectnamee" 
                                       value="<?= e($subjectnamee) ?>" 
                                       required
                                       maxlength="255"
                                       placeholder="Enter subject name in English"
                                       dir="ltr"
                                       style="text-align: left;">
                                <?php if (isset($errors['subjectnamee'])): ?>
                                    <span class="error-message"><?= e($errors['subjectnamee']) ?></span>
                                <?php else: ?>
                                    <span class="form-help">الاسم الكامل للمادة باللغة الإنجليزية</span>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Academic Information -->
                    <div class="form-section">
                        <h5>
                            <i class="fas fa-university me-2"></i>
                            المعلومات الأكاديمية
                        </h5>
                        
                        <div class="row g-3">
                            <!-- College -->
                            <div class="col-md-4">
                                <label for="college_id" class="form-label required-field">
                                    <i class="fas fa-building me-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="loadSections()">
                                    <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>
                            
                            <!-- Program -->
                            <div class="col-md-4">
                                <label for="program_id" class="form-label required-field">
                                    <i class="fas fa-graduation-cap me-1"></i>البرنامج
                                </label>
                                <select class="form-select <?= isset($errors['program_id']) ? 'is-invalid' : '' ?>" 
                                        id="program_id" 
                                        name="program_id" 
                                        required>
                                    <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>
                            
                            <!-- Section -->
                            <div class="col-md-4">
                                <label for="section_id" class="form-label required-field">
                                    <i class="fas fa-layer-group me-1"></i>القسم
                                </label>
                                <select class="form-select <?= isset($errors['section_id']) ? 'is-invalid' : '' ?>" 
                                        id="section_id" 
                                        name="section_id" 
                                        required>
                                    <option value="">اختر القسم</option>
                                    <?php 
                                    // Show sections for the current college
                                    if ($college_id): 
                                        foreach ($sections as $section): 
                                            if ($section['parent'] == $college_id): ?>
                                                <option value="<?= e($section['id']) ?>" 
                                                    <?= ($section_id == $section['id']) ? 'selected' : '' ?>>
                                                    <?= e($section['name']) ?>
                                                </option>
                                            <?php endif; 
                                        endforeach;
                                    endif; 
                                    ?>
                                </select>
                                <?php if (isset($errors['section_id'])): ?>
                                    <span class="error-message"><?= e($errors['section_id']) ?></span>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-lg-4">
                    <!-- Status & Actions -->
                    <div class="form-section">
                        <h5>
                            <i class="fas fa-cog me-2"></i>
                            الحالة والإجراءات
                        </h5>
                        
                        <!-- Status -->
                        <div class="mb-4">
                            <label class="form-label d-block">
                                <i class="fas fa-toggle-on me-1"></i>حالة المادة
                            </label>
                            <div class="d-flex align-items-center gap-3">
                                <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.2);">
                                    <label class="form-check-label" for="is_active">
                                        <?php if ($is_active): ?>
                                            <span class="status-badge status-active">
                                                <i class="fas fa-check-circle"></i> نشط
                                            </span>
                                        <?php else: ?>
                                            <span class="status-badge status-inactive">
                                                <i class="fas fa-pause-circle"></i> غير نشط
                                            </span>
                                        <?php endif; ?>
                                    </label>
                                </div>
                            </div>
                            <span class="form-help">المادة النشطة تظهر في القوائم والاختيارات</span>
                        </div>
                        
                        <!-- Quick Stats -->
                        <div class="preview-card">
                            <h6 class="fw-semibold mb-3">معلومات سريعة</h6>
                            <div class="row g-2">
                                <div class="col-6">
                                    <div class="text-muted small">رمز المادة:</div>
                                    <div class="fw-bold" id="previewCode"><?= e($subjectcode) ?></div>
                                </div>
                                <div class="col-6">
                                    <div class="text-muted small">الساعات:</div>
                                    <div class="fw-bold" id="previewHours"><?= e($subjecthours) ?> ساعة</div>
                                </div>
                                <div class="col-12 mt-2">
                                    <div class="text-muted small">الاسم:</div>
                                    <div class="fw-bold text-truncate" id="previewName"><?= e($subjectnamea) ?></div>
                                </div>
                                <div class="col-12 mt-2">
                                    <div class="text-muted small">الحالة:</div>
                                    <div class="fw-bold">
                                        <span class="<?= $is_active ? 'status-active' : 'status-inactive' ?>">
                                            <?= $is_active ? 'نشط' : 'غير نشط' ?>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Save Buttons -->
                        <div class="form-actions">
                            <div class="d-grid gap-2">
                                <button type="submit" name="save" class="btn btn-primary btn-lg">
                                    <i class="fas fa-save me-2"></i>حفظ التعديلات
                                </button>
                                <button type="submit" name="save_and_new" class="btn btn-outline-primary">
                                    <i class="fas fa-sync-alt me-2"></i>حفظ وتحديث
                                </button>
                                <a href="subjects_list.php" class="btn btn-outline-secondary">
                                    <i class="fas fa-times me-2"></i>إلغاء
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </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 sections data
    let allSections = <?= json_encode($sections) ?>;
    
    // Load sections based on selected college
    function loadSections() {
        const collegeId = document.getElementById('college_id').value;
        const sectionSelect = document.getElementById('section_id');
        
        // Clear options
        sectionSelect.innerHTML = '<option value="">اختر القسم</option>';
        
        if (!collegeId) {
            // Disable section select if no college selected
            sectionSelect.disabled = true;
            return;
        }
        
        // Enable section select
        sectionSelect.disabled = false;
        
        // Filter sections by college (parent field)
        const filteredSections = allSections.filter(section => {
            // Check if section.parent equals the selected college ID
            // Convert both to numbers for comparison
            return parseInt(section.parent) === parseInt(collegeId);
        });
        
        // Populate sections
        if (filteredSections.length > 0) {
            filteredSections.forEach(section => {
                const option = document.createElement('option');
                option.value = section.id;
                option.textContent = section.name;
                sectionSelect.appendChild(option);
            });
            
            // If there's a previously selected section that exists in filtered sections, select it
            const previousSectionId = <?= json_encode($section_id) ?>;
            if (previousSectionId && filteredSections.some(s => s.id == previousSectionId)) {
                sectionSelect.value = previousSectionId;
            }
        } else {
            const option = document.createElement('option');
            option.value = '';
            option.textContent = 'لا توجد أقسام لهذه الكلية';
            sectionSelect.appendChild(option);
        }
        
        // Update preview
        updatePreview();
    }
    
    // Update preview
    function updatePreview() {
        document.getElementById('previewCode').textContent = 
            document.getElementById('subjectcode').value || '<?= e($subjectcode) ?>';
        document.getElementById('previewHours').textContent = 
            document.getElementById('subjecthours').value + ' ساعة';
        document.getElementById('previewName').textContent = 
            document.getElementById('subjectnamea').value || '<?= e($subjectnamea) ?>';
        
        // Update status badge
        const isActive = document.getElementById('is_active').checked;
        const statusElement = document.querySelector('.preview-card .fw-bold span');
        if (isActive) {
            statusElement.className = 'status-badge status-active';
            statusElement.innerHTML = '<i class="fas fa-check-circle"></i> نشط';
        } else {
            statusElement.className = 'status-badge status-inactive';
            statusElement.innerHTML = '<i class="fas fa-pause-circle"></i> غير نشط';
        }
    }
    
    // Check if subject code exists (excluding current subject)
    function checkSubjectCodeExists() {
        const subjectcode = document.getElementById('subjectcode').value;
        const programId = document.getElementById('program_id').value;
        const collegeId = document.getElementById('college_id').value;
        const sectionId = document.getElementById('section_id').value;
        const subjectId = <?= e($subjectId) ?>;
        
        if (subjectcode && programId && collegeId && sectionId) {
            $.ajax({
                url: 'check_subject_code.php',
                type: 'POST',
                data: {
                    subjectcode: subjectcode,
                    program_id: programId,
                    college_id: collegeId,
                    section_id: sectionId,
                    exclude_id: subjectId
                },
                dataType: 'json',
                success: function(response) {
                    if (response.exists) {
                        alert('رمز المادة هذا موجود بالفعل لنفس البرنامج والكلية والقسم');
                        document.getElementById('subjectcode').focus();
                        document.getElementById('subjectcode').classList.add('is-invalid');
                    } else {
                        document.getElementById('subjectcode').classList.remove('is-invalid');
                        document.getElementById('subjectcode').classList.add('is-valid');
                    }
                },
                error: function() {
                    console.log('Error checking subject code');
                }
            });
        }
    }
    
    // Toggle status badge
    document.getElementById('is_active').addEventListener('change', function() {
        const label = this.nextElementSibling;
        if (this.checked) {
            label.innerHTML = '<span class="status-badge status-active"><i class="fas fa-check-circle"></i> نشط</span>';
        } else {
            label.innerHTML = '<span class="status-badge status-inactive"><i class="fas fa-pause-circle"></i> غير نشط</span>';
        }
        updatePreview();
    });
    
    // Initialize when page loads
    document.addEventListener('DOMContentLoaded', function() {
        // If college is selected, enable section select
        const collegeSelect = document.getElementById('college_id');
        const sectionSelect = document.getElementById('section_id');
        const initialCollegeId = collegeSelect.value;
        
        if (initialCollegeId) {
            sectionSelect.disabled = false;
        } else {
            sectionSelect.disabled = true;
        }
        
        // Set up preview updates
        document.getElementById('subjectcode').addEventListener('input', updatePreview);
        document.getElementById('subjectnamea').addEventListener('input', updatePreview);
        document.getElementById('subjecthours').addEventListener('input', updatePreview);
        
        // Check subject code when losing focus
        document.getElementById('subjectcode').addEventListener('blur', function() {
            if (this.value.trim()) {
                checkSubjectCodeExists();
                updatePreview();
            }
        });
        
        // Form validation
        const form = document.getElementById('subjectForm');
        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');
                }
            });
            
            if (!isValid) {
                e.preventDefault();
                alert('الرجاء ملء جميع الحقول المطلوبة');
            }
        });
        
        // Initial preview update
        updatePreview();
    });
    </script>
</body>
</html>