<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
    <title>Exam Attendance</title>
    <?php echo app('Illuminate\Foundation\Vite')(['resources/css/app.css', 'resources/js/app.js']); ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">
    <script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/mammoth@1.4.21/mammoth.browser.min.js"></script>
</head>
<body class="bg-gradient-to-br from-blue-50 via-white to-indigo-50 dark:from-gray-900 dark:via-gray-800 dark:to-gray-900 text-gray-900 dark:text-gray-100 min-h-screen">
    <!-- User Header -->
    <div class="bg-white dark:bg-gray-800 shadow-sm border-b border-gray-200 dark:border-gray-700">
        <div class="container mx-auto px-4 py-4 max-w-7xl">
            <div class="flex justify-between items-center">
                <div class="flex items-center space-x-4">
                    <div class="w-8 h-8 bg-gradient-to-r from-blue-500 to-purple-600 rounded-full flex items-center justify-center text-white font-semibold text-sm">
                        <?php echo e(substr(auth()->user()->name, 0, 1)); ?>

                    </div>
                    <div>
                        <p class="font-medium text-gray-900 dark:text-gray-100"><?php echo e(auth()->user()->name); ?></p>
                        <p class="text-sm text-gray-500 dark:text-gray-400 capitalize"><?php echo e(auth()->user()->role); ?></p>
                    </div>
                </div>
                <form method="POST" action="<?php echo e(route('logout')); ?>">
                    <?php echo csrf_field(); ?>
                    <button type="submit" class="inline-flex items-center px-4 py-2 bg-red-600 hover:bg-red-700 text-white text-sm font-medium rounded-lg transition-colors duration-200">
                        <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"></path>
                        </svg>
                        Logout
                    </button>
                </form>
            </div>
        </div>
    </div>

    <div class="container mx-auto px-4 py-8 max-w-7xl">
        <!-- Flash Messages -->
        <?php if(session('error')): ?>
            <div class="mb-6 bg-red-100 dark:bg-red-900 border border-red-400 dark:border-red-600 text-red-700 dark:text-red-200 px-4 py-3 rounded-lg">
                <div class="flex items-center">
                    <svg class="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
                        <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd"></path>
                    </svg>
                    <?php echo e(session('error')); ?>

                </div>
            </div>
        <?php endif; ?>

        <div class="text-center mb-10">
            <h1 class="text-4xl md:text-5xl font-bold bg-gradient-to-r from-blue-600 via-purple-600 to-indigo-600 bg-clip-text text-transparent mb-3">
                📚 Exam Attendance System
            </h1>
            <p class="text-lg text-gray-600 dark:text-gray-400 max-w-2xl mx-auto">
                Comprehensive student attendance and grade management platform
            </p>
        </div>

        <div class="grid grid-cols-1 xl:grid-cols-3 gap-8">
            <!-- Form Section -->
            <div class="xl:col-span-1">
                <div class="bg-white dark:bg-gray-800 rounded-xl shadow-xl p-6 border border-gray-100 dark:border-gray-700 backdrop-blur-sm bg-opacity-95">
                    <div class="flex items-center mb-6">
                        <div class="bg-gradient-to-r from-blue-500 to-purple-600 p-3 rounded-lg mr-4">
                            <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
                            </svg>
                        </div>
                        <div>
                            <h2 class="text-xl font-bold text-gray-800 dark:text-gray-200">Record Attendance</h2>
                            <p class="text-sm text-gray-600 dark:text-gray-400">Submit student attendance</p>
                        </div>
                    </div>

                    <form id="attendanceForm" enctype="multipart/form-data" class="space-y-5">
                        <div class="grid grid-cols-1 gap-4">
                            <div>
                                <label for="name" class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                                    Student Name <span class="text-red-500">*</span>
                                </label>
                                <input type="text" id="name" name="name" required
                                       class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-gray-100 transition-all duration-200"
                                       placeholder="Enter full name">
                            </div>

                            <div class="grid grid-cols-2 gap-3">
                                <div>
                                    <label for="class" class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                                        Class <span class="text-red-500">*</span>
                                    </label>
                                    <select id="class" name="class" required
                                            class="w-full px-3 py-3 border border-gray-300 dark:border-gray-600 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-gray-100 transition-all duration-200">
                                        <option value="">Select</option>
                                        <option value="Kelas X">Kelas X</option>
                                        <option value="Kelas XI-1">XI-1</option>
                                        <option value="Kelas XI-2">XI-2</option>
                                        <option value="Kelas XII">Kelas XII</option>
                                    </select>
                                </div>

                                <div>
                                    <label for="session" class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                                        Session <span class="text-red-500">*</span>
                                    </label>
                                    <select id="session" name="session" required
                                            class="w-full px-3 py-3 border border-gray-300 dark:border-gray-600 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-gray-100 transition-all duration-200">
                                        <option value="">Select</option>
                                        <option value="Sesi 1">Sesi 1</option>
                                        <option value="Sesi 2">Sesi 2</option>
                                        <option value="Sesi 3">Sesi 3</option>
                                        <option value="Sesi 4">Sesi 4</option>
                                    </select>
                                </div>
                            </div>

                            <?php if(in_array(auth()->user()->role, ['teacher', 'admin'])): ?>
                                <div>
                                    <label for="score" class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                                        Score <span class="text-gray-500">(Optional)</span>
                                    </label>
                                    <input type="number" id="score" name="score" min="0" max="100" step="0.01"
                                        class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-gray-100 transition-all duration-200"
                                        placeholder="0-100">
                                </div>
                            <?php endif; ?>

                            <div>
                                <label for="file" class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                                    Attachment <span class="text-red-500">*</span>
                                </label>
                                <input type="file" id="file" name="file" required accept=".pdf,.doc,.docx,.jpg,.png,.txt,.xlsx,.xls,.rtf,.log,.js,.php,.py,.java,.cpp,.html,.css,.sql,.xml,.json,.md"
                                       class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-gray-100 file:mr-4 file:py-2 file:px-4 file:rounded-l-lg file:border-0 file:text-sm file:font-semibold file:bg-gradient-to-r file:from-blue-50 file:to-purple-50 file:text-blue-700 hover:file:from-blue-100 hover:file:to-purple-100 transition-all duration-200">
                                <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">Supported: PDF, Word, Excel, Images, Text files</p>
                            </div>
                        </div>

                        <button type="submit" id="submitBtn"
                                class="w-full bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 text-white font-semibold py-3 px-6 rounded-lg transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transform hover:scale-105 shadow-lg">
                            <span class="flex items-center justify-center">
                                <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path>
                                </svg>
                                Submit Attendance
                            </span>
                        </button>
                    </form>

                    <div id="message" class="mt-4 hidden"></div>
                </div>
            </div>

            <!-- List Section -->
            <div class="xl:col-span-2">
                <div class="bg-white dark:bg-gray-800 rounded-xl shadow-xl p-6 border border-gray-100 dark:border-gray-700 backdrop-blur-sm bg-opacity-95">
                    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 gap-4">
                        <div class="flex items-center">
                            <div class="bg-gradient-to-r from-green-500 to-emerald-600 p-3 rounded-lg mr-4">
                                <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path>
                                </svg>
                            </div>
                            <div>
                                <h2 class="text-xl font-bold text-gray-800 dark:text-gray-200">Attendance Records</h2>
                                <p class="text-sm text-gray-600 dark:text-gray-400">View and manage submissions</p>
                            </div>
                        </div>

                        <div class="flex items-center space-x-3">
                            <?php if(in_array(auth()->user()->role, ['admin', 'teacher'])): ?>
                            <div class="flex items-center space-x-2 mr-4">
                                <span class="text-sm font-medium text-gray-600 dark:text-gray-400">Export:</span>
                                <button onclick="exportToExcel()" class="inline-flex items-center px-3 py-2 bg-green-600 hover:bg-green-700 text-white text-sm font-medium rounded-lg transition-colors duration-200">
                                    <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                                    </svg>
                                    Excel
                                </button>
                                <button onclick="exportToPDF()" class="inline-flex items-center px-3 py-2 bg-red-600 hover:bg-red-700 text-white text-sm font-medium rounded-lg transition-colors duration-200">
                                    <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                                    </svg>
                                    PDF
                                </button>
                            </div>
                            <?php endif; ?>

                            <div class="flex flex-col sm:flex-row gap-3">
                                <div class="flex items-center space-x-2">
                                    <span class="text-sm font-medium text-gray-600 dark:text-gray-400">Show:</span>
                                    <select id="perPage" onchange="changePerPage(this.value)"
                                            class="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200">
                                        <option value="5">5</option>
                                        <option value="10" selected>10</option>
                                        <option value="15">15</option>
                                        <option value="20">20</option>
                                        <option value="25">25</option>
                                        <option value="50">50</option>
                                        <option value="100">100</option>
                                    </select>
                                </div>

                                <div class="flex items-center space-x-2">
                                    <span class="text-sm font-medium text-gray-600 dark:text-gray-400">Filter by Class:</span>
                                    <select id="classFilter" onchange="changeClassFilter(this.value)"
                                            class="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200">
                                        <option value="">All Classes</option>
                                        <option value="Kelas X">Kelas X</option>
                                        <option value="Kelas XI-1">Kelas XI-1</option>
                                        <option value="Kelas XI-2">Kelas XI-2</option>
                                        <option value="Kelas XII">Kelas XII</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Search and Filters -->
                    <div class="bg-gray-50 dark:bg-gray-700 rounded-lg p-4 mb-6">
                        <div class="flex flex-col lg:flex-row gap-4">
                            <div class="flex-1">
                                <div class="relative">
                                    <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                                        <svg class="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                                        </svg>
                                    </div>
                                    <input type="text" id="searchInput" placeholder="Search by name, class, or session..."
                                           class="w-full pl-11 pr-11 py-3 border border-gray-300 dark:border-gray-600 rounded-lg text-sm bg-white dark:bg-gray-600 text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-400 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200">
                                    <button id="clearSearch" class="absolute inset-y-0 right-0 pr-4 flex items-center text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-200">
                                        <svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                                        </svg>
                                    </button>
                                </div>
                            </div>

                            <div class="flex flex-col sm:flex-row gap-3">
                                <div class="flex items-center space-x-2">
                                    <label for="sortBy" class="text-sm font-medium text-gray-600 dark:text-gray-400 whitespace-nowrap">Sort by:</label>
                                    <select id="sortBy" onchange="changeSorting()"
                                            class="px-3 py-3 border border-gray-300 dark:border-gray-600 rounded-lg text-sm bg-white dark:bg-gray-600 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200">
                                        <option value="created_at">Date</option>
                                        <option value="name">Name</option>
                                        <option value="class">Class</option>
                                        <option value="session">Session</option>
                                        <option value="score">Score</option>
                                    </select>
                                </div>

                                <div class="flex items-center space-x-2">
                                    <label for="sortOrder" class="text-sm font-medium text-gray-600 dark:text-gray-400 whitespace-nowrap">Order:</label>
                                    <select id="sortOrder" onchange="changeSorting()"
                                            class="px-3 py-3 border border-gray-300 dark:border-gray-600 rounded-lg text-sm bg-white dark:bg-gray-600 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200">
                                        <option value="desc">Newest</option>
                                        <option value="asc">Oldest</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div id="attendanceList" class="space-y-4">
                        <!-- Records will be loaded here -->
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- File Viewer Modal -->
    <div id="fileViewerModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50">
        <div class="flex items-center justify-center min-h-screen p-4">
            <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-hidden">
                <div class="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
                    <h3 id="modalTitle" class="text-lg font-semibold text-gray-900 dark:text-gray-100">File Viewer</h3>
                    <div class="flex items-center space-x-2">
                        <a id="downloadLink" href="#" download class="inline-flex items-center px-3 py-1 bg-gray-600 hover:bg-gray-700 text-white text-sm rounded transition-colors">
                            <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                            </svg>
                            Download
                        </a>
                        <button onclick="closeFileViewer()" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
                            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                            </svg>
                        </button>
                    </div>
                </div>
                <div id="fileContent" class="p-4 overflow-auto max-h-[70vh]">
                    <!-- File content will be loaded here -->
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Modal -->
    <div id="editModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50">
        <div class="flex items-center justify-center min-h-screen p-4">
            <div class="bg-white dark:bg-gray-800 rounded-xl shadow-xl max-w-lg w-full">
                <div class="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
                    <h3 class="text-lg font-semibold text-gray-900 dark:text-gray-100">Edit Attendance</h3>
                    <button onclick="closeEditModal()" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                        </svg>
                    </button>
                </div>

                <div class="p-6">
                    <form id="editForm" onsubmit="submitEdit(event)">
                        <input type="hidden" id="editAttendanceId" name="attendance_id">

                        <div class="grid grid-cols-1 gap-4">
                            <div>
                                <label for="editName" class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                                    Student Name <span class="text-red-500">*</span>
                                </label>
                                <input type="text" id="editName" name="name" required
                                       class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-gray-100 transition-all duration-200">
                            </div>

                            <div class="grid grid-cols-2 gap-3">
                                <div>
                                    <label for="editClass" class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                                        Class <span class="text-red-500">*</span>
                                    </label>
                                    <select id="editClass" name="class" required
                                            class="w-full px-3 py-3 border border-gray-300 dark:border-gray-600 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-gray-100 transition-all duration-200">
                                        <option value="Kelas X">Kelas X</option>
                                        <option value="Kelas XI-1">XI-1</option>
                                        <option value="Kelas XI-2">XI-2</option>
                                        <option value="Kelas XII">Kelas XII</option>
                                    </select>
                                </div>

                                <div>
                                    <label for="editSession" class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                                        Session <span class="text-red-500">*</span>
                                    </label>
                                    <select id="editSession" name="session" required
                                            class="w-full px-3 py-3 border border-gray-300 dark:border-gray-600 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-gray-100 transition-all duration-200">
                                        <option value="Sesi 1">Sesi 1</option>
                                        <option value="Sesi 2">Sesi 2</option>
                                        <option value="Sesi 3">Sesi 3</option>
                                        <option value="Sesi 4">Sesi 4</option>
                                    </select>
                                </div>
                            </div>

                            
                            <?php if(in_array(auth()->user()->role, ['teacher', 'admin'])): ?>
                                <div>
                                    <label for="editScore" class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                                        Score <span class="text-gray-500">(Optional)</span>
                                    </label>
                                    <input type="number" id="editScore" name="score" min="0" max="100" step="0.01"
                                        class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-gray-100 transition-all duration-200">
                                </div>
                            <?php endif; ?>
                        </div>

                        <div class="flex space-x-3 mt-6">
                            <button type="submit" id="editSubmitBtn"
                                    class="flex-1 bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700 text-white font-semibold py-3 px-6 rounded-lg transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transform hover:scale-105 shadow-lg">
                                <span class="flex items-center justify-center">
                                    <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                                    </svg>
                                    Update Attendance
                                </span>
                            </button>
                            <button type="button" onclick="closeEditModal()"
                                    class="px-6 py-3 bg-gray-300 dark:bg-gray-600 hover:bg-gray-400 dark:hover:bg-gray-500 text-gray-700 dark:text-gray-200 font-medium rounded-lg transition-colors duration-200">
                                Cancel
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Grading Modal -->
    <div id="gradingModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50">
        <div class="flex items-center justify-center min-h-screen p-4">
            <div class="bg-white dark:bg-gray-800 rounded-xl shadow-xl max-w-md w-full">
                <div class="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
                    <h3 class="text-lg font-semibold text-gray-900 dark:text-gray-100">Grade Assignment</h3>
                    <button onclick="closeGradingModal()" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                        </svg>
                    </button>
                </div>

                <div class="p-6">
                    <div class="mb-4">
                        <p class="text-sm text-gray-600 dark:text-gray-400">Student: <span id="gradingStudentName" class="font-medium text-gray-900 dark:text-gray-100"></span></p>
                    </div>

                    <form id="gradingForm" onsubmit="submitGrade(event)">
                        <input type="hidden" id="gradingAttendanceId" name="attendance_id">

                        <div class="mb-4">
                            <label for="gradingScore" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                Score (0-100)
                            </label>
                            <input type="number" id="gradingScore" name="score" min="0" max="100" step="0.01" required
                                   class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-green-500 dark:bg-gray-700 dark:text-gray-100 transition-all duration-200">
                        </div>

                        <div class="flex space-x-3">
                            <button type="submit" id="gradingSubmitBtn"
                                    class="flex-1 bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 text-white font-semibold py-3 px-6 rounded-lg transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 transform hover:scale-105 shadow-lg">
                                <span class="flex items-center justify-center">
                                    <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"></path>
                                    </svg>
                                    Save Grade
                                </span>
                            </button>
                            <button type="button" onclick="closeGradingModal()"
                                    class="px-6 py-3 bg-gray-300 dark:bg-gray-600 hover:bg-gray-400 dark:hover:bg-gray-500 text-gray-700 dark:text-gray-200 font-medium rounded-lg transition-colors duration-200">
                                Cancel
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script>
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    
    // User role for client-side checks
    const userRole = '<?php echo e(auth()->user()->role); ?>';
    
    $(document).ready(function() {
    
        // Load data awal
        loadAttendances(1, 10);

    // =============================
    // SEARCH (DEBOUNCE)
    // =============================
    let searchTimeout;
    $('#searchInput').on('input', function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(function() {
            performSearch();
        }, 300);
    });

    $('#clearSearch').on('click', function() {
        $('#searchInput').val('');
        performSearch();
    });

    // =============================
    // SUBMIT FORM
    // =============================
    $('#attendanceForm').on('submit', function(e) {
        e.preventDefault();
        var $submitBtn = $('#submitBtn');

        $submitBtn.prop('disabled', true).text('Submitting...');

        var formData = new FormData(this);
        $.ajax({
            url: '/api/attendances',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(data) {
                showToast('Attendance recorded successfully!', 'success');
                $('#attendanceForm')[0].reset();
                loadAttendances(1);
            },
            error: function(xhr) {
                var errorMsg = 'An error occurred.';
                if (xhr.responseJSON && xhr.responseJSON.errors) {
                    errorMsg = Object.values(xhr.responseJSON.errors)
                                      .flat()
                                      .join('<br>');
                }
                showToast(errorMsg, 'error');
            },
            complete: function() {
                $submitBtn.prop('disabled', false).text('Submit Attendance');
            }
        });
    });

}); // END DOCUMENT READY


