<?php
require_once '../../config/database.php';
require_once '../../config/auth.php';
require_once '../../config/rbac.php';
require_once '../includes/functions.php';
require_once '../includes/middleware.php';

// Check if user is instructor or admin
anyRoleMiddleware(['instructor', 'admin']);

$user = getUserContext();
$db = getDB();
$userId = $_SESSION['user_id'];

// Handle filters and search
$search = $_GET['search'] ?? '';
$exam_filter = $_GET['exam'] ?? '';
$course_filter = $_GET['course'] ?? '';
$status_filter = $_GET['status'] ?? 'pending'; // Default to pending
$priority_filter = $_GET['priority'] ?? '';
$limit = isset($_GET['limit']) ? intval($_GET['limit']) : 50;
$offset = isset($_GET['offset']) ? intval($_GET['offset']) : 0;

// Build query for submissions needing grading
$query = "
    SELECT
        ea.id as attempt_id,
        ea.student_id,
        ea.exam_id,
        ea.attempt_number,
        ea.started_at,
        ea.completed_at,
        ea.time_spent,
        ea.score,
        ea.max_score,
        ea.percentage,
        ea.is_passed,
        ea.status as attempt_status,
        e.title as exam_title,
        e.exam_type,
        e.total_points,
        e.passing_score,
        c.title as course_title,
        up.first_name,
        up.last_name,
        u.email,
        up.avatar,
        -- Calculate priority based on time since completion and question types
        CASE
            WHEN ea.completed_at IS NULL THEN 1 -- In progress (lowest priority)
            WHEN EXISTS (
                SELECT 1 FROM exam_questions eq
                JOIN questions q ON eq.question_id = q.id
                WHERE eq.exam_id = e.id AND q.question_type IN ('essay', 'short_answer', 'code', 'fill_blanks')
                AND JSON_EXTRACT(ea.answers, CONCAT('$.', eq.question_id)) IS NOT NULL
            ) THEN 3 -- Has subjective questions (high priority)
            ELSE 2 -- Only objective questions (medium priority)
        END as priority_level,
        -- Count questions needing manual grading
        (
            SELECT COUNT(*)
            FROM exam_questions eq
            JOIN questions q ON eq.question_id = q.id
            WHERE eq.exam_id = e.id AND q.question_type IN ('essay', 'short_answer', 'code', 'fill_blanks')
            AND JSON_EXTRACT(ea.answers, CONCAT('$.', eq.question_id)) IS NOT NULL
        ) as manual_questions_count,
        TIMESTAMPDIFF(HOUR, ea.completed_at, NOW()) as hours_since_completion
    FROM exam_attempts ea
    JOIN exams e ON ea.exam_id = e.id
    LEFT JOIN courses c ON e.course_id = c.id
    JOIN users u ON ea.student_id = u.id
    LEFT JOIN user_profiles up ON u.id = up.user_id
    WHERE e.instructor_id = ?
";

$params = [$userId];

// Apply filters
if (!empty($search)) {
    $query .= " AND (e.title LIKE ? OR up.first_name LIKE ? OR up.last_name LIKE ? OR u.email LIKE ?)";
    $searchTerm = "%$search%";
    $params = array_merge($params, [$searchTerm, $searchTerm, $searchTerm, $searchTerm]);
}

if (!empty($exam_filter)) {
    $query .= " AND e.id = ?";
    $params[] = $exam_filter;
}

if (!empty($course_filter)) {
    $query .= " AND e.course_id = ?";
    $params[] = $course_filter;
}

if (!empty($status_filter)) {
    switch ($status_filter) {
        case 'pending':
            $query .= " AND ea.status = 'completed' AND (
                EXISTS (
                    SELECT 1 FROM exam_questions eq
                    JOIN questions q ON eq.question_id = q.id
                    WHERE eq.exam_id = e.id AND q.question_type IN ('essay', 'short_answer', 'code', 'fill_blanks')
                    AND JSON_EXTRACT(ea.answers, CONCAT('$.', eq.question_id)) IS NOT NULL
                ) OR ea.score IS NULL
            )";
            break;
        case 'completed':
            $query .= " AND ea.status = 'completed' AND ea.score IS NOT NULL";
            break;
        case 'in_progress':
            $query .= " AND ea.status = 'in_progress'";
            break;
    }
}

