<!DOCTYPE html>
<html lang="zh-Hant">
<head>
    <meta charset="UTF-8">
    <title>TTVS後台管理系統</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            padding: 20px;
            background-color: #f8f9fa;
        }
        .table-container {
            background-color: #ffffff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        #deleteSelectedBtn {
            margin-bottom: 15px;
        }
        .no-data {
            text-align: center;
            color: #6c757d;
        }
        .auth-container {
            max-width: 400px;
            margin: 0 auto;
            padding: 40px;
            background-color: #ffffff;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .auth-container h2 {
            margin-bottom: 20px;
            text-align: center;
            color: #343a40;
        }
        .filter-container {
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .filter-container input[type="date"] {
            max-width: 200px;
        }
    </style>
</head>
<body>

    <div class="container">
        <div id="authSection" class="auth-container">
            <h2>教師登入</h2>
            <form id="loginForm">
                <div class="mb-3">
                    <label for="emailInput" class="form-label">電子郵件</label>
                    <input type="email" class="form-control" id="emailInput" required>
                </div>
                <div class="mb-3">
                    <label for="passwordInput" class="form-label">密碼</label>
                    <input type="password" class="form-control" id="passwordInput" required>
                </div>
                <button type="submit" class="btn btn-primary w-100">登入</button>
            </form>
            <div id="authError" class="mt-3 text-danger text-center"></div>
        </div>
        <div id="adminSection" class="d-none">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <button id="logoutBtn" class="btn btn-secondary">登出</button>
            </div>

            <div class="table-container">
                <div class="filter-container">
                    <label for="filterDate" class="form-label mb-0">篩選日期：</label>
                    <input type="date" id="filterDate" class="form-control">
                    <button id="filterBtn" class="btn btn-primary">篩選</button>
                    <button id="clearFilterBtn" class="btn btn-secondary">清除篩選</button>
                </div>
                <div class="d-flex justify-content-between mb-3">
                    <button id="deleteSelectedBtn" class="btn btn-danger">刪除選取項目</button>
                    <button onclick="exportTableToCSV('quizResults.csv')" class="btn btn-secondary">匯出為 CSV</button>
                </div>
                <table id="quizResultsTable" class="table table-striped table-hover">
                    <thead class="table-dark">
                        <tr>
                            <th scope="col"><input type="checkbox" id="selectAll"></th>
                            <th scope="col">學號</th>
                            <th scope="col">姓名</th>
                            <th scope="col">電子郵件</th>
                            <th scope="col">章節</th>
                            <th scope="col">測驗日期</th>
                            <th scope="col">測驗時長</th>
                            <th scope="col">題數</th>
                            <th scope="col">分數</th>
                            <th scope="col">操作</th>
                        </tr>
                    </thead>
                    <tbody id="quizResultsBody">
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://www.gstatic.com/firebasejs/9.22.2/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/9.22.2/firebase-auth-compat.js"></script>

    <script src="https://www.gstatic.com/firebasejs/9.22.2/firebase-database-compat.js"></script>
    <script>

const firebaseConfig = {
  apiKey: "AIzaSyCknahg0vqFDiFYDQM1YkS4Sa6j4Eth7ro",
  authDomain: "nasirsweb.firebaseapp.com",
  databaseURL: "https://nasirsweb-default-rtdb.firebaseio.com",
  projectId: "nasirsweb",
  storageBucket: "nasirsweb.firebasestorage.app",
  messagingSenderId: "472577461049",
  appId: "1:472577461049:web:00b9cab35ce7b7401bf6e8",
  measurementId: "G-7HZ5KWXJGP"
};
        firebase.initializeApp(firebaseConfig);
        const auth = firebase.auth();
        const database = firebase.database();
        const loginForm = document.getElementById('loginForm');
        const emailInput = document.getElementById('emailInput');
        const passwordInput = document.getElementById('passwordInput');
        const authError = document.getElementById('authError');
        const authSection = document.getElementById('authSection');
        const adminSection = document.getElementById('adminSection');
        const logoutBtn = document.getElementById('logoutBtn');
        const filterDateInput = document.getElementById('filterDate');
        const filterBtn = document.getElementById('filterBtn');
        const clearFilterBtn = document.getElementById('clearFilterBtn');

        let allData = {}; 
        function formatDate(dateStr) {
            let date = new Date(dateStr);
            if (!isNaN(date)) {
                let year = date.getFullYear();
                let month = ('0' + (date.getMonth() + 1)).slice(-2);
                let day = ('0' + date.getDate()).slice(-2);
                return `${year}/${month}/${day}`;
            }
            let parts = dateStr.split('/');
            if (parts.length === 3) {
                let [month, day, year] = parts;
                if (year.length === 4) {
                    return `${year}/${month.padStart(2, '0')}/${day.padStart(2, '0')}`;
                }
            }
            return dateStr;
        }
        function fetchQuizResults() {
            const selfSelectedRef = database.ref('selfselectedtestsystem');
            selfSelectedRef.on('value', (snapshot) => {
                const data = snapshot.val();
                allData = data || {};
                populateTable(allData);
            }, (error) => {
                console.error('讀取數據失敗:', error);
            });
        }

        function populateTable(data) {
            const tbody = document.getElementById('quizResultsBody');
            tbody.innerHTML = '';

            if (!data || Object.keys(data).length === 0) {
                const row = document.createElement('tr');
                const cell = document.createElement('td');
                cell.colSpan = 10; 
                cell.className = 'no-data';
                cell.textContent = '目前沒有測驗結果。';
                row.appendChild(cell);
                tbody.appendChild(row);
                return;
            }
            Object.keys(data).forEach((chapter) => {
                const entries = data[chapter];
                Object.keys(entries).forEach((key) => {
                    const entry = entries[key];
                    const testDateFormatted = entry.測驗日期 ? formatDate(entry.測驗日期) : 'N/A';
                    const filterDate = filterDateInput.value;
                    if (filterDate) {
                        const filterDateFormatted = filterDate.replace(/-/g, '/');
                        if (testDateFormatted !== filterDateFormatted) {
                            return; 
                        }
                    }

                    const row = document.createElement('tr');
                    const selectCell = document.createElement('td');
                    const checkbox = document.createElement('input');
                    checkbox.type = 'checkbox';
                    checkbox.className = 'form-check-input delete-checkbox';
                    checkbox.dataset.chapter = chapter;
                    checkbox.dataset.key = key;
                    selectCell.appendChild(checkbox);
                    row.appendChild(selectCell);
                    const studentIDCell = document.createElement('td');
                    studentIDCell.textContent = entry.學號 || 'N/A';
                    row.appendChild(studentIDCell);

                    const nameCell = document.createElement('td');
                    nameCell.textContent = entry.姓名 || 'N/A';
                    row.appendChild(nameCell);
                    const emailCell = document.createElement('td');
                    emailCell.textContent = entry.電子郵件 || 'N/A'; 
                    row.appendChild(emailCell);
                    const chapterCell = document.createElement('td');
                    chapterCell.textContent = chapter || 'N/A';
                    row.appendChild(chapterCell);
                    const testDateCell = document.createElement('td');
                    testDateCell.textContent = testDateFormatted;
                    row.appendChild(testDateCell);
                    const testDurationCell = document.createElement('td');
                    testDurationCell.textContent = entry.測驗時長 || 'N/A';
                    row.appendChild(testDurationCell);
                    const numQuestionsCell = document.createElement('td');
                    numQuestionsCell.textContent = entry.題數 || 'N/A';
                    row.appendChild(numQuestionsCell);
                    const scoreCell = document.createElement('td');
                    scoreCell.textContent = entry.分數 ?? 'N/A'; 
                    row.appendChild(scoreCell);
                    const actionCell = document.createElement('td');
                    const deleteBtn = document.createElement('button');
                    deleteBtn.className = 'btn btn-sm btn-danger';
                    deleteBtn.textContent = '刪除';
                    deleteBtn.onclick = () => deleteEntry(chapter, key);
                    actionCell.appendChild(deleteBtn);
                    row.appendChild(actionCell);
                    tbody.appendChild(row);
                });
            });
            if (tbody.children.length === 0) {
                const row = document.createElement('tr');
                const cell = document.createElement('td');
                cell.colSpan = 10;
                cell.className = 'no-data';
                cell.textContent = '沒有符合篩選條件的測驗結果。';
                row.appendChild(cell);
                tbody.appendChild(row);
            }
        }
        function deleteEntry(chapter, key) {
            if (confirm('您確定要刪除此項目嗎？')) {
                database.ref(`selfselectedtestsystem/${chapter}/${key}`).remove()
                    .then(() => {
                        alert('刪除成功！');
                    })
                    .catch((error) => {
                        console.error('刪除失敗:', error);
                        alert('刪除失敗，請稍後再試。');
                    });
            }
        }
        function deleteSelectedEntries() {
            const checkboxes = document.querySelectorAll('.delete-checkbox:checked');
            if (checkboxes.length === 0) {
                alert('請選取至少一個項目進行刪除。');
                return;
            }

            if (!confirm(`您確定要刪除 ${checkboxes.length} 個選取項目嗎？`)) {
                return;
            }

            const promises = [];
            checkboxes.forEach((checkbox) => {
                const chapter = checkbox.dataset.chapter;
                const key = checkbox.dataset.key;
                const promise = database.ref(`selfselectedtestsystem/${chapter}/${key}`).remove();
                promises.push(promise);
            });

            Promise.all(promises)
                .then(() => {
                    alert('選取項目已成功刪除！');
                })
                .catch((error) => {
                    console.error('刪除失敗:', error);
                    alert('部分項目刪除失敗，請稍後再試。');
                });
        }
        document.getElementById('selectAll').addEventListener('change', function() {
            const checkboxes = document.querySelectorAll('.delete-checkbox');
            checkboxes.forEach((checkbox) => {
                checkbox.checked = this.checked;
            });
        });
        document.getElementById('deleteSelectedBtn').addEventListener('click', deleteSelectedEntries);
        loginForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const email = emailInput.value;
            const password = passwordInput.value;

            auth.signInWithEmailAndPassword(email, password)
                .then((userCredential) => {
                    authError.textContent = '';
                })
                .catch((error) => {
                    console.error('登入失敗:', error);
                    authError.textContent = '登入失敗：' + error.message;
                });
        });

        // 登出
        logoutBtn.addEventListener('click', function() {
            auth.signOut()
                .then(() => {
                })
                .catch((error) => {
                    console.error('登出失敗:', error);
                });
        });
        auth.onAuthStateChanged(function(user) {
            if (user) {
                const allowedEmails = ['nasir.lin@msa.hinet.net', 'it@nasify.org'];

                if (allowedEmails.includes(user.email)) {
                    authSection.classList.add('d-none');
                    adminSection.classList.remove('d-none');
                    fetchQuizResults();
                } else {
                    auth.signOut();
                    authError.textContent = '您沒有訪問此頁面的權限。';
                }
            } else {
                authSection.classList.remove('d-none');
                adminSection.classList.add('d-none');
            }
        });
        filterBtn.addEventListener('click', function() {
            populateTable(allData);
        });
        clearFilterBtn.addEventListener('click', function() {
            filterDateInput.value = '';
            populateTable(allData);
        });
        function exportTableToCSV(filename) {
            let csv = [];
            const rows = document.querySelectorAll("table tr");
            
            for (let i = 0; i < rows.length; i++) {
                const row = [], cols = rows[i].querySelectorAll("td, th");
                
                for (let j = 0; j < cols.length; j++) {
                    if (j === 0) continue; 
                    row.push('"' + cols[j].textContent.replace(/"/g, '""') + '"');
                }
                
                csv.push(row.join(","));
            }
            const csvContent = '\uFEFF' + csv.join("\n");
            const csvFile = new Blob([csvContent], {type: "text/csv;charset=utf-8;"});
            const downloadLink = document.createElement("a");
            downloadLink.download = filename;
            downloadLink.href = window.URL.createObjectURL(csvFile);
            downloadLink.style.display = "none";
            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink); 
        }
        function detectDevTools() {
            const threshold = 160;
            const isMobile = /Mobi|Android|iPhone|iPad|iPod/i.test(navigator.userAgent);
        
            if (!isMobile) {
                const isDevToolsOpen = window.outerWidth - window.innerWidth > threshold || window.outerHeight - window.innerHeight > threshold;
        
                if (isDevToolsOpen) {
                    window.location.href = 'about:blank';
                }
            }
        }
        
        document.addEventListener('keydown', (e) => {
            if (e.key === 'F12') {
                e.preventDefault();
                window.location.href = 'about:blank';
            }
        });
        document.addEventListener('keydown', (e) => {
            if ((e.ctrlKey || e.metaKey) && e.key === 's') {
                e.preventDefault();
            }
        });


    </script>
</body>
</html>