// =============================
// FILTER & SORT FUNCTIONS
// =============================

function changePerPage(perPage) {
    loadAttendances(1, perPage);
}

function changeClassFilter(classFilter) {
    loadAttendances(1);
}

function changeSorting() {
    loadAttendances(1);
}

function performSearch() {
    loadAttendances(1);
}

function deleteAttendance(id) {
    Swal.fire({
        title: 'Are you sure?',
        text: 'You won\'t be able to revert this! This will permanently delete the attendance record.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ef4444',
        cancelButtonColor: '#6b7280',
        confirmButtonText: 'Yes, delete it!',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: '/api/attendances/' + id,
                type: 'DELETE',
                success: function(response) {
                    showToast('Attendance record deleted successfully!', 'success');
                    loadAttendances(1);
                },
                error: function(xhr) {
                    var errorMsg = 'Failed to delete attendance record.';
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        errorMsg = xhr.responseJSON.message;
                    }
                    showToast(errorMsg, 'error');
                }
            });
        }
    });
}

function viewFile(filePath, fileName) {
    var fileUrl = '/storage/' + filePath;
    var fileExtension = filePath.split('.').pop().toLowerCase();

    $('#modalTitle').text('Viewing: ' + fileName);
    $('#downloadLink').attr('href', fileUrl);
    $('#fileViewerModal').removeClass('hidden');

    var content = '';

    // Handle different file types
    if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(fileExtension)) {
        // Images
        content = '<div class="flex justify-center"><img src="' + fileUrl + '" alt="' + fileName + '" class="max-w-full max-h-[60vh] object-contain"></div>';
    } else if (fileExtension === 'pdf') {
        // PDFs
        content = '<iframe src="' + fileUrl + '" class="w-full h-[60vh]" frameborder="0"></iframe>';
    } else if (['xls', 'xlsx'].includes(fileExtension)) {
        // Excel files - use SheetJS to display as table
        content = '<div class="text-center py-4"><div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div><p class="mt-2 text-gray-600 dark:text-gray-400">Loading Excel file...</p></div>';

        fetch(fileUrl)
            .then(response => response.arrayBuffer())
            .then(data => {
                var workbook = XLSX.read(data, {type: 'array'});
                var sheetName = workbook.SheetNames[0];
                var worksheet = workbook.Sheets[sheetName];

                // Create custom HTML table that shows formulas
                var range = XLSX.utils.decode_range(worksheet['!ref']);
                var html = '<table id="excel-table" class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">';

                // Add header row with column letters
                html += '<thead class="bg-gray-50 dark:bg-gray-700"><tr>';
                html += '<th class="px-3 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">#</th>';
                for (var col = range.s.c; col <= range.e.c; col++) {
                    var colLetter = XLSX.utils.encode_col(col);
                    html += '<th class="px-3 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">' + colLetter + '</th>';
                }
                html += '</tr></thead>';

                // Add data rows
                html += '<tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">';
                for (var row = range.s.r; row <= range.e.r; row++) {
                    html += '<tr class="hover:bg-gray-50 dark:hover:bg-gray-700">';
                    // Row number
                    html += '<td class="px-3 py-2 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100">' + (row + 1) + '</td>';

                    for (var col = range.s.c; col <= range.e.c; col++) {
                        var cellAddress = XLSX.utils.encode_cell({r: row, c: col});
                        var cell = worksheet[cellAddress];

                        var cellValue = '';
                        var cellClass = 'px-3 py-2 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100';
                        var title = '';

                        if (cell) {
                            if (cell.f) {
                                // Cell has formula - show formula with value
                                cellValue = '=' + cell.f;
                                title = 'Formula: =' + cell.f + '\nValue: ' + (cell.v || cell.w || '');
                                cellClass += ' font-mono text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-900';
                            } else if (cell.v !== undefined) {
                                // Regular cell value
                                cellValue = cell.w || cell.v;
                            } else if (cell.t === 's' && cell.v) {
                                // String value
                                cellValue = cell.v;
                            }
                        }

                        html += '<td class="' + cellClass + '" title="' + title + '">' + (cellValue || '') + '</td>';
                    }
                    html += '</tr>';
                }
                html += '</tbody></table>';

                // Style the table
                var styledHtml = '<div class="overflow-auto max-h-[60vh]"><div class="mb-4 p-3 bg-blue-50 dark:bg-blue-900 border border-blue-200 dark:border-blue-800 rounded-lg">' +
                    '<p class="text-sm text-blue-800 dark:text-blue-200">' +
                    '<strong>Formula Display:</strong> Cells with formulas are shown in blue with the formula text (starting with =). ' +
                    'Hover over formula cells to see both the formula and calculated value.' +
                    '</p></div>' + html + '</div>';

                $('#fileContent').html(styledHtml);
            })
            .catch(error => {
                content = '<div class="text-center text-red-500 py-8">Unable to load Excel file. <a href="' + fileUrl + '" download class="text-blue-600 hover:text-blue-800">Download instead</a></div>';
                $('#fileContent').html(content);
            });

        return; // Exit early, content will be set by fetch promise
    } else if (['docx'].includes(fileExtension)) {
        // Word files - use mammoth.js to convert to HTML
        content = '<div class="text-center py-4"><div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div><p class="mt-2 text-gray-600 dark:text-gray-400">Loading Word document...</p></div>';

        fetch(fileUrl)
            .then(response => response.arrayBuffer())
            .then(data => {
                return mammoth.convertToHtml({arrayBuffer: data});
            })
            .then(result => {
                var styledHtml = '<div class="prose prose-sm max-w-none dark:prose-invert overflow-auto max-h-[60vh] p-4 bg-white dark:bg-gray-800 rounded border">' +
                    result.value +
                    '</div>';

                if (result.messages.length > 0) {
                    styledHtml += '<div class="mt-4 p-3 bg-yellow-100 dark:bg-yellow-900 text-yellow-800 dark:text-yellow-200 rounded text-sm">' +
                        '<strong>Conversion Notes:</strong><br>' +
                        result.messages.map(msg => msg.message).join('<br>') +
                        '</div>';
                }

                $('#fileContent').html(styledHtml);
            })
            .catch(error => {
                content = '<div class="text-center text-red-500 py-8">Unable to load Word document. <a href="' + fileUrl + '" download class="text-blue-600 hover:text-blue-800">Download instead</a></div>';
                $('#fileContent').html(content);
            });

        return; // Exit early, content will be set by fetch promise
    } else if (['doc'].includes(fileExtension)) {
        // Old Word format - not supported by mammoth.js
        content = '<div class="text-center py-8">' +
            '<div class="mb-4">' +
                '<svg class="w-16 h-16 mx-auto text-blue-500 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">' +
                    '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>' +
                '</svg>' +
            '</div>' +
            '<h3 class="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-2">Microsoft Word Document (.doc)</h3>' +
            '<p class="text-gray-600 dark:text-gray-400 mb-6">Older Word format (.doc) cannot be previewed online. Please download to view.</p>' +
            '<div class="flex flex-col sm:flex-row gap-3 justify-center">' +
                '<a href="' + fileUrl + '" download class="inline-flex items-center px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors duration-200">' +
                    '<svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">' +
                        '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>' +
                    '</svg>' +
                    'Download & Open in Word' +
                '</a>' +
                '<button onclick="closeFileViewer()" class="inline-flex items-center px-6 py-3 bg-gray-600 hover:bg-gray-700 text-white font-medium rounded-lg transition-colors duration-200">' +
                    '<svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">' +
                        '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>' +
                    '</svg>' +
                    'Close' +
                '</button>' +
            '</div>' +
        '</div>';
    } else if (['txt', 'log', 'md', 'js', 'php', 'py', 'java', 'cpp', 'html', 'css', 'sql', 'xml', 'json'].includes(fileExtension)) {
        // Text files - load and display content
        $.get(fileUrl, function(textContent) {
            content = '<pre class="bg-gray-100 dark:bg-gray-900 p-4 rounded text-sm overflow-auto max-h-[60vh] whitespace-pre-wrap">' + textContent + '</pre>';
            $('#fileContent').html(content);
        }).fail(function() {
            content = '<div class="text-center text-red-500 py-8">Unable to load text file content.</div>';
            $('#fileContent').html(content);
        });
        return; // Exit early, content will be set by AJAX callback
    } else {
        // Other files - show download message
        content = '<div class="text-center py-8"><div class="text-gray-600 dark:text-gray-400 mb-4">This file type cannot be previewed in the browser.</div><a href="' + fileUrl + '" download class="inline-flex items-center px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg"><svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path></svg>Download File</a></div>';
    }

    $('#fileContent').html(content);
}