if (!empty($priority_filter)) {
    $query .= " AND (
        CASE
            WHEN ea.completed_at IS NULL THEN 1
            WHEN EXISTS (
                SELECT 1 FROM exam_questions eq
                JOIN questions q ON eq.question_id = q.id
                WHERE eq.exam_id = e.id AND q.question_type IN ('essay', 'short_answer', 'code', 'fill_blanks')
                AND JSON_EXTRACT(ea.answers, CONCAT('$.', eq.question_id)) IS NOT NULL
            ) THEN 3
            ELSE 2
        END = ?
    )";
    $params[] = $priority_filter;
}

// Order by priority and completion time
$query .= " ORDER BY
    priority_level DESC,
    hours_since_completion DESC,
    ea.completed_at DESC
LIMIT " . intval($limit) . " OFFSET " . intval($offset);

// Get submissions
$stmt = $db->prepare($query);
$stmt->execute($params);
$submissions = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get filter options
$exams = $db->prepare("
    SELECT DISTINCT e.id, e.title
    FROM exams e
    JOIN exam_attempts ea ON e.id = ea.exam_id
    WHERE e.instructor_id = ?
    ORDER BY e.title
", [$userId])->fetchAll();

$courses = $db->prepare("
    SELECT DISTINCT c.id, c.title
    FROM courses c
    JOIN exams e ON c.id = e.course_id
    JOIN exam_attempts ea ON e.id = ea.exam_id
    WHERE e.instructor_id = ?
    ORDER BY c.title
", [$userId])->fetchAll();

// Get statistics
$statsQuery = "
    SELECT
        COUNT(CASE WHEN ea.status = 'completed' AND (
            EXISTS (
                SELECT 1 FROM exam_questions eq
                JOIN questions q ON eq.question_id = q.id
                WHERE eq.exam_id = e.id AND q.question_type IN ('essay', 'short_answer', 'code', 'fill_blanks')
                AND JSON_EXTRACT(ea.answers, CONCAT('$.', eq.question_id)) IS NOT NULL
            ) OR ea.score IS NULL
        ) THEN 1 END) as pending_count,
        COUNT(CASE WHEN ea.status = 'completed' AND ea.score IS NOT NULL THEN 1 END) as graded_count,
        COUNT(CASE WHEN ea.status = 'in_progress' THEN 1 END) as in_progress_count,
        COUNT(*) as total_count
    FROM exam_attempts ea
    JOIN exams e ON ea.exam_id = e.id
    WHERE e.instructor_id = ?
";

$stats = $db->prepare($statsQuery, [$userId])->fetch(PDO::FETCH_ASSOC);

// Initialize stats with default values if query failed
if (!$stats) {
    $stats = [
        'pending_count' => 0,
        'graded_count' => 0,
        'in_progress_count' => 0,
        'total_count' => 0
    ];
}

$page_title = 'Grading Queue - Mutalex Academy';
?>

<div class="admin-container">
    <div class="admin-sidebar">
        <div class="sidebar-header">
            <h2><i class="fas fa-graduation-cap me-2"></i>Mutalex Academy</h2>
            <p>Instructor Panel</p>
        </div>

        <nav class="sidebar-nav">
            <ul>
                <li><a href="../dashboard.php"><i class="fas fa-tachometer-alt me-2"></i>Dashboard</a></li>
                <li><a href="../courses/"><i class="fas fa-book me-2"></i>My Courses</a></li>
                <li><a href="../courses/new.php"><i class="fas fa-plus me-2"></i>Create Course</a></li>
                <li><a href="../questions/index.php"><i class="fas fa-question-circle me-2"></i>Question Bank</a></li>
                <li><a href="../exams/index.php"><i class="fas fa-file-alt me-2"></i>Exams</a></li>
                <li><a href="index.php" class="active"><i class="fas fa-chart-line me-2"></i>Grading</a></li>
                <li><a href="../resources.php"><i class="fas fa-folder me-2"></i>Resources</a></li>
                <li><a href="../students.php"><i class="fas fa-users me-2"></i>Students</a></li>
                <li><a href="../assignments.php"><i class="fas fa-tasks me-2"></i>Assignments</a></li>
                <li><a href="../../logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>
            </ul>
        </nav>
    </div>

    <div class="admin-main">
        <div class="admin-header">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h1>Grading Queue</h1>
                    <p class="text-muted">Review and grade student submissions</p>
                </div>
                <div class="stats-cards">
                    <div class="stat-card">
                        <div class="stat-number text-warning"><?php echo $stats['pending_count']; ?></div>
                        <div class="stat-label">Pending</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number text-success"><?php echo $stats['graded_count']; ?></div>
                        <div class="stat-label">Graded</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number text-info"><?php echo $stats['in_progress_count']; ?></div>
                        <div class="stat-label">In Progress</div>
                    </div>
                </div>
            </div>
        </div>

        <div class="admin-content">

        <!-- Filters -->
        <div class="card mb-4">
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-3">
                        <input type="text" class="form-control" name="search" placeholder="Search students, exams..."
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    <div class="col-md-2">
                        <select class="form-select" name="exam">
                            <option value="">All Exams</option>
                            <?php foreach ($exams as $exam): ?>
                                <option value="<?php echo $exam['id']; ?>" <?php echo $exam_filter == $exam['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($exam['title']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <select class="form-select" name="course">
                            <option value="">All Courses</option>
                            <?php foreach ($courses as $course): ?>
                                <option value="<?php echo $course['id']; ?>" <?php echo $course_filter == $course['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($course['title']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <select class="form-select" name="status">
                            <option value="pending" <?php echo $status_filter === 'pending' ? 'selected' : ''; ?>>Pending Review</option>
                            <option value="completed" <?php echo $status_filter === 'completed' ? 'selected' : ''; ?>>Graded</option>
                            <option value="in_progress" <?php echo $status_filter === 'in_progress' ? 'selected' : ''; ?>>In Progress</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <select class="form-select" name="priority">
                            <option value="">All Priorities</option>
                            <option value="3" <?php echo $priority_filter === '3' ? 'selected' : ''; ?>>High Priority</option>
                            <option value="2" <?php echo $priority_filter === '2' ? 'selected' : ''; ?>>Medium Priority</option>
                            <option value="1" <?php echo $priority_filter === '1' ? 'selected' : ''; ?>>Low Priority</option>
                        </select>
                    </div>
                    <div class="col-md-1">
                        <button type="submit" class="btn btn-primary w-100">Filter</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Bulk Actions -->
        <div class="card mb-4" id="bulk-actions" style="display: none;">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <span id="selected-count">0 submissions selected</span>
                    <div>
                        <button class="btn btn-outline-primary btn-sm" onclick="bulkGrade()">Bulk Grade</button>
                        <button class="btn btn-outline-secondary btn-sm" onclick="clearSelection()">Clear</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Submissions List -->
        <div class="card">
            <div class="card-body">
                <?php if (empty($submissions)): ?>
                    <div class="text-center py-5">
                        <i class="fas fa-check-circle fa-3x text-success mb-3"></i>
                        <h5>All caught up!</h5>
                        <p class="text-muted">No submissions require grading at this time.</p>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th width="40">
                                        <input type="checkbox" id="select-all">
                                    </th>
                                    <th>Student</th>
                                    <th>Exam</th>
                                    <th>Status</th>
                                    <th>Priority</th>
                                    <th>Submitted</th>
                                    <th>Score</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($submissions as $submission): ?>
                                    <tr>
                                        <td>
                                            <input type="checkbox" class="submission-checkbox"
                                                   value="<?php echo $submission['attempt_id']; ?>">
                                        </td>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <?php if ($submission['avatar']): ?>
                                                    <img src="<?php echo htmlspecialchars($submission['avatar']); ?>"
                                                         class="rounded-circle me-2" width="32" height="32" alt="Avatar">
                                                <?php else: ?>
                                                    <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center me-2"
                                                         style="width: 32px; height: 32px; font-size: 14px;">
                                                        <?php echo strtoupper(substr($submission['first_name'], 0, 1) . substr($submission['last_name'], 0, 1)); ?>
                                                    </div>
                                                <?php endif; ?>
                                                <div>
                                                    <div class="fw-bold">
                                                        <?php echo htmlspecialchars($submission['first_name'] . ' ' . $submission['last_name']); ?>
                                                    </div>
                                                    <small class="text-muted"><?php echo htmlspecialchars($submission['email']); ?></small>
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <div>
                                                <div class="fw-bold"><?php echo htmlspecialchars($submission['exam_title']); ?></div>
                                                <?php if ($submission['course_title']): ?>
                                                    <small class="text-muted"><?php echo htmlspecialchars($submission['course_title']); ?></small>
                                                <?php endif; ?>
                                                <br>
                                                <small class="text-muted">
                                                    Attempt <?php echo $submission['attempt_number']; ?> •
                                                    <?php echo $submission['manual_questions_count']; ?> manual questions
                                                </small>
                                            </div>
                                        </td>
                                        <td>
                                            <?php
                                            $statusClass = '';
                                            $statusText = '';
                                            if ($submission['attempt_status'] === 'in_progress') {
                                                $statusClass = 'warning';
                                                $statusText = 'In Progress';
                                            } elseif ($submission['score'] === null) {
                                                $statusClass = 'danger';
                                                $statusText = 'Needs Grading';
                                            } else {
                                                $statusClass = 'success';
                                                $statusText = 'Graded';
                                            }
                                            ?>
                                            <span class="badge bg-<?php echo $statusClass; ?>">
                                                <?php echo $statusText; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php
                                            $priorityClass = '';
                                            $priorityText = '';
                                            switch ($submission['priority_level']) {
                                                case 3:
                                                    $priorityClass = 'danger';
                                                    $priorityText = 'High';
                                                    break;
                                                case 2:
                                                    $priorityClass = 'warning';
                                                    $priorityText = 'Medium';
                                                    break;
                                                case 1:
                                                    $priorityClass = 'secondary';
                                                    $priorityText = 'Low';
                                                    break;
                                            }
                                            ?>
                                            <span class="badge bg-<?php echo $priorityClass; ?>">
                                                <?php echo $priorityText; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php if ($submission['completed_at']): ?>
                                                <div><?php echo date('M j, Y', strtotime($submission['completed_at'])); ?></div>
                                                <small class="text-muted"><?php echo date('g:i A', strtotime($submission['completed_at'])); ?></small>
                                                <?php if ($submission['hours_since_completion'] > 24): ?>
                                                    <br><small class="text-danger"><?php echo floor($submission['hours_since_completion'] / 24); ?> days ago</small>
                                                <?php elseif ($submission['hours_since_completion'] > 1): ?>
                                                    <br><small class="text-warning"><?php echo $submission['hours_since_completion']; ?> hours ago</small>
                                                <?php endif; ?>
                                            <?php else: ?>
                                                <span class="text-muted">Not completed</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($submission['score'] !== null): ?>
                                                <div class="fw-bold">
                                                    <?php echo round($submission['percentage'], 1); ?>%
                                                </div>
                                                <small class="text-muted">
                                                    <?php echo $submission['score']; ?>/<?php echo $submission['max_score']; ?>
                                                </small>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <div class="btn-group" role="group">
                                                <a href="grade.php?id=<?php echo $submission['attempt_id']; ?>"
                                                   class="btn btn-sm btn-outline-primary">
                                                    <i class="fas fa-edit me-1"></i>Grade
                                                </a>
                                                <div class="dropdown">
                                                    <button class="btn btn-sm btn-outline-secondary dropdown-toggle"
                                                            type="button" data-bs-toggle="dropdown">
                                                        <i class="fas fa-ellipsis-v"></i>
                                                    </button>
                                                    <ul class="dropdown-menu">
                                                        <li><a class="dropdown-item" href="#" onclick="viewSubmission(<?php echo $submission['attempt_id']; ?>)">
                                                            <i class="fas fa-eye me-2"></i>View Details
                                                        </a></li>
                                                        <li><a class="dropdown-item" href="#" onclick="downloadSubmission(<?php echo $submission['attempt_id']; ?>)">
                                                            <i class="fas fa-download me-2"></i>Download
                                                        </a></li>
                                                        <li><hr class="dropdown-divider"></li>
                                                        <li><a class="dropdown-item text-danger" href="#" onclick="flagSubmission(<?php echo $submission['attempt_id']; ?>)">
                                                            <i class="fas fa-flag me-2"></i>Flag for Review
                                                        </a></li>
                                                    </ul>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination -->
                    <nav aria-label="Page navigation" class="mt-4">
                        <ul class="pagination justify-content-center">
                            <li class="page-item <?php echo $offset == 0 ? 'disabled' : ''; ?>">
                                <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['offset' => max(0, $offset - $limit)])); ?>">
                                    Previous
                                </a>
                            </li>
                            <li class="page-item">
                                <span class="page-link">
                                    Page <?php echo floor($offset / $limit) + 1; ?>
                                </span>
                            </li>
                            <li class="page-item">
                                <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['offset' => $offset + $limit])); ?>">
                                    Next
                                </a>
                            </li>
                        </ul>
                    </nav>
                <?php endif; ?>
            </div>
        </div>
    </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Select all checkbox
    document.getElementById('select-all').addEventListener('change', function() {
        const checkboxes = document.querySelectorAll('.submission-checkbox');
        checkboxes.forEach(cb => cb.checked = this.checked);
        updateBulkActions();
    });

    // Individual checkboxes
    document.addEventListener('change', function(e) {
        if (e.target.classList.contains('submission-checkbox')) {
            updateBulkActions();
        }
    });
});

