<?php
// academic_plans_list.php - نسخة محسنة مع RTL وتصميم أفضل وآمنة من SQL Injection
error_reporting(E_ALL);
ini_set('display_errors', 1);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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;

// =============================================
// معالجة الإجراءات (حذف، تغيير حالة)
// =============================================

// Handle deletion
if (isset($_GET['delete']) && ctype_digit($_GET['delete'])) {
    $planId = (int)$_GET['delete'];
    
    // Check if plan exists and belongs to committee's scope
    $checkSql = "SELECT ap.id FROM academic_plans ap WHERE ap.id = ? AND ap.deleted_at IS NULL";
    $types = "i";
    $params = [$planId];
    
    if (!$canAll && $scopeCollege !== null) {
        $checkSql .= " AND ap.college_id = ?";
        $types .= "i";
        $params[] = $scopeCollege;
    }
    
    $checkStmt = $mysqli1->prepare($checkSql);
    if ($checkStmt) {
        $checkStmt->bind_param($types, ...$params);
        $checkStmt->execute();
        $planExists = $checkStmt->get_result()->fetch_assoc();
        $checkStmt->close();
        
        if ($planExists) {
            // Soft delete
            $deleteStmt = $mysqli1->prepare("UPDATE academic_plans SET deleted_at = NOW() WHERE id = ?");
            if ($deleteStmt) {
                $deleteStmt->bind_param('i', $planId);
                
                if ($deleteStmt->execute()) {
                    $_SESSION['success_message'] = "تم حذف الخطة الدراسية بنجاح";
                } else {
                    $_SESSION['error_message'] = "حدث خطأ أثناء الحذف";
                }
                $deleteStmt->close();
            }
        } else {
            $_SESSION['error_message'] = "الخطة الدراسية غير موجودة أو ليس لديك صلاحية لحذفها";
        }
    }
    
    header("Location: academic_plans_list.php");
    exit;
}

// Handle status toggle
if (isset($_GET['toggle_status']) && ctype_digit($_GET['toggle_status'])) {
    $planId = (int)$_GET['toggle_status'];
    
    $checkSql = "SELECT ap.id, ap.is_active FROM academic_plans ap WHERE ap.id = ? AND ap.deleted_at IS NULL";
    $types = "i";
    $params = [$planId];
    
    if (!$canAll && $scopeCollege !== null) {
        $checkSql .= " AND ap.college_id = ?";
        $types .= "i";
        $params[] = $scopeCollege;
    }
    
    $checkStmt = $mysqli1->prepare($checkSql);
    if ($checkStmt) {
        $checkStmt->bind_param($types, ...$params);
        $checkStmt->execute();
        $plan = $checkStmt->get_result()->fetch_assoc();
        $checkStmt->close();
        
        if ($plan) {
            $newStatus = $plan['is_active'] ? 0 : 1;
            $toggleStmt = $mysqli1->prepare("UPDATE academic_plans SET is_active = ? WHERE id = ?");
            if ($toggleStmt) {
                $toggleStmt->bind_param('ii', $newStatus, $planId);
                
                if ($toggleStmt->execute()) {
                    $_SESSION['success_message'] = $newStatus ? "تم تفعيل الخطة الدراسية" : "تم إيقاف الخطة الدراسية";
                } else {
                    $_SESSION['error_message'] = "حدث خطأ أثناء تغيير الحالة";
                }
                $toggleStmt->close();
            }
        }
    }
    
    header("Location: academic_plans_list.php");
    exit;
}

// =============================================
// بناء الاستعلام مع الفلاتر (باستخدام Prepared Statements)
// =============================================

// تنظيف المدخلات
$search = trim($_GET['search'] ?? '');
$search = htmlspecialchars($search, ENT_QUOTES, 'UTF-8');

$program_id = isset($_GET['program_id']) && $_GET['program_id'] !== '' && ctype_digit($_GET['program_id']) ? (int)$_GET['program_id'] : null;
$college_id = isset($_GET['college_id']) && $_GET['college_id'] !== '' && ctype_digit($_GET['college_id']) ? (int)$_GET['college_id'] : null;
$section_id = isset($_GET['section_id']) && $_GET['section_id'] !== '' && ctype_digit($_GET['section_id']) ? (int)$_GET['section_id'] : null;
$specialization_id = isset($_GET['specialization_id']) && $_GET['specialization_id'] !== '' && ctype_digit($_GET['specialization_id']) ? (int)$_GET['specialization_id'] : null;
$is_active = isset($_GET['is_active']) && $_GET['is_active'] !== '' && ctype_digit($_GET['is_active']) ? (int)$_GET['is_active'] : null;

$where = "WHERE ap.deleted_at IS NULL";
$types = '';
$params = [];

// Apply committee scope
if (!$canAll && $scopeCollege !== null) {
    $where .= " AND ap.college_id = ?";
    $types .= 'i';
    $params[] = $scopeCollege;
}