function closeFileViewer() {
    $('#fileViewerModal').addClass('hidden');
    $('#fileContent').html('');
}

// =============================
// GRADING FUNCTIONS
// =============================
function openGradingModal(attendanceId, studentName, currentScore) {
    $('#gradingAttendanceId').val(attendanceId);
    $('#gradingStudentName').text(studentName);
    $('#gradingScore').val(currentScore);
    $('#gradingModal').removeClass('hidden');
}

function openEditModal(attendanceId, name, className, session, score) {
    $('#editAttendanceId').val(attendanceId);
    $('#editName').val(name);
    $('#editClass').val(className);
    $('#editSession').val(session);
    $('#editScore').val(score || '');
    $('#editModal').removeClass('hidden');
}

function closeEditModal() {
    $('#editModal').addClass('hidden');
    $('#editForm')[0].reset();
}

function submitEdit(event) {
    event.preventDefault();

    var attendanceId = $('#editAttendanceId').val();
    var formData = new FormData(document.getElementById('editForm'));
    var $submitBtn = $('#editSubmitBtn');

    $submitBtn.prop('disabled', true).find('span').text('Updating...');

    $.ajax({
        url: '/api/attendances/' + attendanceId,
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        headers: {
            'X-HTTP-Method-Override': 'PUT'
        },
        success: function(response) {
            showToast('Attendance record updated successfully!', 'success');
            closeEditModal();
            loadAttendances(1);
        },
        error: function(xhr) {
            var errorMsg = 'Failed to update attendance record.';
            if (xhr.responseJSON && xhr.responseJSON.errors) {
                errorMsg = Object.values(xhr.responseJSON.errors).flat().join('<br>');
            }
            showToast(errorMsg, 'error');
        },
        complete: function() {
            $submitBtn.prop('disabled', false).find('span').html(`
                <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                </svg>
                Update Attendance
            `);
        }
    });
}