function updateBulkActions() {
    const checkedBoxes = document.querySelectorAll('.submission-checkbox:checked');
    const bulkActions = document.getElementById('bulk-actions');
    const selectedCount = document.getElementById('selected-count');

    if (checkedBoxes.length > 0) {
        bulkActions.style.display = 'block';
        selectedCount.textContent = checkedBoxes.length + ' submission' + (checkedBoxes.length > 1 ? 's' : '') + ' selected';
    } else {
        bulkActions.style.display = 'none';
    }
}

function bulkGrade() {
    const selectedIds = Array.from(document.querySelectorAll('.submission-checkbox:checked')).map(cb => cb.value);

    if (selectedIds.length === 0) {
        alert('Please select submissions to grade');
        return;
    }

    if (confirm('Grade ' + selectedIds.length + ' submission(s) with default scores?')) {
        // Implement bulk grading
        alert('Bulk grading functionality will be implemented');
    }
}

function clearSelection() {
    document.querySelectorAll('.submission-checkbox').forEach(cb => cb.checked = false);
    document.getElementById('select-all').checked = false;
    updateBulkActions();
}

function viewSubmission(attemptId) {
    window.open('view.php?id=' + attemptId, '_blank');
}

function downloadSubmission(attemptId) {
    // Implement download functionality
    alert('Download functionality will be implemented');
}