// Apply filters
if ($search !== '') {
    $where .= " AND (ap.plan_name LIKE ? OR ap.plan_code LIKE ?)";
    $types .= 'ss';
    $searchTerm = "%$search%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

if ($program_id !== null) {
    $where .= " AND ap.program_id = ?";
    $types .= 'i';
    $params[] = $program_id;
}

// التحقق من الصلاحية قبل تطبيق فلتر الكلية
if ($college_id !== null && ($canAll || $college_id == $scopeCollege)) {
    $where .= " AND ap.college_id = ?";
    $types .= 'i';
    $params[] = $college_id;
}

if ($section_id !== null) {
    $where .= " AND ap.section_id = ?";
    $types .= 'i';
    $params[] = $section_id;
}

if ($specialization_id !== null) {
    $where .= " AND ap.specialization_id = ?";
    $types .= 'i';
    $params[] = $specialization_id;
}

if ($is_active !== null) {
    $where .= " AND ap.is_active = ?";
    $types .= 'i';
    $params[] = $is_active;
}

// Get total count for plans
$countQuery = "SELECT COUNT(*) as total FROM academic_plans ap $where";
$countStmt = $mysqli1->prepare($countQuery);
$totalCount = 0;

if ($countStmt) {
    if (!empty($params)) {
        $countStmt->bind_param($types, ...$params);
    }
    $countStmt->execute();
    $countResult = $countStmt->get_result()->fetch_assoc();
    $totalCount = $countResult['total'] ?? 0;
    $countStmt->close();
}

// Pagination
$perPage = 20;
$page = isset($_GET['page']) && ctype_digit($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $perPage;
$totalPages = $totalCount > 0 ? ceil($totalCount / $perPage) : 1;

// Get plans with joins including specialization
$query = "
    SELECT 
        ap.*,
        c.name as college_name,
        sec.name as section_name,
        p.name as program_name,
        sp.specialization_name_ar as specialization_name,
        (SELECT COUNT(*) FROM academic_plan_subjects WHERE plan_id = ap.id) as total_subjects,
        (SELECT COUNT(DISTINCT semester_id) FROM academic_plan_subjects WHERE plan_id = ap.id) as total_semesters_used
    FROM academic_plans ap
    LEFT JOIN colleges c ON c.id = ap.college_id
    LEFT JOIN sections sec ON sec.id = ap.section_id
    LEFT JOIN programs p ON p.id = ap.program_id
    LEFT JOIN specializations sp ON sp.specialization_id = ap.specialization_id
    $where
    ORDER BY ap.created_at DESC
    LIMIT ? OFFSET ?
";

$queryTypes = $types . 'ii';
$queryParams = array_merge($params, [$perPage, $offset]);

$plans = [];
$stmt = $mysqli1->prepare($query);
if ($stmt) {
    if (!empty($queryParams)) {
        $stmt->bind_param($queryTypes, ...$queryParams);
    }
    $stmt->execute();
    $result = $stmt->get_result();
    $plans = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
}

// Get filter data باستخدام prepared statements
$colleges = [];
$collegesStmt = $mysqli1->prepare("SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name");
if ($collegesStmt) {
    $collegesStmt->execute();
    $collegesResult = $collegesStmt->get_result();
    $colleges = $collegesResult->fetch_all(MYSQLI_ASSOC);
    $collegesStmt->close();
}

$programs = [];
$programsStmt = $mysqli1->prepare("SELECT id, name FROM programs WHERE deleted_at IS NULL ORDER BY name");
if ($programsStmt) {
    $programsStmt->execute();
    $programsResult = $programsStmt->get_result();
    $programs = $programsResult->fetch_all(MYSQLI_ASSOC);
    $programsStmt->close();
}

$sections = [];
$sectionsStmt = $mysqli1->prepare("SELECT id, name, parent FROM sections WHERE deleted_at IS NULL ORDER BY name");
if ($sectionsStmt) {
    $sectionsStmt->execute();
    $sectionsResult = $sectionsStmt->get_result();
    $sections = $sectionsResult->fetch_all(MYSQLI_ASSOC);
    $sectionsStmt->close();
}

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

// =============================================
// إحصائيات ديناميكية مع تطبيق الفلاتر (باستخدام Prepared Statements)
// =============================================

$statsWhere = "WHERE deleted_at IS NULL";
$statsTypes = '';
$statsParams = [];

// Apply committee scope
if (!$canAll && $scopeCollege !== null) {
    $statsWhere .= " AND college_id = ?";
    $statsTypes .= 'i';
    $statsParams[] = $scopeCollege;
}

// Apply all filters except is_active (since we need active/inactive breakdown)
if ($search !== '') {
    $statsWhere .= " AND (plan_name LIKE ? OR plan_code LIKE ?)";
    $statsTypes .= 'ss';
    $searchTerm = "%$search%";
    $statsParams[] = $searchTerm;
    $statsParams[] = $searchTerm;
}

if ($program_id !== null) {
    $statsWhere .= " AND program_id = ?";
    $statsTypes .= 'i';
    $statsParams[] = $program_id;
}

// التحقق من الصلاحية قبل تطبيق فلتر الكلية في الإحصائيات
if ($college_id !== null && ($canAll || $college_id == $scopeCollege)) {
    $statsWhere .= " AND college_id = ?";
    $statsTypes .= 'i';
    $statsParams[] = $college_id;
}

if ($section_id !== null) {
    $statsWhere .= " AND section_id = ?";
    $statsTypes .= 'i';
    $statsParams[] = $section_id;
}

if ($specialization_id !== null) {
    $statsWhere .= " AND specialization_id = ?";
    $statsTypes .= 'i';
    $statsParams[] = $specialization_id;
}

// Get statistics with filters applied
$statsQuery = "
    SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active,
        SUM(CASE WHEN is_active = 0 THEN 1 ELSE 0 END) as inactive,
        SUM(total_credit_hours) as total_hours
    FROM academic_plans 
    $statsWhere
";

$totalStats = 0;
$activeStats = 0;
$inactiveStats = 0;
$totalHours = 0;

$statsStmt = $mysqli1->prepare($statsQuery);
if ($statsStmt) {
    if (!empty($statsParams)) {
        $statsStmt->bind_param($statsTypes, ...$statsParams);
    }
    $statsStmt->execute();
    $statsResult = $statsStmt->get_result();
    if ($statsResult) {
        $stats = $statsResult->fetch_assoc();
        $totalStats = (int)($stats['total'] ?? 0);
        $activeStats = (int)($stats['active'] ?? 0);
        $inactiveStats = (int)($stats['inactive'] ?? 0);
        $totalHours = (float)($stats['total_hours'] ?? 0);
    }
    $statsStmt->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>الخطط الدراسية - لوحة اللجنة</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;
        }
        
        /* Glassmorphism Cards */
        .glass-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 30px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            border: 1px solid rgba(255, 255, 255, 0.2);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        
        .glass-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 30px 80px rgba(0, 0, 0, 0.4);
        }
        
        /* 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::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -50%;
            width: 200%;
            height: 200%;
            background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
            animation: rotate 20s linear infinite;
        }
        
        @keyframes rotate {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }
        
        .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;
        }
        
        .page-header p {
            color: rgba(255,255,255,0.9);
            font-size: 1.1rem;
            margin-top: 10px;
            position: relative;
        }
        
        /* Buttons */
        .btn-gradient {
            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);
            position: relative;
            overflow: hidden;
        }
        
        .btn-gradient::before {
            content: '';
            position: absolute;
            top: 0;
            right: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent);
            transition: right 0.5s ease;
        }
        
        .btn-gradient:hover::before {
            right: 100%;
        }
        
        .btn-gradient:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0, 176, 155, 0.6);
            color: white;
        }
        
        .btn-outline-gradient {
            background: transparent;
            border: 2px solid #00b09b;
            color: #00b09b;
            padding: 10px 25px;
            border-radius: 50px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .btn-outline-gradient:hover {
            background: linear-gradient(135deg, #00b09b, #96c93d);
            color: white;
            transform: translateY(-2px);
        }
        
        /* Filter Card */
        .filter-card {
            background: rgba(255, 255, 255, 0.98);
            border-radius: 30px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15);
        }
        
        .filter-card .form-label {
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 8px;
            font-size: 0.95rem;
        }
        
        .filter-card .form-control,
        .filter-card .form-select {
            border: 2px solid #e2e8f0;
            border-radius: 15px;
            padding: 12px 15px;
            font-size: 0.95rem;
            transition: all 0.3s ease;
            background: white;
        }
        
        .filter-card .form-control:focus,
        .filter-card .form-select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
            outline: none;
        }
        
        /* Plan Cards */
        .plan-card {
            background: white;
            border-radius: 25px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
            transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            border: 1px solid rgba(102, 126, 234, 0.1);
            position: relative;
            overflow: hidden;
        }
        
        .plan-card::after {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 5px;
            height: 100%;
            background: linear-gradient(135deg, #667eea, #764ba2);
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        
        .plan-card:hover::after {
            opacity: 1;
        }
        
        .plan-card:hover {
            transform: translateY(-5px) scale(1.02);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
        }
        
        .plan-code {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            padding: 8px 18px;
            border-radius: 50px;
            font-weight: 700;
            font-size: 0.9rem;
            display: inline-block;
            box-shadow: 0 4px 10px rgba(102, 126, 234, 0.3);
        }
        
        .status-badge {
            padding: 8px 18px;
            border-radius: 50px;
            font-size: 0.9rem;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .status-active {
            background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
            color: #1e4620;
            box-shadow: 0 4px 10px rgba(132, 250, 176, 0.3);
        }
        
        .status-inactive {
            background: linear-gradient(135deg, #f6d365 0%, #fda085 100%);
            color: #7f4f24;
            box-shadow: 0 4px 10px rgba(253, 160, 133, 0.3);
        }
        
        /* Info Items */
        .info-item {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 10px 15px;
            background: linear-gradient(135deg, #f5f7fa 0%, #e9edf5 100%);
            border-radius: 15px;
            margin-bottom: 8px;
            border: 1px solid rgba(102, 126, 234, 0.1);
        }
        
        .info-icon {
            width: 35px;
            height: 35px;
            background: linear-gradient(135deg, #667eea, #764ba2);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1rem;
        }
        
        /* Stats Badge */
        .stats-badge {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            padding: 6px 15px;
            border-radius: 50px;
            font-size: 0.85rem;
            font-weight: 600;
            color: #2d3748;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            border: 1px solid #dee2e6;
        }
        
        /* Action Buttons */
        .action-buttons {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }
        
        .action-btn {
            width: 38px;
            height: 38px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1rem;
            transition: all 0.3s ease;
            border: none;
            cursor: pointer;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
        }
        
        .action-btn:hover {
            transform: translateY(-3px) scale(1.1);
        }
        
        .btn-view { background: linear-gradient(135deg, #667eea, #764ba2); }
        .btn-edit { background: linear-gradient(135deg, #f6d365, #fda085); }
        .btn-toggle-on { background: linear-gradient(135deg, #84fab0, #8fd3f4); }
        .btn-toggle-off { background: linear-gradient(135deg, #fda085, #f6d365); }
        .btn-delete { background: linear-gradient(135deg, #fc6767, #ec008c); }
        
        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 80px 40px;
            background: linear-gradient(135deg, #f5f7fa 0%, #e9edf5 100%);
            border-radius: 40px;
            border: 3px dashed #667eea;
        }
        
        .empty-state i {
            font-size: 6rem;
            background: linear-gradient(135deg, #667eea, #764ba2);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            margin-bottom: 20px;
        }
        
        /* Pagination */
        .pagination {
            gap: 8px;
        }
        
        .pagination .page-link {
            border: none;
            background: white;
            color: #2d3748;
            border-radius: 12px;
            padding: 12px 18px;
            font-weight: 600;
            transition: all 0.3s ease;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        
        .pagination .page-link:hover {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        .pagination .page-item.active .page-link {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        /* Statistics Cards */
        .stat-card {
            background: white;
            border-radius: 25px;
            padding: 30px 20px;
            text-align: center;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
            border: 1px solid rgba(102, 126, 234, 0.1);
        }
        
        .stat-card::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -50%;
            width: 200%;
            height: 200%;
            background: radial-gradient(circle, rgba(102,126,234,0.1) 0%, transparent 70%);
            animation: rotate 20s linear infinite;
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 40px rgba(102, 126, 234, 0.3);
        }
        
        .stat-card .stat-icon {
            font-size: 2.5rem;
            margin-bottom: 15px;
            background: linear-gradient(135deg, #667eea, #764ba2);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
        
        .stat-card .stat-number {
            font-size: 2.5rem;
            font-weight: 800;
            color: #2d3748;
            margin: 10px 0;
        }
        
        .stat-card .stat-label {
            color: #718096;
            font-size: 1rem;
            font-weight: 600;
        }
        
        /* Alerts */
        .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;
        }
        
        /* 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); }
        }
        
        /* Filter Info */
        .filter-info {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-radius: 20px;
            padding: 15px 20px;
            margin-top: 20px;
            border-right: 4px solid #667eea;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .page-header h1 {
                font-size: 1.8rem;
            }
            
            .plan-card {
                padding: 20px;
            }
            
            .stat-card {
                padding: 20px 15px;
            }
            
            .stat-card .stat-number {
                font-size: 2rem;
            }
        }
        
        /* 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);
        }
    </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-layer-group ms-3"></i>
                        الخطط الدراسية
                    </h1>
                    <p class="mb-0">
                        <i class="fas fa-user-graduate ms-2"></i>
                        إدارة وعرض جميع الخطط الدراسية في النظام
                        <?php if ($search || $program_id || $college_id || $section_id || $specialization_id || $is_active !== null): ?>
                            <span class="badge bg-warning text-dark ms-3">
                                <i class="fas fa-filter ms-1"></i>
                                نتائج البحث
                            </span>
                        <?php endif; ?>
                    </p>
                </div>
                <div>
                    <a href="academic_plan_add.php" class="btn-gradient me-2">
                        <i class="fas fa-plus ms-2"></i>
                        إضافة خطة جديدة
                    </a>
                    <a href="admin_dashboard.php" class="btn-outline-gradient">
                        <i class="fas fa-arrow-left 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>
                    <?= htmlspecialchars($_SESSION['success_message'], ENT_QUOTES, 'UTF-8') ?>
                    <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($_SESSION['error_message'])): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-circle ms-2"></i>
                    <?= htmlspecialchars($_SESSION['error_message'], ENT_QUOTES, 'UTF-8') ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php unset($_SESSION['error_message']); ?>
            <?php endif; ?>

            <!-- Statistics Cards with Filters Applied -->
            <div class="row g-4 mb-4">
                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-layer-group"></i>
                        </div>
                        <div class="stat-number"><?= number_format($totalStats) ?></div>
                        <div class="stat-label">إجمالي الخطط الدراسية</div>
                        <?php if ($totalCount != $totalStats): ?>
                            <small class="text-muted">
                                (عرض <?= number_format($totalCount) ?> في الصفحة الحالية)
                            </small>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-check-circle"></i>
                        </div>
                        <div class="stat-number"><?= number_format($activeStats) ?></div>
                        <div class="stat-label">الخطط النشطة</div>
                        <?php if ($totalStats > 0): ?>
                            <small class="text-success">
                                <?= round(($activeStats / $totalStats) * 100, 1) ?>% من الإجمالي
                            </small>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-pause-circle"></i>
                        </div>
                        <div class="stat-number"><?= number_format($inactiveStats) ?></div>
                        <div class="stat-label">الخطط غير النشطة</div>
                        <?php if ($totalStats > 0): ?>
                            <small class="text-danger">
                                <?= round(($inactiveStats / $totalStats) * 100, 1) ?>% من الإجمالي
                            </small>
                        <?php endif; ?>
                    </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-number"><?= number_format($totalHours, 2) ?></div>
                        <div class="stat-label">إجمالي الساعات المعتمدة</div>
                        <?php if ($totalStats > 0): ?>
                            <small class="text-info">
                                معدل <?= round($totalHours / $totalStats, 1) ?> ساعة/خطة
                            </small>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Filter Card -->
            <div class="filter-card">
                <form method="get" class="row g-4" id="filterForm">
                    <div class="col-md-3">
                        <label class="form-label">
                            <i class="fas fa-search ms-2"></i>
                            بحث
                        </label>
                        <input type="text" class="form-control" name="search" 
                               placeholder="اسم الخطة أو الرمز..." 
                               value="<?= htmlspecialchars($search, ENT_QUOTES, 'UTF-8') ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <label class="form-label">
                            <i class="fas fa-university ms-2"></i>
                            الكلية
                        </label>
                        <select class="form-select" name="college_id" id="college_id" onchange="this.form.submit()">
                            <option value="">جميع الكليات</option>
                            <?php foreach ($colleges as $college): ?>
                                <?php if ($canAll || $college['id'] == $scopeCollege): ?>
                                    <option value="<?= (int)$college['id'] ?>" 
                                        <?= ($college_id == $college['id']) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($college['name'], ENT_QUOTES, 'UTF-8') ?>
                                    </option>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <label class="form-label">
                            <i class="fas fa-building ms-2"></i>
                            القسم
                        </label>
                        <select class="form-select" name="section_id" id="section_id" onchange="this.form.submit()">
                            <option value="">جميع الأقسام</option>
                            <?php
                            $filteredSections = $sections;
                            if ($college_id) {
                                $filteredSections = array_filter($sections, function($s) use ($college_id) {
                                    return ($s['parent'] ?? 0) == $college_id;
                                });
                            }
                            
                            foreach ($filteredSections as $section): ?>
                                <option value="<?= (int)$section['id'] ?>" 
                                    <?= ($section_id == $section['id']) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($section['name'], ENT_QUOTES, 'UTF-8') ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <label class="form-label">
                            <i class="fas fa-graduation-cap ms-2"></i>
                            البرنامج
                        </label>
                        <select class="form-select" name="program_id" id="program_id" onchange="this.form.submit()">
                            <option value="">جميع البرامج</option>
                            <?php foreach ($programs as $program): ?>
                                <option value="<?= (int)$program['id'] ?>" 
                                    <?= ($program_id == $program['id']) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($program['name'], ENT_QUOTES, 'UTF-8') ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <label class="form-label">
                            <i class="fas fa-tag ms-2"></i>
                            التخصص
                        </label>
                        <select class="form-select" name="specialization_id" id="specialization_id" onchange="this.form.submit()">
                            <option value="">اختر القسم والبرنامج أولاً</option>
                            <?php if ($section_id && $program_id && $selectedSpecializationName): ?>
                                <option value="<?= (int)$specialization_id ?>" selected>
                                    <?= htmlspecialchars($selectedSpecializationName, ENT_QUOTES, 'UTF-8') ?>
                                </option>
                            <?php endif; ?>
                        </select>
                        <small class="text-muted" id="specializationStatus"></small>
                    </div>
                    
                    <div class="col-md-1">
                        <label class="form-label">
                            <i class="fas fa-toggle-on ms-2"></i>
                            الحالة
                        </label>
                        <select class="form-select" name="is_active" onchange="this.form.submit()">
                            <option value="">الكل</option>
                            <option value="1" <?= ($is_active === 1) ? 'selected' : '' ?>>نشط</option>
                            <option value="0" <?= ($is_active === 0) ? 'selected' : '' ?>>غير نشط</option>
                        </select>
                    </div>
                </form>
                
                <!-- Active Filters Info -->
                <?php if ($search || $program_id || $college_id || $section_id || $specialization_id || $is_active !== null): ?>
                    <div class="filter-info d-flex align-items-center flex-wrap gap-2">
                        <span class="fw-bold text-secondary ms-2">
                            <i class="fas fa-filter ms-1"></i>
                            الفلاتر النشطة:
                        </span>
                        <?php if ($search): ?>
                            <span class="badge bg-primary text-white p-2">
                                <i class="fas fa-search ms-1"></i>
                                بحث: <?= htmlspecialchars($search, ENT_QUOTES, 'UTF-8') ?>
                            </span>
                        <?php endif; ?>
                        <?php if ($college_id): 
                            $collegeName = '';
                            foreach($colleges as $c) {
                                if($c['id'] == $college_id) {
                                    $collegeName = $c['name'];
                                    break;
                                }
                            }
                        ?>
                            <span class="badge bg-info text-white p-2">
                                <i class="fas fa-university ms-1"></i>
                                <?= htmlspecialchars($collegeName, ENT_QUOTES, 'UTF-8') ?>
                            </span>
                        <?php endif; ?>
                        <?php if ($section_id): 
                            $sectionName = '';
                            foreach($sections as $s) {
                                if($s['id'] == $section_id) {
                                    $sectionName = $s['name'];
                                    break;
                                }
                            }
                        ?>
                            <span class="badge bg-success text-white p-2">
                                <i class="fas fa-building ms-1"></i>
                                <?= htmlspecialchars($sectionName, ENT_QUOTES, 'UTF-8') ?>
                            </span>
                        <?php endif; ?>
                        <?php if ($program_id): 
                            $programName = '';
                            foreach($programs as $p) {
                                if($p['id'] == $program_id) {
                                    $programName = $p['name'];
                                    break;
                                }
                            }
                        ?>
                            <span class="badge bg-warning text-dark p-2">
                                <i class="fas fa-graduation-cap ms-1"></i>
                                <?= htmlspecialchars($programName, ENT_QUOTES, 'UTF-8') ?>
                            </span>
                        <?php endif; ?>
                        <?php if ($specialization_id): ?>
                            <span class="badge text-white p-2" style="background: linear-gradient(135deg, #667eea, #764ba2);">
                                <i class="fas fa-tag ms-1"></i>
                                <?= htmlspecialchars($selectedSpecializationName, ENT_QUOTES, 'UTF-8') ?>
                            </span>
                        <?php endif; ?>
                        <?php if ($is_active !== null): ?>
                            <span class="badge bg-<?= $is_active ? 'success' : 'secondary' ?> text-white p-2">
                                <i class="fas fa-<?= $is_active ? 'check-circle' : 'pause-circle' ?> ms-1"></i>
                                <?= $is_active ? 'نشط' : 'غير نشط' ?>
                            </span>
                        <?php endif; ?>
                        <a href="academic_plans_list.php" class="btn btn-sm btn-outline-danger ms-auto">
                            <i class="fas fa-times ms-1"></i>
                            إزالة الكل
                        </a>
                    </div>
                    
                    <!-- Results Summary -->
                    <div class="mt-3 text-muted">
                        <i class="fas fa-info-circle ms-1"></i>
                        عرض <?= count($plans) ?> من أصل <?= number_format($totalCount) ?> خطة تطابق معايير البحث
                    </div>
                <?php endif; ?>
            </div>

            <!-- Plans Grid -->
            <div class="row g-4">
                <?php if (empty($plans)): ?>
                    <div class="col-12">
                        <div class="empty-state">
                            <i class="fas fa-folder-open"></i>
                            <h4 class="fw-bold mb-3">لا توجد خطط دراسية</h4>
                            <p class="text-muted mb-4">
                                <?php if ($search || $program_id || $college_id || $section_id || $specialization_id || $is_active !== null): ?>
                                    لا توجد نتائج تطابق معايير البحث المحددة
                                <?php else: ?>
                                    لم يتم إضافة أي خطط دراسية بعد
                                <?php endif; ?>
                            </p>
                            <?php if ($search || $program_id || $college_id || $section_id || $specialization_id || $is_active !== null): ?>
                                <a href="academic_plans_list.php" class="btn-gradient btn-lg">
                                    <i class="fas fa-sync-alt ms-2"></i>
                                    عرض الكل
                                </a>
                            <?php else: ?>
                                <a href="academic_plan_add.php" class="btn-gradient btn-lg">
                                    <i class="fas fa-plus ms-2"></i>
                                    إضافة خطة جديدة
                                </a>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php else: ?>
                    <?php foreach ($plans as $plan): ?>
                        <div class="col-xl-4 col-lg-6">
                            <div class="plan-card">
                                <div class="d-flex justify-content-between align-items-start mb-4">
                                    <span class="plan-code">
                                        <i class="fas fa-hashtag ms-1"></i>
                                        <?= htmlspecialchars($plan['plan_code'] ?? '', ENT_QUOTES, 'UTF-8') ?>
                                    </span>
                                    <span class="status-badge <?= ($plan['is_active'] ?? 0) ? 'status-active' : 'status-inactive' ?>">
                                        <i class="fas fa-<?= ($plan['is_active'] ?? 0) ? 'check-circle' : 'pause-circle' ?> ms-1"></i>
                                        <?= ($plan['is_active'] ?? 0) ? 'نشط' : 'غير نشط' ?>
                                    </span>
                                </div>
                                
                                <h4 class="fw-bold mb-4"><?= htmlspecialchars($plan['plan_name'] ?? '', ENT_QUOTES, 'UTF-8') ?></h4>
                                
                                <div class="mb-4">
                                    <div class="info-item">
                                        <div class="info-icon">
                                            <i class="fas fa-university"></i>
                                        </div>
                                        <span class="fw-medium"><?= htmlspecialchars($plan['college_name'] ?? 'غير محدد', ENT_QUOTES, 'UTF-8') ?></span>
                                    </div>
                                    <div class="info-item">
                                        <div class="info-icon">
                                            <i class="fas fa-building"></i>
                                        </div>
                                        <span class="fw-medium"><?= htmlspecialchars($plan['section_name'] ?? 'غير محدد', ENT_QUOTES, 'UTF-8') ?></span>
                                    </div>
                                    <div class="info-item">
                                        <div class="info-icon">
                                            <i class="fas fa-graduation-cap"></i>
                                        </div>
                                        <span class="fw-medium"><?= htmlspecialchars($plan['program_name'] ?? 'غير محدد', ENT_QUOTES, 'UTF-8') ?></span>
                                    </div>
                                    <?php if (!empty($plan['specialization_name'])): ?>
                                    <div class="info-item">
                                        <div class="info-icon">
                                            <i class="fas fa-tag"></i>
                                        </div>
                                        <span class="fw-medium"><?= htmlspecialchars($plan['specialization_name'], ENT_QUOTES, 'UTF-8') ?></span>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                
                                <div class="d-flex flex-wrap gap-2 mb-4">
                                    <span class="stats-badge">
                                        <i class="fas fa-book ms-1"></i>
                                        <?= (int)($plan['total_subjects'] ?? 0) ?> مادة
                                    </span>
                                    <span class="stats-badge">
                                        <i class="fas fa-calendar-alt ms-1"></i>
                                        <?= (int)($plan['total_semesters_used'] ?? 0) ?> فصل
                                    </span>
                                    <span class="stats-badge">
                                        <i class="fas fa-clock ms-1"></i>
                                        <?= (int)($plan['total_credit_hours'] ?? 0) ?> ساعة
                                    </span>
                                </div>
                                
                                <div class="d-flex justify-content-between align-items-center">
                                    <small class="text-muted">
                                        <i class="fas fa-calendar-plus ms-1"></i>
                                        <?= date('Y-m-d', strtotime($plan['created_at'] ?? 'now')) ?>
                                    </small>
                                    
                                    <div class="action-buttons">
                                        <a href="academic_plan_view.php?id=<?= (int)$plan['id'] ?>" 
                                           class="action-btn btn-view" 
                                           title="عرض التفاصيل">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <a href="academic_plan_edit.php?id=<?= (int)$plan['id'] ?>" 
                                           class="action-btn btn-edit" 
                                           title="تعديل">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <a href="academic_plans_list.php?toggle_status=<?= (int)$plan['id'] ?>" 
                                           class="action-btn <?= ($plan['is_active'] ?? 0) ? 'btn-toggle-off' : 'btn-toggle-on' ?>" 
                                           title="<?= ($plan['is_active'] ?? 0) ? 'إيقاف' : 'تفعيل' ?>"
                                           onclick="return confirm('هل أنت متأكد من <?= ($plan['is_active'] ?? 0) ? 'إيقاف' : 'تفعيل' ?> الخطة؟')">
                                            <i class="fas fa-<?= ($plan['is_active'] ?? 0) ? 'pause' : 'play' ?>"></i>
                                        </a>
                                        <a href="academic_plans_list.php?delete=<?= (int)$plan['id'] ?>" 
                                           class="action-btn btn-delete" 
                                           title="حذف"
                                           onclick="return confirm('⚠️ هل أنت متأكد من حذف هذه الخطة؟\nلا يمكن التراجع عن هذا الإجراء.')">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                    
                    <!-- Pagination -->
                    <?php if ($totalPages > 1): ?>
                        <div class="col-12 mt-5">
                            <nav aria-label="Page navigation">
                                <ul class="pagination justify-content-center">
                                    <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
                                        <a class="page-link" href="?<?= htmlspecialchars(http_build_query(array_merge($_GET, ['page' => $page - 1])), ENT_QUOTES, 'UTF-8') ?>">
                                            <i class="fas fa-chevron-right"></i>
                                        </a>
                                    </li>
                                    
                                    <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                                        <?php if ($i == 1 || $i == $totalPages || ($i >= $page - 2 && $i <= $page + 2)): ?>
                                            <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                                                <a class="page-link" href="?<?= htmlspecialchars(http_build_query(array_merge($_GET, ['page' => $i])), ENT_QUOTES, 'UTF-8') ?>">
                                                    <?= $i ?>
                                                </a>
                                            </li>
                                        <?php elseif ($i == $page - 3 || $i == $page + 3): ?>
                                            <li class="page-item disabled">
                                                <span class="page-link">...</span>
                                            </li>
                                        <?php endif; ?>
                                    <?php endfor; ?>
                                    
                                    <li class="page-item <?= $page >= $totalPages ? 'disabled' : '' ?>">
                                        <a class="page-link" href="?<?= htmlspecialchars(http_build_query(array_merge($_GET, ['page' => $page + 1])), ENT_QUOTES, 'UTF-8') ?>">
                                            <i class="fas fa-chevron-left"></i>
                                        </a>
                                    </li>
                                </ul>
                            </nav>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </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>
    $(document).ready(function() {
        // Auto-hide alerts
        setTimeout(function() {
            $('.alert').fadeOut(500, function() {
                $(this).remove();
            });
        }, 5000);
        
        // Load specializations
        function loadSpecializations() {
            const sectionId = $('#section_id').val();
            const programId = $('#program_id').val();
            const currentSpecialization = <?= $specialization_id ? (int)$specialization_id : 'null' ?>;
            
            if (sectionId && programId && sectionId !== '' && programId !== '') {
                $('#specialization_id').prop('disabled', true);
                $('#specializationStatus').html('<span class="loading-spinner"></span> جاري تحميل التخصصات...');
                
                $.ajax({
                    url: 'ajax/get_specializations.php',
                    method: 'GET',
                    data: { 
                        section_id: sectionId,
                        program_id: programId 
                    },
                    dataType: 'json',
                    success: function(specializations) {
                        let options = '<option value="">جميع التخصصات</option>';
                        
                        if (specializations.length > 0) {
                            specializations.forEach(function(spec) {
                                const selected = (currentSpecialization == spec.specialization_id) ? 'selected' : '';
                                options += `<option value="${spec.specialization_id}" ${selected}>${spec.specialization_name_ar}</option>`;
                            });
                            $('#specializationStatus').html('<span class="text-success"><i class="fas fa-check-circle ms-1"></i> ' + specializations.length + ' تخصص</span>');
                        } else {
                            options = '<option value="">لا توجد تخصصات متاحة</option>';
                            $('#specializationStatus').html('<span class="text-muted"><i class="fas fa-info-circle ms-1"></i> لا توجد تخصصات</span>');
                        }
                        
                        $('#specialization_id').html(options).prop('disabled', false);
                    },
                    error: function(xhr, status, error) {
                        console.error('Error loading specializations:', error);
                        $('#specialization_id').html('<option value="">خطأ في تحميل التخصصات</option>').prop('disabled', false);
                        $('#specializationStatus').html('<span class="text-danger"><i class="fas fa-exclamation-circle ms-1"></i> خطأ في التحميل</span>');
                    }
                });
            } else {
                $('#specialization_id').html('<option value="">اختر القسم والبرنامج أولاً</option>').prop('disabled', true);
                $('#specializationStatus').html('<span class="text-muted"><i class="fas fa-info-circle ms-1"></i> يجب اختيار القسم والبرنامج</span>');
            }
        }
        
        // Load specializations on page load
        <?php if ($section_id && $program_id): ?>
            loadSpecializations();
        <?php endif; ?>
        
        // Load specializations on change
        $('#section_id, #program_id').on('change', function() {
            loadSpecializations();
        });
        
        // Auto-submit on specialization change
        $('#specialization_id').on('change', function() {
            $('#filterForm').submit();
        });
        
        // Search debounce
        let searchTimer;
        $('input[name="search"]').on('input', function() {
            clearTimeout(searchTimer);
            searchTimer = setTimeout(() => {
                $('#filterForm').submit();
            }, 1000);
        });
        
        // Tooltips
        $('[title]').tooltip({
            placement: 'top',
            boundary: 'window'
        });
        
        // Smooth scroll for pagination
        $('.pagination .page-link').on('click', function(e) {
            e.preventDefault();
            const url = $(this).attr('href');
            if (url && !$(this).parent().hasClass('disabled')) {
                window.location.href = url;
            }
        });
        
        // Add loading state to buttons
        $('form').on('submit', function() {
            $(this).find('button[type="submit"]').prop('disabled', true).html('<span class="loading-spinner"></span> جاري التحميل...');
        });
        
        // Animate stats cards on scroll
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    $(entry.target).addClass('animate__animated animate__fadeInUp');
                }
            });
        });
        
        $('.stat-card').each(function() {
            observer.observe(this);
        });
    });
    </script>
</body>
</html>
<?php include 'footer.php'; ?>