function closeGradingModal() {
    $('#gradingModal').addClass('hidden');
    $('#gradingForm')[0].reset();
}

function submitGrade(event) {
    event.preventDefault();

    var attendanceId = $('#gradingAttendanceId').val();
    var score = $('#gradingScore').val();
    var $submitBtn = $('#gradingSubmitBtn');

    $submitBtn.prop('disabled', true).find('span').text('Saving...');

    $.ajax({
        url: '/api/attendances/' + attendanceId + '/score',
        type: 'PATCH',
        data: { score: score },
        success: function(response) {
            showToast('Grade saved successfully!', 'success');
            closeGradingModal();
            loadAttendances(1); // Reload the list
        },
        error: function(xhr) {
            var errorMsg = 'Failed to save grade.';
            if (xhr.responseJSON && xhr.responseJSON.message) {
                errorMsg = xhr.responseJSON.message;
            }
            showToast(errorMsg, 'error');
        },
        complete: function() {
            $submitBtn.prop('disabled', false).find('span').html(`
                <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"></path>
                </svg>
                Save Grade
            `);
        }
    });
}


// =============================
// LOAD DATA
// =============================
function loadAttendances(page = 1, perPage = 10) {

    if (!perPage) perPage = $('#perPage').val() || 10;

    var sortBy = $('#sortBy').val() || 'created_at';
    var sortOrder = $('#sortOrder').val() || 'desc';
    var search = $('#searchInput').val() || '';
    var classFilter = $('#classFilter').val() || '';

    $.get('/api/attendances?page=' + page +
          '&per_page=' + perPage +
          '&sort_by=' + sortBy +
          '&sort_order=' + sortOrder +
          '&search=' + encodeURIComponent(search) +
          '&class_filter=' + encodeURIComponent(classFilter),
        function(response) {

            var data = response.data;
            var html = '';

            if (!data || data.length === 0) {
                html = '<p class="text-gray-500 dark:text-gray-400 text-center py-8">No attendance records found.</p>';
            } else {
                data.forEach(function(att) {
                    html += `
                        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg hover:shadow-xl transition-all duration-300 border border-gray-100 dark:border-gray-700 overflow-hidden group">
                            <!-- Header with avatar and name -->
                            <div class="px-6 py-4 border-b border-gray-100 dark:border-gray-700 bg-gradient-to-r from-gray-50 to-white dark:from-gray-700 dark:to-gray-800">
                                <div class="flex items-center justify-between">
                                    <div class="flex items-center space-x-3">
                                        <div class="w-10 h-10 bg-gradient-to-r from-blue-500 to-purple-600 rounded-full flex items-center justify-center text-white font-semibold text-sm">
                                            ${att.name.charAt(0).toUpperCase()}
                                        </div>
                                        <div>
                                            <h3 class="font-bold text-gray-900 dark:text-gray-100 text-lg">${capitalizeWords(att.name)}</h3>
                                            <p class="text-sm text-gray-500 dark:text-gray-400 flex items-center">
                                                <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                                </svg>
                                                ${new Date(att.created_at).toLocaleDateString()} at ${new Date(att.created_at).toLocaleTimeString()}
                                            </p>
                                        </div>
                                    </div>
                                    <div class="flex items-center space-x-2" data-attendance-id="${att.id}" data-name="${att.name}" data-class="${att.class}" data-session="${att.session}" data-file="${att.file_path || ''}" data-score="${att.score || 0}">
                                        <!-- Buttons will be generated by JavaScript -->
                                    </div>
                                </div>
                            </div>

                            <!-- Details section -->
                            <div class="px-6 py-4">
                                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                                    <!-- Class -->
                                    <div class="bg-blue-50 dark:bg-blue-900/20 rounded-lg p-3 border border-blue-200 dark:border-blue-800">
                                        <div class="flex items-center space-x-2">
                                            <div class="p-1 bg-blue-500 rounded">
                                                <svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"></path>
                                                </svg>
                                            </div>
                                            <div>
                                                <p class="text-xs font-medium text-blue-600 dark:text-blue-400 uppercase tracking-wide">Class</p>
                                                <p class="text-sm font-semibold text-blue-900 dark:text-blue-100">${att.class}</p>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Session -->
                                    <div class="bg-green-50 dark:bg-green-900/20 rounded-lg p-3 border border-green-200 dark:border-green-800">
                                        <div class="flex items-center space-x-2">
                                            <div class="p-1 bg-green-500 rounded">
                                                <svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.746 0 3.332.477 4.5 1.253v13C19.832 18.477 18.246 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"></path>
                                                </svg>
                                            </div>
                                            <div>
                                                <p class="text-xs font-medium text-green-600 dark:text-green-400 uppercase tracking-wide">Session</p>
                                                <p class="text-sm font-semibold text-green-900 dark:text-green-100">${att.session}</p>
                                            </div>
                                        </div>
                                    </div>

                                    <?php if(in_array(auth()->user()->role, ['teacher', 'admin'])): ?>
                                    <!-- Score -->
                                    <div class="bg-yellow-50 dark:bg-yellow-900/20 rounded-lg p-3 border border-yellow-200 dark:border-yellow-800">
                                        <div class="flex items-center space-x-2">
                                            <div class="p-1 bg-yellow-500 rounded">
                                                <svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"></path>
                                                </svg>
                                            </div>
                                            <div>
                                                <p class="text-xs font-medium text-yellow-600 dark:text-yellow-400 uppercase tracking-wide">Score</p>
                                                <p class="text-sm font-semibold ${att.score ? 'text-yellow-900 dark:text-yellow-100' : 'text-gray-500 dark:text-gray-400'}">${att.score ? att.score + '/100' : 'Not graded'}</p>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>`;
                });
            }

            // PAGINATION
            if (response.last_page > 1) {
                html += `<div class="flex items-center justify-between mt-8 px-4 py-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600">`;
                html += `<div class="text-sm text-gray-600 dark:text-gray-400">Showing page ${response.current_page} of ${response.last_page}</div>`;

                html += `<div class="flex items-center space-x-1">`;

                if (response.current_page > 1) {
                    html += `<button onclick="loadAttendances(${response.current_page - 1}, ${perPage})"
                              class="px-3 py-2 text-sm font-medium text-gray-500 dark:text-gray-400 bg-white dark:bg-gray-600 border border-gray-300 dark:border-gray-500 rounded-md hover:bg-gray-50 dark:hover:bg-gray-500 transition-colors duration-200 flex items-center">
                              <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                              </svg>
                              Previous
                              </button>`;
                }

                for (var i = Math.max(1, response.current_page - 2);
                     i <= Math.min(response.last_page, response.current_page + 2);
                     i++) {
                    if (i === response.current_page) {
                        html += `<span class="px-3 py-2 text-sm font-medium text-white bg-blue-600 border border-blue-600 rounded-md">${i}</span>`;
                    } else {
                        html += `<button onclick="loadAttendances(${i}, ${perPage})"
                                  class="px-3 py-2 text-sm font-medium text-gray-500 dark:text-gray-400 bg-white dark:bg-gray-600 border border-gray-300 dark:border-gray-500 rounded-md hover:bg-gray-50 dark:hover:bg-gray-500 transition-colors duration-200">${i}</button>`;
                    }
                }

                if (response.current_page < response.last_page) {
                    html += `<button onclick="loadAttendances(${response.current_page + 1}, ${perPage})"
                              class="px-3 py-2 text-sm font-medium text-gray-500 dark:text-gray-400 bg-white dark:bg-gray-600 border border-gray-300 dark:border-gray-500 rounded-md hover:bg-gray-50 dark:hover:bg-gray-500 transition-colors duration-200 flex items-center">
                              Next
                              <svg class="w-4 h-4 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                              </svg>
                              </button>`;
                }

                html += `</div></div>`;
            }

            $('#attendanceList').html(html);

            // Generate action buttons based on user role
            generateActionButtons();

        }).fail(function() {
            $('#attendanceList').html(
                '<p class="text-red-500 dark:text-red-400 text-center py-8">Failed to load attendance records.</p>'
            );
        });
}