function flagSubmission(attemptId) {
    if (confirm('Flag this submission for additional review?')) {
        // Implement flagging functionality
        alert('Flagging functionality will be implemented');
    }
}
</script>

<style>
/* Custom styles for Grading Index page */
.admin-container {
    display: flex;
    min-height: 100vh;
    background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
}

.admin-sidebar {
    width: 280px;
    background: linear-gradient(135deg, #1e293b 0%, #334155 100%);
    color: white;
    position: fixed;
    height: 100vh;
    overflow-y: auto;
    box-shadow: 4px 0 15px rgba(0, 0, 0, 0.1);
    z-index: 1000;
}

.sidebar-header {
    padding: 2rem 1.5rem;
    border-bottom: 1px solid #374151;
    text-align: center;
}

.sidebar-header h2 {
    font-size: 1.5rem;
    font-weight: 800;
    margin-bottom: 0.5rem;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
}

.sidebar-nav ul {
    list-style: none;
    padding: 0;
    margin: 0;
}

.sidebar-nav li a {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    padding: 1rem 1.5rem;
    color: #cbd5e1;
    text-decoration: none;
    transition: all 0.3s ease;
    font-weight: 500;
    border-left: 3px solid transparent;
}

.sidebar-nav li a:hover,
.sidebar-nav li a.active {
    background: linear-gradient(135deg, #374151 0%, #4b5563 100%);
    color: white;
    border-left-color: #3b82f6;
    transform: translateX(5px);
}

.admin-main {
    margin-left: 280px;
    margin-top: 80px;
    flex: 1;
    min-height: 100vh;
}

.admin-header {
    background: white;
    padding: 2rem;
    border-bottom: 1px solid #e5e7eb;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.admin-header h1 {
    font-size: 2rem;
    font-weight: 800;
    color: #1f2937;
    margin-bottom: 0.5rem;
    display: flex;
    align-items: center;
    gap: 0.75rem;
}

.header-actions {
    display: flex;
    gap: 1rem;
    align-items: center;
}

.admin-content {
    padding: 2rem;
}

/* Modern Professional Styling for Grading Queue */

/* Statistics Cards */
.stats-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 1.5rem;
    margin-top: 1rem;
}

.stat-card {
    background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
    border-radius: 16px;
    padding: 2rem;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
    border: 1px solid rgba(255, 255, 255, 0.8);
    text-align: center;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.stat-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
}

.stat-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 12px 40px rgba(0, 0, 0, 0.12);
}

