<?php
// admin_dashboard.php - Enhanced Version
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

// Start session first
session_start();

// Check if admin is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: admin_login.php');
    exit;
}

try {
    // Include required files
    if (!file_exists('db.php')) {
        throw new Exception('File db.php not found');
    }
    require 'db.php';
    
    if (!file_exists('helpers.php')) {
        throw new Exception('File helpers.php not found');
    }
    require 'helpers.php';

    $adminId = (int)($_SESSION['admin_id'] ?? 0);
    $adminName = (string)($_SESSION['admin_username'] ?? 'الإدارة العليا');

    // Check database connection
    if (!isset($mysqli1)) {
        throw new Exception('Database connection $mysqli1 not found');
    }

    $mysqli1->set_charset('utf8mb4');
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

    /* ---------- Debug: Check if tables exist ---------- */
    $tableCheck = $mysqli1->query("SHOW TABLES LIKE 'students'");
    if ($tableCheck->num_rows === 0) {
        throw new Exception('Table "students" does not exist');
    }
    
    $tableCheck = $mysqli1->query("SHOW TABLES LIKE 'colleges'");
    if ($tableCheck->num_rows === 0) {
        throw new Exception('Table "colleges" does not exist');
    }
    
    $tableCheck = $mysqli1->query("SHOW TABLES LIKE 'payments'");
    if ($tableCheck->num_rows === 0) {
        // Continue but note that payments table doesn't exist
        $payments_table_exists = false;
    } else {
        $payments_table_exists = true;
    }

    /* ---------- Top KPIs ---------- */
    $sqlKpi = "
        SELECT
            COUNT(*) AS total_students,
            
            -- Profile completion
            SUM(CASE WHEN s.profile_completed = 1 THEN 1 ELSE 0 END) AS profile_complete,
            SUM(CASE WHEN s.profile_completed = 0 OR s.profile_completed IS NULL THEN 1 ELSE 0 END) AS profile_incomplete,
            
            -- Medical status
            SUM(CASE WHEN s.medically_fit = 1 THEN 1 ELSE 0 END) AS medical_fit,
            SUM(CASE WHEN s.medically_fit = 0 THEN 1 ELSE 0 END) AS medical_unfit,
            SUM(CASE WHEN (s.medically_fit IS NULL OR s.medically_fit = '') AND s.profile_completed = 1 THEN 1 ELSE 0 END) AS medical_pending,
            
            -- Interview status
            SUM(CASE WHEN s.interview_status = 'accepted' THEN 1 ELSE 0 END) AS interview_accepted,
            SUM(CASE WHEN s.interview_status = 'rejected' THEN 1 ELSE 0 END) AS interview_rejected,
            SUM(CASE WHEN s.interview_status = 'pending' OR s.interview_status IS NULL THEN 1 ELSE 0 END) AS interview_pending
            
        FROM students s
    ";
    
    $kpi_result = $mysqli1->query($sqlKpi);
    if (!$kpi_result) {
        throw new Exception('SQL Error in KPI query: ' . $mysqli1->error);
    }
    
    $kpi = $kpi_result->fetch_assoc();
    $kpi_result->close();

    // Ensure all kpi values are integers
    foreach ($kpi as $key => $value) {
        $kpi[$key] = (int)($value ?? 0);
    }

    /* ---------- Total Fees Paid ---------- */
    $total_fees = 0;
    if ($payments_table_exists) {
        $sqlFees = "SELECT SUM(payment_amount) as total_fees FROM payments";
        $fees_result = $mysqli1->query($sqlFees);
        if ($fees_result) {
            $fees_data = $fees_result->fetch_assoc();
            $total_fees = $fees_data['total_fees'] ? (float)$fees_data['total_fees'] : 0;
            $fees_result->close();
        }
    }

    /* ---------- Students per College with Fees ---------- */
    $sqlColleges = "
        SELECT 
            c.id,
            c.name as college_name,
            COUNT(s.student_id) as student_count,
            COALESCE(SUM(p.payment_amount), 0) as total_fees,
            SUM(CASE WHEN s.profile_completed = 1 THEN 1 ELSE 0 END) as profile_complete,
            SUM(CASE WHEN s.medically_fit = 1 THEN 1 ELSE 0 END) as medical_fit,
            SUM(CASE WHEN s.medically_fit = 0 THEN 1 ELSE 0 END) as medical_unfit,
            SUM(CASE WHEN s.interview_status = 'accepted' THEN 1 ELSE 0 END) as interview_accepted
        FROM colleges c
        LEFT JOIN students s ON c.id = s.college_id
        " . ($payments_table_exists ? "LEFT JOIN payments p ON s.student_id = p.student_id" : "") . "
        GROUP BY c.id, c.name
        ORDER BY student_count DESC
    ";
    
    $colleges_result = $mysqli1->query($sqlColleges);
    if (!$colleges_result) {
        throw new Exception('SQL Error in colleges query: ' . $mysqli1->error);
    }
    
    $college_stats = $colleges_result->fetch_all(MYSQLI_ASSOC);
    $colleges_result->close();

    /* ---------- Payment Statistics ---------- */
    $payment_stats = [
        'students_with_payments' => 0,
        'total_payments' => 0,
        'avg_payment' => 0,
        'max_payment' => 0,
        'min_payment' => 0
    ];
    
    if ($payments_table_exists) {
        $sqlPayments = "
            SELECT 
                COUNT(DISTINCT student_id) as students_with_payments,
                COUNT(*) as total_payments,
                AVG(payment_amount) as avg_payment,
                MAX(payment_amount) as max_payment,
                MIN(payment_amount) as min_payment
            FROM payments
        ";
        $payments_result = $mysqli1->query($sqlPayments);
        if ($payments_result) {
            $payment_stats = $payments_result->fetch_assoc();
            $payments_result->close();
        }
    }

    // Ensure numeric values
    $payment_stats['students_with_payments'] = (int)($payment_stats['students_with_payments'] ?? 0);
    $payment_stats['total_payments'] = (int)($payment_stats['total_payments'] ?? 0);
    $payment_stats['avg_payment'] = $payment_stats['avg_payment'] ? round((float)$payment_stats['avg_payment'], 2) : 0;
    $payment_stats['max_payment'] = $payment_stats['max_payment'] ? round((float)$payment_stats['max_payment'], 2) : 0;
    $payment_stats['min_payment'] = $payment_stats['min_payment'] ? round((float)$payment_stats['min_payment'], 2) : 0;

    /* ---------- Recent Students with Details ---------- */
    $sqlRecent = "
        SELECT 
            s.student_id,
            s.student_name_eng,
            s.student_name,
            c.name as college_name,
            s.profile_completed,
            s.medical_status,
            s.medically_fit,
            s.interview_status,
            COALESCE(SUM(p.payment_amount), 0) as paid_amount
        FROM students s
        LEFT JOIN colleges c ON s.college_id = c.id
        " . ($payments_table_exists ? "LEFT JOIN payments p ON s.student_id = p.student_id" : "") . "
        GROUP BY s.student_id
        ORDER BY s.created_at DESC
        LIMIT 50
    ";
    
    $recent_result = $mysqli1->query($sqlRecent);
    if (!$recent_result) {
        throw new Exception('SQL Error in recent students query: ' . $mysqli1->error);
    }
    
    $recent_students = $recent_result->fetch_all(MYSQLI_ASSOC);
    $recent_result->close();

    $data_loaded = true;

} catch (Exception $e) {
    $error_message = $e->getMessage();
    $data_loaded = false;
    
    // Fallback data for UI
    $kpi = [
        'total_students' => 0,
        'profile_complete' => 0,
        'profile_incomplete' => 0,
        'medical_fit' => 0,
        'medical_unfit' => 0,
        'medical_pending' => 0,
        'interview_accepted' => 0,
        'interview_rejected' => 0,
        'interview_pending' => 0
    ];
    $total_fees = 0;
    $college_stats = [];
    $payment_stats = [
        'students_with_payments' => 0,
        'total_payments' => 0,
        'avg_payment' => 0,
        'max_payment' => 0,
        'min_payment' => 0
    ];
    $recent_students = [];
}

