<?php
// academic_plan_add.php
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;
$isEdit = $plan_id > 0;

// Initialize variables
$plan_name = $plan_code = $description = '';
$college_id = $section_id = $program_id = 0;
$total_semesters = 8;
$is_active = 1;
$errors = [];

// Get filter data
$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 edit, fetch plan data
if ($isEdit) {
    $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;
    }
    
    $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'];
    $total_semesters = $plan['total_semesters'];
    $description = $plan['description'];
    $is_active = $plan['is_active'];
}

// 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;
    $total_semesters = isset($_POST['total_semesters']) ? (int)$_POST['total_semesters'] : 8;
    $description = trim($_POST['description'] ?? '');
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    
    // 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'] = 'البرنامج مطلوب';
    }
    
    // Check if plan code exists (for new plans or if code changed in edit)
    if (empty($errors['plan_code'])) {
        $checkStmt = $mysqli1->prepare("
            SELECT id FROM academic_plans 
            WHERE plan_code = ? AND deleted_at IS NULL
            " . ($isEdit ? " AND id != ?" : "")
        );
        
        if ($isEdit) {
            $checkStmt->bind_param('si', $plan_code, $plan_id);
        } else {
            $checkStmt->bind_param('s', $plan_code);
        }
        
        $checkStmt->execute();
        $checkStmt->store_result();
        
        if ($checkStmt->num_rows > 0) {
            $errors['plan_code'] = 'رمز الخطة هذا موجود بالفعل';
        }
        $checkStmt->close();
    }
    
    // If no errors, save to database
    if (empty($errors)) {
        if ($isEdit) {
            // Update existing plan
            $stmt = $mysqli1->prepare("
                UPDATE academic_plans SET
                    plan_name = ?,
                    plan_code = ?,
                    college_id = ?,
                    section_id = ?,
                    program_id = ?,
                    total_semesters = ?,
                    description = ?,
                    is_active = ?
                WHERE id = ?
            ");
            
            $stmt->bind_param(
                'ssiiiiisi',
                $plan_name,
                $plan_code,
                $college_id,
                $section_id,
                $program_id,
                $total_semesters,
                $description,
                $is_active,
                $plan_id
            );
            
            if ($stmt->execute()) {
                $_SESSION['success_message'] = "تم تحديث الخطة الدراسية بنجاح";
                header("Location: academic_plan_edit.php?id=$plan_id");
                exit;
            } else {
                $errors[] = "حدث خطأ أثناء التحديث: " . $stmt->error;
            }
            
            $stmt->close();
        } else {
            // Insert new plan
            $stmt = $mysqli1->prepare("
                INSERT INTO academic_plans (
                    plan_name, plan_code, college_id, section_id, program_id,
                    total_semesters, description, is_active
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ");
            
            $stmt->bind_param(
                'ssiiiiis',
                $plan_name,
                $plan_code,
                $college_id,
                $section_id,
                $program_id,
                $total_semesters,
                $description,
                $is_active
            );
            
            if ($stmt->execute()) {
                $new_plan_id = $stmt->insert_id;
                $_SESSION['success_message'] = "تم إضافة الخطة الدراسية بنجاح";
                
                if (isset($_POST['save_and_continue'])) {
                    header("Location: academic_plan_subjects.php?id=$new_plan_id");
                } else {
                    header("Location: academic_plans_list.php");
                }
                exit;
            } else {
                $errors[] = "حدث خطأ أثناء الحفظ: " . $stmt->error;
            }
            
            $stmt->close();
        }
    }
}

include 'header.php';
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $isEdit ? 'تعديل' : 'إضافة' ?> خطة دراسية</title>
    <link rel="stylesheet" href="css/style4.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&display=swap" rel="stylesheet">
    <style>
        .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: 24px;
            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: 20px;
            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;
        }
        
        .required-field::after {
            content: " *";
            color: #e74c3c;
        }
        
        .bg-light {
            background-color: #f8fafc !important;
        }
        
        .info-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 16px;
            padding: 24px;
            margin-bottom: 20px;
        }
    </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-layer-group me-2"></i>
                    <?= $isEdit ? 'تعديل الخطة الدراسية' : 'إضافة خطة دراسية جديدة' ?>
                </h3>
                <p class="text-muted mb-0">
                    <?= $isEdit ? 'تعديل بيانات الخطة الدراسية' : 'أدخل بيانات الخطة الدراسية الجديدة' ?>
                </p>
            </div>
            <div>
                <a href="academic_plans_list.php" class="btn btn-outline-secondary">
                    <i class="fas fa-arrow-right me-2"></i>العودة للقائمة
                </a>
            </div>
        </div>

        <?php if (!empty($errors) && !isset($errors['plan_name']) && !isset($errors['plan_code'])): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-circle me-2"></i>
                <?php foreach ($errors as $error): ?>
                    <div><?= e($error) ?></div>
                <?php endforeach; ?>
                <button type="button" class="btn-close float-start" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- 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 me-2"></i>
                            المعلومات الأساسية
                        </h5>
                        
                        <div class="row g-3">
                            <!-- Plan Name -->
                            <div class="col-md-6">
                                <label for="plan_name" class="form-label required-field">
                                    <i class="fas fa-heading me-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 me-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 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="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 me-1"></i>القسم
                                </label>
                                <select class="form-select <?= isset($errors['section_id']) ? 'is-invalid' : '' ?>" 
                                        id="section_id" 
                                        name="section_id" 
                                        required>
                                    <option value="">اختر الكلية أولاً</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 me-1"></i>البرنامج
                                </label>
                                <select class="form-select <?= isset($errors['program_id']) ? 'is-invalid' : '' ?>" 
                                        id="program_id" 
                                        name="program_id" 
                                        required>
                                    <option value="">اختر الكلية أولاً</option>
                                </select>
                                <?php if (isset($errors['program_id'])): ?>
                                    <span class="error-message"><?= e($errors['program_id']) ?></span>
                                <?php endif; ?>
                            </div>
                            
                            <!-- Total Semesters -->
                            <div class="col-md-6">
                                <label for="total_semesters" class="form-label">
                                    <i class="fas fa-calendar-alt me-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>
                            
                            <!-- Description -->
                            <div class="col-12">
                                <label for="description" class="form-label">
                                    <i class="fas fa-align-left me-1"></i>وصف الخطة
                                </label>
                                <textarea class="form-control" 
                                          id="description" 
                                          name="description" 
                                          rows="3"
                                          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 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="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">
                                    <span class="badge bg-<?= $is_active ? 'success' : 'secondary' ?> p-2">
                                        <i class="fas fa-<?= $is_active ? 'check-circle' : 'pause-circle' ?> me-1"></i>
                                        <?= $is_active ? 'نشط' : 'غير نشط' ?>
                                    </span>
                                </label>
                            </div>
                            <span class="form-help">الخطة النشطة تظهر في القوائم والاختيارات</span>
                        </div>
                        
                        <!-- Quick Info -->
                        <div class="alert alert-info">
                            <h6 class="fw-semibold mb-2">
                                <i class="fas fa-info-circle me-1"></i>
                                معلومات
                            </h6>
                            <p class="small mb-0">
                                بعد حفظ الخطة، يمكنك إضافة المقررات الدراسية وتوزيعها على الفصول الدراسية.
                            </p>
                        </div>
                        
                        <!-- Save Buttons -->
                        <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>
                                <?= $isEdit ? 'تحديث الخطة' : 'حفظ الخطة' ?>
                            </button>
                            
                            <?php if (!$isEdit): ?>
                                <button type="submit" name="save_and_continue" class="btn btn-outline-primary">
                                    <i class="fas fa-arrow-left me-2"></i>
                                    حفظ وإضافة المقررات
                                </button>
                            <?php endif; ?>
                            
                            <?php if ($isEdit): ?>
                                <a href="academic_plan_subjects.php?id=<?= $plan_id ?>" class="btn btn-outline-info">
                                    <i class="fas fa-book me-2"></i>
                                    إدارة المقررات
                                </a>
                            <?php endif; ?>
                            
                            <a href="academic_plans_list.php" class="btn btn-outline-secondary">
                                <i class="fas fa-times me-2"></i>
                                إلغاء
                            </a>
                        </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 data
    let allSections = <?= json_encode($sections) ?>;
    let allPrograms = <?= json_encode($programs) ?>;
    
    function loadSectionsAndPrograms() {
        const collegeId = document.getElementById('college_id').value;
        const sectionSelect = document.getElementById('section_id');
        const programSelect = document.getElementById('program_id');
        
        // Clear and disable if no college
        if (!collegeId) {
            sectionSelect.innerHTML = '<option value="">اختر الكلية أولاً</option>';
            programSelect.innerHTML = '<option value="">اختر الكلية أولاً</option>';
            sectionSelect.disabled = true;
            programSelect.disabled = true;
            return;
        }
        
        // Enable selects
        sectionSelect.disabled = false;
        programSelect.disabled = false;
        
        // Filter sections
        const filteredSections = allSections.filter(s => parseInt(s.parent) === parseInt(collegeId));
        sectionSelect.innerHTML = '<option value="">اختر القسم</option>';
        
        if (filteredSections.length > 0) {
            filteredSections.forEach(section => {
                const option = document.createElement('option');
                option.value = section.id;
                option.textContent = section.name;
                <?php if ($section_id): ?>
                if (section.id == <?= $section_id ?>) {
                    option.selected = true;
                }
                <?php endif; ?>
                sectionSelect.appendChild(option);
            });
        } else {
            sectionSelect.innerHTML = '<option value="">لا توجد أقسام</option>';
        }
        
        // Programs are not filtered by college, but we'll keep them all
        programSelect.innerHTML = '<option value="">اختر البرنامج</option>';
        allPrograms.forEach(program => {
            const option = document.createElement('option');
            option.value = program.id;
            option.textContent = program.name;
            <?php if ($program_id): ?>
            if (program.id == <?= $program_id ?>) {
                option.selected = true;
            }
            <?php endif; ?>
            programSelect.appendChild(option);
        });
    }
    
    // Initialize on page load
    document.addEventListener('DOMContentLoaded', function() {
        const collegeSelect = document.getElementById('college_id');
        
        if (collegeSelect.value) {
            loadSectionsAndPrograms();
        } else {
            document.getElementById('section_id').disabled = true;
            document.getElementById('program_id').disabled = true;
        }
        
        // Form validation
        const form = document.getElementById('planForm');
        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('الرجاء ملء جميع الحقول المطلوبة');
            }
        });
    });
    </script>
</body>
</html>