.stat-card:nth-child(2)::before {
    background: linear-gradient(90deg, #f093fb 0%, #f5576c 100%);
}

.stat-card:nth-child(3)::before {
    background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
}

.stat-number {
    font-size: 2.5rem;
    font-weight: 800;
    color: #1f2937;
    margin-bottom: 0.5rem;
    display: block;
}

.stat-label {
    font-size: 0.95rem;
    font-weight: 600;
    color: #6b7280;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

/* Cards */
.card {
    background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
    border: 1px solid rgba(255, 255, 255, 0.8);
    overflow: hidden;
    margin-bottom: 2rem;
}

.card-body {
    padding: 2rem;
}

/* Form Elements */
.form-control, .form-select {
    border: 2px solid #e5e7eb;
    border-radius: 12px;
    padding: 0.75rem 1rem;
    font-size: 0.95rem;
    transition: all 0.3s ease;
    background: #ffffff;
}

.form-control:focus, .form-select:focus {
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    outline: none;
}

.btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    border-radius: 12px;
    padding: 0.75rem 2rem;
    font-weight: 600;
    font-size: 0.95rem;
    transition: all 0.3s ease;
    box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
    background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%);
}

/* Table Styling */
.table-responsive {
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}

.table {
    margin-bottom: 0;
    background: white;
}