// Include header after processing data to avoid header sent errors
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 href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root {
            --g-900: #1F3A2E;
            --g-700: #3E6B54;
            --g-500: #6F9E84;
            --g-300: #A8C5B4;
            --g-100: #ECF3EF;
            --purple-600: #8e44ad;
            --purple-700: #7d3c98;
            --blue-500: #3498db;
            --green-500: #27ae60;
            --orange-500: #f39c12;
            --red-500: #e74c3c;
            --teal-500: #1abc9c;
        }

        body {
            font-family: 'Cairo', system-ui, -apple-system, sans-serif;
            background: var(--g-100);
            min-height: 100vh;
        }

        .dashboard-header {
            background: linear-gradient(135deg, var(--purple-600), var(--purple-700));
            color: white;
            padding: 2rem 0;
            margin-bottom: 2rem;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }

        .welcome-message {
            font-size: 1.8rem;
            font-weight: 800;
            margin-bottom: 0.5rem;
        }

        .stats-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 1.5rem;
            margin-bottom: 3rem;
        }

        .stat-card {
            background: white;
            padding: 1.5rem;
            border-radius: 1rem;
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
            border-right: 4px solid var(--purple-600);
            text-align: center;
            transition: all 0.3s ease;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }

        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 100%;
            height: 4px;
            background: inherit;
            opacity: 0.3;
        }

        .stat-icon {
            font-size: 2.5rem;
            margin-bottom: 1rem;
            opacity: 0.9;
        }

        .stat-number {
            font-size: 2.2rem;
            font-weight: 800;
            margin-bottom: 0.5rem;
            color: var(--g-900);
        }

        .stat-label {
            color: var(--gray-600);
            font-weight: 600;
            font-size: 1rem;
            margin-bottom: 0.5rem;
        }

        .stat-subtext {
            font-size: 0.85rem;
            color: #6c757d;
            margin-top: 0.5rem;
        }

        .stat-card-link {
            text-decoration: none;
            color: inherit;
            display: block;
        }

        .stat-card-link:hover {
            color: inherit;
            text-decoration: none;
        }

        .college-card {
            background: white;
            border-radius: 0.75rem;
            padding: 1.5rem;
            border-right: 4px solid var(--purple-600);
            margin-bottom: 1rem;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .college-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.12);
            border-right-color: var(--blue-500);
        }

        .college-name {
            font-weight: 800;
            color: var(--g-900);
            margin-bottom: 1rem;
            font-size: 1.1rem;
        }

        .college-stats {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 0.5rem;
            margin-bottom: 1rem;
        }

        .college-stat-item {
            text-align: center;
            padding: 0.5rem;
            background: var(--g-100);
            border-radius: 0.5rem;
        }

        .college-stat-number {
            font-weight: 700;
            font-size: 1.1rem;
            color: var(--g-900);
        }

        .college-stat-label {
            font-size: 0.75rem;
            color: var(--gray-600);
            margin-top: 0.25rem;
        }

        .college-actions {
            display: flex;
            gap: 0.5rem;
            justify-content: space-between;
        }

        .college-action-btn {
            flex: 1;
            padding: 0.4rem 0.8rem;
            border: none;
            border-radius: 0.5rem;
            font-size: 0.8rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            text-align: center;
        }

        .college-action-btn.primary {
            background: var(--blue-500);
            color: white;
        }

        .college-action-btn.secondary {
            background: var(--g-300);
            color: var(--g-900);
        }

        .college-action-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        }

        .error-alert {
            background: #fee2e2;
            border: 1px solid #fecaca;
            color: #dc2626;
            padding: 1rem;
            border-radius: 0.75rem;
            margin-bottom: 2rem;
            font-weight: 600;
        }

        .debug-info {
            background: #f3f4f6;
            border: 1px solid #d1d5db;
            color: #374151;
            padding: 1rem;
            border-radius: 0.75rem;
            margin-bottom: 2rem;
            font-family: monospace;
            font-size: 0.9rem;
            white-space: pre-wrap;
        }

        .logout-btn {
            background: var(--purple-600);
            color: white;
            border: none;
            padding: 0.75rem 1.5rem;
            border-radius: 0.75rem;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.3s ease;
            font-family: 'Cairo', sans-serif;
            text-decoration: none;
            display: inline-block;
        }

        .logout-btn:hover {
            background: var(--purple-700);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(142, 68, 173, 0.3);
            color: white;
        }

        .section-title {
            font-size: 1.5rem;
            font-weight: 800;
            color: var(--g-900);
            margin-bottom: 1.5rem;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid var(--g-300);
        }

        .data-section {
            background: white;
            border-radius: 1rem;
            padding: 2rem;
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
            margin-bottom: 2rem;
        }
    </style>
