<?php
// admin_students.php - Filtered Student Lists
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

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 {
    require 'db.php';
    require 'helpers.php';

    $adminName = (string)($_SESSION['admin_username'] ?? 'الإدارة العليا');
    $mysqli1->set_charset('utf8mb4');
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

    // Get filter parameters
    $filter = $_GET['filter'] ?? 'all';
    $college_id = $_GET['college'] ?? null;
    $search = $_GET['search'] ?? '';

    // Build base query
    $sql = "
        SELECT 
            s.student_id,
            s.student_name_eng,
            s.student_name,
            c.name as college_name,
            s.college_id,
            s.profile_completed,
            s.medical_status,
            s.medically_fit,
            s.interview_status,
            s.created_at,
            COALESCE(SUM(p.payment_amount), 0) as paid_amount
        FROM students s
        LEFT JOIN colleges c ON s.college_id = c.id
        LEFT JOIN payments p ON s.student_id = p.student_id
        WHERE 1=1
    ";

    $params = [];
    $types = '';

    // Apply college filter
    if ($college_id && is_numeric($college_id)) {
        $sql .= " AND s.college_id = ?";
        $params[] = $college_id;
        $types .= 'i';
    }

    // Apply search filter
    if (!empty($search)) {
        $sql .= " AND (s.student_id LIKE ? OR s.student_name LIKE ? OR s.student_name_eng LIKE ?)";
        $search_term = "%$search%";
        $params = array_merge($params, [$search_term, $search_term, $search_term]);
        $types .= 'sss';
    }

    // Apply status filter
    switch ($filter) {
        case 'profile_complete':
            $sql .= " AND s.profile_completed = 1";
            break;
        case 'profile_incomplete':
            $sql .= " AND (s.profile_completed = 0 OR s.profile_completed IS NULL)";
            break;
        case 'medical_fit':
            $sql .= " AND s.medically_fit = 1";
            break;
        case 'medical_unfit':
            $sql .= " AND s.medically_fit = 0";
            break;
        case 'medical_pending':
            $sql .= " AND (s.medically_fit IS NULL OR s.medically_fit = '')";
            break;
        case 'interview_accepted':
            $sql .= " AND s.interview_status = 'accepted'";
            break;
        case 'interview_rejected':
            $sql .= " AND s.interview_status = 'rejected'";
            break;
        case 'interview_pending':
            $sql .= " AND (s.interview_status = 'pending' OR s.interview_status IS NULL)";
            break;
        case 'all':
        default:
            // No additional filter
            break;
    }

    $sql .= " GROUP BY s.student_id ORDER BY s.created_at DESC";

    // Prepare and execute query
    $stmt = $mysqli1->prepare($sql);
    if ($types) {
        $stmt->bind_param($types, ...$params);
    }
    $stmt->execute();
    $students = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    // Get college name if filtered by college
    $college_name = '';
    if ($college_id) {
        $college_stmt = $mysqli1->prepare("SELECT name FROM colleges WHERE id = ?");
        $college_stmt->bind_param('i', $college_id);
        $college_stmt->execute();
        $college_result = $college_stmt->get_result()->fetch_assoc();
        $college_name = $college_result['name'] ?? '';
        $college_stmt->close();
    }

    $data_loaded = true;

} catch (Exception $e) {
    $error_message = $e->getMessage();
    $data_loaded = false;
    $students = [];
    $college_name = '';
}

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

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

        .dashboard-header {
            background: linear-gradient(135deg, var(--purple-600), #7d3c98);
            color: white;
            padding: 2rem 0;
            margin-bottom: 2rem;
        }

        .filter-badge {
            background: var(--g-700);
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 2rem;
            font-weight: 600;
        }

        .stats-card {
            background: white;
            border-radius: 1rem;
            padding: 1.5rem;
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
            border-right: 4px solid var(--purple-600);
            margin-bottom: 2rem;
        }

        .back-btn {
            background: var(--purple-600);
            color: white;
            border: none;
            padding: 0.75rem 1.5rem;
            border-radius: 0.75rem;
            font-weight: 700;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            transition: all 0.3s ease;
        }

        .back-btn:hover {
            background: #7d3c98;
            color: white;
            transform: translateY(-2px);
        }
    </style>
</head>
<body>
    <!-- Header -->
    <div class="dashboard-header">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <h1 class="h3 mb-2">قائمة الطلاب</h1>
                    <div class="d-flex align-items-center gap-3 flex-wrap">
                        <?php if ($college_name): ?>
                            <span class="filter-badge">الكلية: <?= htmlspecialchars($college_name) ?></span>
                        <?php endif; ?>
                        <?php if ($filter !== 'all'): ?>
                            <span class="filter-badge">
                                التصفية: 
                                <?= [
                                    'profile_complete' => 'مكتملي الملف',
                                    'profile_incomplete' => 'غير مكتملي الملف',
                                    'medical_fit' => 'لائق طبياً',
                                    'medical_unfit' => 'غير لائق',
                                    'medical_pending' => 'بانتظار الفحص',
                                    'interview_accepted' => 'مقبول في المقابلة',
                                    'interview_rejected' => 'مرفوض في المقابلة',
                                    'interview_pending' => 'قيد الانتظار'
                                ][$filter] ?? 'الكل' ?>
                            </span>
                        <?php endif; ?>
                        <span class="filter-badge">عدد الطلاب: <?= number_format(count($students)) ?></span>
                    </div>
                </div>
                <div class="col-md-6 text-md-start">
                    <a href="admin_dashboard.php" class="back-btn">
                        <i class="fas fa-arrow-right"></i> العودة للوحة التحكم
                    </a>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <?php if (isset($error_message)): ?>
            <div class="alert alert-danger"><?= htmlspecialchars($error_message) ?></div>
        <?php endif; ?>

        <!-- Search and Filters -->
        <div class="stats-card mb-4">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <form method="GET" class="d-flex gap-2">
                        <input type="hidden" name="filter" value="<?= htmlspecialchars($filter) ?>">
                        <?php if ($college_id): ?>
                            <input type="hidden" name="college" value="<?= htmlspecialchars($college_id) ?>">
                        <?php endif; ?>
                        <input type="text" name="search" class="form-control" placeholder="ابحث بالاسم أو الرقم الجامعي..." 
                               value="<?= htmlspecialchars($search) ?>">
                        <button type="submit" class="btn btn-primary">بحث</button>
                        <?php if ($search): ?>
                            <a href="?filter=<?= htmlspecialchars($filter) ?><?= $college_id ? '&college=' . $college_id : '' ?>" 
                               class="btn btn-outline-secondary">إلغاء البحث</a>
                        <?php endif; ?>
                    </form>
                </div>
                <div class="col-md-6 text-md-start">
                    <div class="btn-group">
                        <a href="?filter=all<?= $college_id ? '&college=' . $college_id : '' ?><?= $search ? '&search=' . urlencode($search) : '' ?>" 
                           class="btn btn-sm <?= $filter === 'all' ? 'btn-primary' : 'btn-outline-primary' ?>">الكل</a>
                        <a href="?filter=profile_complete<?= $college_id ? '&college=' . $college_id : '' ?><?= $search ? '&search=' . urlencode($search) : '' ?>" 
                           class="btn btn-sm <?= $filter === 'profile_complete' ? 'btn-primary' : 'btn-outline-primary' ?>">مكتمل الملف</a>
                        <a href="?filter=medical_fit<?= $college_id ? '&college=' . $college_id : '' ?><?= $search ? '&search=' . urlencode($search) : '' ?>" 
                           class="btn btn-sm <?= $filter === 'medical_fit' ? 'btn-primary' : 'btn-outline-primary' ?>">لائق طبياً</a>
                    </div>
                </div>
            </div>
        </div>

        <!-- Students Table -->
        <div class="stats-card">
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead class="table-dark">
                        <tr>
                            <th>الرقم الجامعي</th>
                            <th>اسم الطالب</th>
                            <th>الكلية</th>
                            <th>الملف الشخصي</th>
                            <th>الحالة الطبية</th>
                            <th>حالة المقابلة</th>
                            <th>المبلغ المدفوع</th>
                            <th>تاريخ التسجيل</th>
                            <th>الإجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($students)): ?>
                            <tr>
                                <td colspan="9" class="text-center py-4 text-muted">
                                    <i class="fas fa-inbox fa-2x mb-3"></i><br>
                                    لا توجد طلاب مطابقين للبحث
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($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 if ($student['medically_fit'] == 1): ?>
                                            <span class="badge bg-success">لائق</span>
                                        <?php elseif ($student['medically_fit'] == 0): ?>
                                            <span class="badge bg-danger">غير لائق</span>
                                        <?php else: ?>
                                            <span class="badge bg-warning">قيد المراجعة</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($student['interview_status'] == 'accepted'): ?>
                                            <span class="badge bg-success">مقبول</span>
                                        <?php elseif ($student['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>
                                        <?= !empty($student['created_at']) ? date('Y-m-d', strtotime($student['created_at'])) : 'غير محدد' ?>
                                    </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; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

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