.table thead th {
    background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
    border: none;
    padding: 1.25rem 1rem;
    font-weight: 700;
    font-size: 0.875rem;
    color: #374151;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    position: sticky;
    top: 0;
    z-index: 10;
}

.table tbody td {
    padding: 1.25rem 1rem;
    border-bottom: 1px solid #f3f4f6;
    vertical-align: middle;
    color: #374151;
}

.table tbody tr {
    transition: all 0.3s ease;
}

.table tbody tr:hover {
    background: linear-gradient(135deg, #f8fafc 0%, #f0f4f8 100%);
    transform: scale(1.005);
}

/* Badge Styling */
.badge {
    font-weight: 600;
    padding: 0.5rem 1rem;
    border-radius: 20px;
    font-size: 0.8rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.bg-success {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%) !important;
    color: white;
}

.bg-warning {
    background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%) !important;
    color: white;
}

.bg-danger {
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%) !important;
    color: white;
}

.bg-info {
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%) !important;
    color: white;
}

.bg-secondary {
    background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%) !important;
    color: white;
}

/* Button Groups */
.btn-group .btn {
    border-radius: 8px !important;
    margin-right: 0.5rem;
    font-weight: 500;
    transition: all 0.3s ease;
}

.btn-outline-primary {
    border: 2px solid #667eea;
    color: #667eea;
    background: transparent;
}