</head>
<body>
    <!-- Dashboard Header -->
    <div class="dashboard-header">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h1 class="welcome-message">مرحباً، <?php echo htmlspecialchars($adminName); ?> 👨‍💼</h1>
                    <p class="login-time">آخر تحديث: <?php echo date('Y-m-d H:i:s'); ?></p>
                </div>
                <div class="col-md-4 text-md-start">
                    <a href="admin_logout.php" class="logout-btn">
                        <i class="fas fa-sign-out-alt"></i> تسجيل الخروج
                    </a>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <?php if (isset($error_message)): ?>
            <div class="error-alert">
                <i class="fas fa-exclamation-triangle"></i> <strong>خطأ:</strong> <?php echo htmlspecialchars($error_message); ?>
            </div>
            
            <div class="debug-info">
                <strong>معلومات التصحيح:</strong>
                
                تحقق من:
                ١. وجود ملف db.php في المجلد الصحيح
                ٢. اتصال قاعدة البيانات في db.php
                ٣. وجود الجداول التالية: students, colleges, payments
                ٤. أسماء الأعمدة في الجداول تتطابق مع الاستعلامات
                
                الخطأ التفصيلي:
                <?php echo htmlspecialchars($error_message); ?>
            </div>
        <?php endif; ?>

        <?php if ($data_loaded): ?>
        <!-- Main Statistics with Links -->
        <div class="data-section">
            <h4 class="section-title">📊 الإحصائيات الرئيسية</h4>
            <div class="stats-cards">
                <!-- Total Students Card -->
                <a href="admin_students.php?filter=all" class="stat-card-link">
                    <div class="stat-card" style="border-right-color: var(--blue-500);">
                        <div class="stat-icon">🎓</div>
                        <div class="stat-number"><?= number_format($kpi['total_students']) ?></div>
                        <div class="stat-label">إجمالي الطلاب</div>
                        <div class="stat-subtext">انقر لعرض جميع الطلاب</div>
                    </div>
                </a>

                <!-- Profile Complete Card -->
                <a href="admin_students.php?filter=profile_complete" class="stat-card-link">
                    <div class="stat-card" style="border-right-color: var(--green-500);">
                        <div class="stat-icon">✅</div>
                        <div class="stat-number"><?= number_format($kpi['profile_complete']) ?></div>
                        <div class="stat-label">مكتملي الملف الشخصي</div>
                        <div class="stat-subtext"><?= $kpi['total_students'] > 0 ? number_format(($kpi['profile_complete']/$kpi['total_students'])*100, 1) : 0 ?>% من الإجمالي</div>
                    </div>
                </a>

                <!-- Medical Fit Card -->
                <a href="admin_students.php?filter=medical_fit" class="stat-card-link">
                    <div class="stat-card" style="border-right-color: var(--teal-500);">
                        <div class="stat-icon">💪</div>
                        <div class="stat-number"><?= number_format($kpi['medical_fit']) ?></div>
                        <div class="stat-label">لائق طبياً</div>
                        <div class="stat-subtext">انقر لعرض اللائقين طبياً</div>
                    </div>
                </a>

                <!-- Medical Unfit Card -->
                <a href="admin_students.php?filter=medical_unfit" class="stat-card-link">
                    <div class="stat-card" style="border-right-color: var(--red-500);">
                        <div class="stat-icon">🚫</div>
                        <div class="stat-number"><?= number_format($kpi['medical_unfit']) ?></div>
                        <div class="stat-label">غير لائق طبياً</div>
                        <div class="stat-subtext">انقر لعرض غير اللائقين</div>
                    </div>
                </a>

                <!-- Interview Accepted Card -->
                <a href="admin_students.php?filter=interview_accepted" class="stat-card-link">
                    <div class="stat-card" style="border-right-color: var(--green-500);">
                        <div class="stat-icon">👍</div>
                        <div class="stat-number"><?= number_format($kpi['interview_accepted']) ?></div>
                        <div class="stat-label">مقبول في المقابلة</div>
                        <div class="stat-subtext">انقر لعرض المقبولين</div>
                    </div>
                </a>

                <!-- Interview Rejected Card -->
                <a href="admin_students.php?filter=interview_rejected" class="stat-card-link">
                    <div class="stat-card" style="border-right-color: var(--red-500);">
                        <div class="stat-icon">👎</div>
                        <div class="stat-number"><?= number_format($kpi['interview_rejected']) ?></div>
                        <div class="stat-label">مرفوض في المقابلة</div>
                        <div class="stat-subtext">انقر لعرض المرفوضين</div>
                    </div>
                </a>

                <!-- Pending Medical Card -->
                <a href="admin_students.php?filter=medical_pending" class="stat-card-link">
                    <div class="stat-card" style="border-right-color: var(--orange-500);">
                        <div class="stat-icon">⏳</div>
                        <div class="stat-number"><?= number_format($kpi['medical_pending']) ?></div>
                        <div class="stat-label">بانتظار الفحص الطبي</div>
                        <div class="stat-subtext">انقر لعرض قيد الانتظار</div>
                    </div>
                </a>

                <!-- Total Fees Card -->
                <a href="admin_payments.php" class="stat-card-link">
                    <div class="stat-card" style="border-right-color: var(--purple-600);">
                        <div class="stat-icon">💰</div>
                        <div class="stat-number"><?= number_format($total_fees) ?></div>
                        <div class="stat-label">إجمالي الرسوم المدفوعة</div>
                        <div class="stat-subtext">انقر لعرض المدفوعات</div>
                    </div>
                </a>
            </div>
        </div>

        <!-- Advanced College Statistics -->
        <div class="data-section">
            <h4 class="section-title">🏫 إحصائيات الكليات المتقدمة</h4>
            <div class="row">
                <?php foreach ($college_stats as $college): ?>
                    <div class="col-md-6 col-lg-4 mb-3">
                        <div class="college-card" onclick="viewCollegeStudents(<?= $college['id'] ?>)">
                            <div class="college-name"><?= htmlspecialchars($college['college_name']) ?></div>
                            
                            <div class="college-stats">
                                <div class="college-stat-item">
                                    <div class="college-stat-number"><?= number_format($college['student_count']) ?></div>
                                    <div class="college-stat-label">إجمالي الطلاب</div>
                                </div>
                                <div class="college-stat-item">
                                    <div class="college-stat-number"><?= number_format($college['total_fees']) ?></div>
                                    <div class="college-stat-label">الرسوم</div>
                                </div>
                                <div class="college-stat-item">
                                    <div class="college-stat-number"><?= number_format($college['profile_complete']) ?></div>
                                    <div class="college-stat-label">ملف مكتمل</div>
                                </div>
                                <div class="college-stat-item">
                                    <div class="college-stat-number"><?= number_format($college['medical_fit']) ?></div>
                                    <div class="college-stat-label">لائق طبياً</div>
                                </div>
                            </div>

                            <div class="college-actions">
                                <a href="admin_students.php?college=<?= $college['id'] ?>&filter=all" 
                                   class="college-action-btn primary">
                                    جميع الطلاب
                                </a>
                                <a href="admin_students.php?college=<?= $college['id'] ?>&filter=medical_fit" 
                                   class="college-action-btn secondary">
                                    اللائقين فقط
                                </a>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Students List -->
        <div class="data-section">
            <h4 class="section-title">🎓 قائمة الطلاب الأخيرة</h4>
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <th>رقم الطالب</th>
                            <th>اسم الطالب</th>
                            <th>الكلية</th>
                            <th>الملف الشخصي</th>
                            <th>الحالة الطبية</th>
                            <th>حالة المقابلة</th>
                            <th>المبلغ المدفوع</th>
                            <th>الإجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($recent_students as $student): ?>
                            <tr>
                                <td><strong><?= htmlspecialchars($student['student_id']) ?></strong></td>
                                <td>
                                    <?php 
                                    $name = !empty($student['student_name']) ? $student['student_name'] : $student['student_name_eng'];
                                    echo htmlspecialchars($name);
                                    ?>
                                </td>
                                <td><?= htmlspecialchars($student['college_name']) ?></td>
                                <td>
                                    <span class="badge <?= $student['profile_completed'] ? 'bg-success' : 'bg-danger'; ?>">
                                        <?= $student['profile_completed'] ? 'مكتمل' : 'غير مكتمل'; ?>
                                    </span>
                                </td>
                                <td>
                                    <?php 
                                    $medical_status = 'pending';
                                    if ($student['medically_fit'] == 1) {
                                        $medical_status = 'fit';
                                    } elseif ($student['medically_fit'] == 0) {
                                        $medical_status = 'unfit';
                                    }
                                    ?>
                                    <?php if ($medical_status == 'fit'): ?>
                                        <span class="badge bg-success">لائق</span>
                                    <?php elseif ($medical_status == 'unfit'): ?>
                                        <span class="badge bg-danger">غير لائق</span>
                                    <?php else: ?>
                                        <span class="badge bg-warning">قيد المراجعة</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php 
                                    $interview_status = $student['interview_status'] ?? 'pending';
                                    ?>
                                    <?php if ($interview_status == 'accepted'): ?>
                                        <span class="badge bg-success">مقبول</span>
                                    <?php elseif ($interview_status == 'rejected'): ?>
                                        <span class="badge bg-danger">مرفوض</span>
                                    <?php else: ?>
                                        <span class="badge bg-warning">قيد الانتظار</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="text-success fw-bold"><?= number_format($student['paid_amount'], 2) ?></span>
                                </td>
                                <td>
                                    <a href="admin_student_details.php?student_id=<?= $student['student_id'] ?>" 
                                       class="btn btn-sm btn-outline-primary">تفاصيل</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <script>
    function viewCollegeStudents(collegeId) {
        window.location.href = 'admin_students.php?college=' + collegeId + '&filter=all';
    }

    // Add click handlers for college cards
    document.addEventListener('DOMContentLoaded', function() {
        const collegeCards = document.querySelectorAll('.college-card');
        collegeCards.forEach(card => {
            card.addEventListener('click', function(e) {
                // Don't trigger if clicking on action buttons
                if (!e.target.closest('.college-action-btn')) {
                    const collegeId = this.getAttribute('onclick').match(/\d+/)[0];
                    viewCollegeStudents(collegeId);
                }
            });
        });
    });
    </script>

    <?php include 'footer.php'; ?>
</body>
</html>