// =============================
// GENERATE ACTION BUTTONS
// =============================
function generateActionButtons() {
    $('[data-attendance-id]').each(function() {
        const $container = $(this);
        const attendanceId = $container.data('attendance-id');
        const name = $container.data('name');
        const className = $container.data('class');
        const session = $container.data('session');
        const filePath = $container.data('file');
        const score = $container.data('score');

        let buttonsHtml = '';

        // View File Button
        if (filePath) {
            const isDisabled = !['admin', 'teacher'].includes(userRole) ? 'disabled' : '';
            const buttonClass = ['admin', 'teacher'].includes(userRole) ? 'text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900 cursor-pointer' : 'text-gray-400 cursor-not-allowed';
            const onclick = ['admin', 'teacher'].includes(userRole) ? `viewFile('${filePath}', '${name}')` : '';
            const title = ['admin', 'teacher'].includes(userRole) ? 'View File' : 'Only admins and teachers can view files';

            buttonsHtml += `
                <button ${isDisabled} onclick="${onclick}" class="p-2 ${buttonClass} rounded-lg transition-colors duration-200" title="${title}">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                    </svg>
                </button>
            `;
        }

        // Edit Button
        const editDisabled = !['admin', 'teacher'].includes(userRole) ? 'disabled' : '';
        const editClass = ['admin', 'teacher'].includes(userRole) ? 'text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900 cursor-pointer' : 'text-gray-400 cursor-not-allowed';
        const editOnclick = ['admin', 'teacher'].includes(userRole) ? `openEditModal(${attendanceId}, '${name}', '${className}', '${session}', ${score})` : '';
        const editTitle = ['admin', 'teacher'].includes(userRole) ? 'Edit Attendance' : 'Only admins and teachers can edit records';

        buttonsHtml += `
            <button ${editDisabled} onclick="${editOnclick}" class="p-2 ${editClass} rounded-lg transition-colors duration-200" title="${editTitle}">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                </svg>
            </button>
        `;

        // Grade Button
        const gradeDisabled = !['admin', 'teacher'].includes(userRole) ? 'disabled' : '';
        const gradeClass = ['admin', 'teacher'].includes(userRole) ? 'text-green-600 hover:bg-green-50 dark:hover:bg-green-900 cursor-pointer' : 'text-gray-400 cursor-not-allowed';
        const gradeOnclick = ['admin', 'teacher'].includes(userRole) ? `openGradingModal(${attendanceId}, '${name}', ${score})` : '';
        const gradeTitle = ['admin', 'teacher'].includes(userRole) ? 'Grade Assignment' : 'Only admins and teachers can grade assignments';

        buttonsHtml += `
            <button ${gradeDisabled} onclick="${gradeOnclick}" class="p-2 ${gradeClass} rounded-lg transition-colors duration-200" title="${gradeTitle}">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"></path>
                </svg>
            </button>
        `;

        // Delete Button
        const deleteDisabled = !['admin', 'teacher'].includes(userRole) ? 'disabled' : '';
        const deleteClass = ['admin', 'teacher'].includes(userRole) ? 'text-red-600 hover:bg-red-50 dark:hover:bg-red-900 cursor-pointer' : 'text-gray-400 cursor-not-allowed';
        const deleteOnclick = ['admin', 'teacher'].includes(userRole) ? `deleteAttendance(${attendanceId})` : '';
        const deleteTitle = ['admin', 'teacher'].includes(userRole) ? 'Delete Record' : 'Only admins and teachers can delete records';

        buttonsHtml += `
            <button ${deleteDisabled} onclick="${deleteOnclick}" class="p-2 ${deleteClass} rounded-lg transition-colors duration-200" title="${deleteTitle}">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                </svg>
            </button>
        `;

        $container.html(buttonsHtml);
    });
}