.btn-outline-primary:hover {
    background: #667eea;
    color: white;
    transform: translateY(-1px);
}

.btn-outline-secondary {
    border: 2px solid #6b7280;
    color: #6b7280;
    background: transparent;
}

.btn-outline-secondary:hover {
    background: #6b7280;
    color: white;
    transform: translateY(-1px);
}

/* Progress Bar */
.progress-bar {
    height: 8px;
    background: #e9ecef;
    border-radius: 4px;
    overflow: hidden;
    margin: 0.5rem 0;
}

.progress-fill {
    height: 100%;
    background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
    transition: width 0.3s ease;
    border-radius: 4px;
}

/* Empty State */
.text-center.py-5 {
    padding: 4rem 2rem;
}

.text-center.py-5 i {
    width: 80px;
    height: 80px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 2rem;
    margin: 0 auto 2rem;
    box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
}

.text-center.py-5 h5 {
    font-size: 1.5rem;
    font-weight: 700;
    color: #1f2937;
    margin-bottom: 1rem;
}

/* Pagination */
.pagination {
    margin-top: 2rem;
}

.page-link {
    border: none;
    border-radius: 8px;
    padding: 0.75rem 1rem;
    margin: 0 0.25rem;
    color: #6b7280;
    background: white;
    transition: all 0.3s ease;
}

.page-link:hover {
    background: #f8fafc;
    color: #374151;
    transform: translateY(-1px);
}

.page-item.active .page-link {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

/* Bulk Actions */
#bulk-actions {
    background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
    border: 1px solid #f59e0b;
    border-radius: 12px;
    margin-bottom: 2rem;
}

#bulk-actions .card-body {
    padding: 1.5rem;
}

/* Responsive Design */
@media (max-width: 1024px) {
    .admin-sidebar {
        transform: translateX(-100%);
        transition: transform 0.3s ease;
    }

    .admin-main {
        margin-left: 0;
    }
}

@media (max-width: 768px) {
    .admin-content {
        padding: 1rem !important;
    }

    .card-body {
        padding: 1.5rem;
    }

    .stats-cards {
        grid-template-columns: 1fr;
        gap: 1rem;
    }

    .stat-card {
        padding: 1.5rem;
    }

    .stat-number {
        font-size: 2rem;
    }

    .table-responsive {
        font-size: 0.875rem;
    }

    .table thead th,
    .table tbody td {
        padding: 0.75rem 0.5rem;
    }

    .btn-group {
        flex-direction: column;
        gap: 0.25rem;
    }

    .btn-group .btn {
        margin-right: 0;
        width: 100%;
    }
}

@media (max-width: 640px) {
    .admin-header {
        flex-direction: column;
        align-items: flex-start !important;
        gap: 1rem;
    }

    .stats-cards {
        margin-top: 0;
    }

    .filter-row {
        flex-direction: column;
        gap: 1rem;
    }

    .filter-row > div {
        width: 100%;
    }
}

/* Animation for loading states */
@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.card {
    animation: fadeIn 0.5s ease-out;
}

/* Custom scrollbar */
.table-responsive::-webkit-scrollbar {
    height: 8px;
}

.table-responsive::-webkit-scrollbar-track {
    background: #f1f5f9;
    border-radius: 4px;
}

.table-responsive::-webkit-scrollbar-thumb {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 4px;
}

.table-responsive::-webkit-scrollbar-thumb:hover {
    background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%);
}
</style>