// =============================
// TOAST NOTIFICATIONS
// =============================
function exportToExcel() {
    const classFilter = $('#classFilter').val() || '';
    const search = $('#searchInput').val() || '';
    const sortBy = $('#sortBy').val() || 'created_at';
    const sortOrder = $('#sortOrder').val() || 'desc';

    const url = `/api/attendances/export/excel?class_filter=${encodeURIComponent(classFilter)}&search=${encodeURIComponent(search)}&sort_by=${sortBy}&sort_order=${sortOrder}`;

    // Open in new tab for download
    window.open(url, '_blank');

    showToast('Excel export file is being generated and will download automatically.', 'success');
}

function exportToPDF() {
    const classFilter = $('#classFilter').val() || '';
    const search = $('#searchInput').val() || '';
    const sortBy = $('#sortBy').val() || 'created_at';
    const sortOrder = $('#sortOrder').val() || 'desc';

    const url = `/api/attendances/export/pdf?class_filter=${encodeURIComponent(classFilter)}&search=${encodeURIComponent(search)}&sort_by=${sortBy}&sort_order=${sortOrder}`;

    // Open in new tab for download
    window.open(url, '_blank');

    showToast('PDF export file is being generated and will download automatically.', 'success');
}

function showToast(message, type) {
    Toastify({
        text: message,
        duration: 4000,
        gravity: "top",
        position: "right",
        backgroundColor: type === 'success' ? "#10b981" : "#ef4444",
        stopOnFocus: true,
    }).showToast();
}

// Function to capitalize first letter of each word and lowercase the rest (Title Case)
function capitalizeWords(str) {
    return str.toLowerCase().replace(/\b\w/g, function(char) {
        return char.toUpperCase();
    });
}
</script>


</body>
</html><?php /**PATH C:\Users\wahyu\Documents\exam-attendance\resources\views/attendance.blade.php ENDPATH**/ ?>