<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>國立臺北商業大學 體育器材管理系統</title>
    <link rel="stylesheet" href="css/content.css">
    <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-auth.js"></script>
    <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-database.js"></script>
</head>
<body>
    <header>
        <h1>體育課程借用登記紀錄查看</h1>
    </header>
    <div class="container">
        <div class="search-section">
            <label for="unit">單位查詢：</label>
            <input type="text" id="unit" placeholder="請輸入單位名稱">
            
            <label for="dateRange">日期篩選：</label>
            <select id="dateRange">
                <option value="7">近7天</option>
                <option value="30">近30天</option>
                <option value="365">近1年</option>
                <option value="all">所有資料</option>
            </select>
            
            <button id="searchBtn">查詢</button>
            <button id="refreshBtn">刷新</button>
            <button id="exportBtn">匯出成 CSV</button>
        </div>
        <table id="recordsTable">
            <thead>
                <tr>
                    <th>借閱時間</th>
                    <th>學制</th>
                    <th>科系</th>
                    <th>姓名</th>
                    <th>學號</th>
                    <th>電話</th>
                    <th>器材</th>
                    <th>確認器材數量</th>
                    <th>其他器材</th>
                    <th>備註</th>
                    <th>借閱狀態</th>
                    <th>圖片連結</th>
                    <th>借閱代碼</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
    <footer>
        國立臺北商業大學 Copyright 2024 納啟科技
    </footer>
    <script>
        const firebaseConfig = {
            apiKey: "AIzaSyCgs6j97oCJerFvnZ1penbVIMhxzSMIEao",
            authDomain: "ntubpeo.firebaseapp.com",
            projectId: "ntubpeo",
            storageBucket: "ntubpeo.firebasestorage.app",
            messagingSenderId: "106907057442",
            appId: "1:106907057442:web:35e0193bdc2a3747faf97b",
            measurementId: "G-CKE0E1XM9L"
        };
        firebase.initializeApp(firebaseConfig);
        const auth = firebase.auth();
        const db = firebase.database();
        function checkLoginStatus() {
            auth.onAuthStateChanged((user) => {
                if (!user || localStorage.getItem('isLoggedIn') !== 'true') {
                    alert('請先登入！');
                    window.location.href = 'index.html';
                }
            });
        }
        document.addEventListener('DOMContentLoaded', checkLoginStatus);
        const recordsTableBody = document.querySelector('#recordsTable tbody');
        const searchBtn = document.getElementById('searchBtn');
        const refreshBtn = document.getElementById('refreshBtn');
        const exportBtn = document.getElementById('exportBtn');
        const unitInput = document.getElementById('unit');
        const dateRangeSelect = document.getElementById('dateRange');
        function formatDate(dateString) {
            const date = new Date(dateString);
            if (isNaN(date)) return dateString;
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}/${month}/${day}`;
        }
        function getCombinedRecords(records) {
            if (!Array.isArray(records)) return records;
            records.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
            const recordsMap = new Map();
            records.forEach(record => {
                const borrowCode = record.borrowCode;
                if (!borrowCode) return;
                if (!recordsMap.has(borrowCode)) {
                    recordsMap.set(borrowCode, { oldest: record, latest: record });
                } else {
                    const existing = recordsMap.get(borrowCode);
                    if (new Date(record.timestamp) > new Date(existing.latest.timestamp)) {
                        existing.latest = record;
                    }
                    recordsMap.set(borrowCode, existing);
                }
            });
            const combinedRecords = [];
            recordsMap.forEach(({ oldest, latest }) => {
                const combined = {
                    '借閱時間': latest.timestamp || '',
                    '學制': oldest.education || '',
                    '科系': oldest.department || '',
                    '姓名': oldest.name || '',
                    '學號': oldest.studentId || '',
                    '電話': oldest.phone || '',
                    '器材': latest.equipment || '',
                    '確認器材數量': latest.equipmentConfirm || '',
                    '其他器材': latest.otherEquipment || '',
                    '備註': latest.備註 || '',
                    '借閱狀態': latest.status || '',
                    '圖片連結': latest.googleDriveLink || '',
                    '借閱代碼': latest.borrowCode || '',
                    'id': latest.id || '' 
                };
                combinedRecords.push(combined);
            });
            return combinedRecords;
        }
        async function fetchRecords(unit = '') {
            try {
                const snapshot = await db.ref('records').once('value');
                const data = snapshot.val();
                let records = [];
                if (data) {
                    for (let key in data) {
                        let record = data[key];
                        record.id = key;
                        records.push(record);
                    }
                }
                if (unit.trim() !== '') {
                    records = records.filter(record => {
                        return record.department && record.department.toLowerCase().includes(unit.trim().toLowerCase());
                    });
                }
                records = getCombinedRecords(records);
                const dateRange = dateRangeSelect.value;
                if (dateRange !== 'all') {
                    const days = parseInt(dateRange, 10);
                    const now = Date.now();
                    records = records.filter(record => {
                        const recDate = new Date(record['借閱時間']).getTime();
                        return now - recDate <= days * 24 * 60 * 60 * 1000;
                    });
                }
                displayRecords(records);
            } catch (error) {
                console.error("Error:", error);
                alert("無法取得資料，請稍後再試。\n" + error.message);
            }
        }
        function displayRecords(records) {
            recordsTableBody.innerHTML = '';
            if (!Array.isArray(records)) {
                recordsTableBody.innerHTML = '<tr><td colspan="14">資料格式錯誤。</td></tr>';
                return;
            }
            if (records.length === 0) {
                const noDataRow = document.createElement('tr');
                const noDataCell = document.createElement('td');
                noDataCell.colSpan = 14;
                noDataCell.textContent = '沒有找到相關紀錄。';
                noDataRow.appendChild(noDataCell);
                recordsTableBody.appendChild(noDataRow);
                return;
            }
            records.forEach(record => {
                const row = document.createElement('tr');
                if (record['借閱狀態'] === '借') {
                    row.classList.add('status-borrowed');
                } else if (record['借閱狀態'] === '還') {
                    row.classList.add('status-returned');
                }
                const fields = [
                    { key: '借閱時間', label: '借閱時間' },
                    { key: '學制', label: '學制' },
                    { key: '科系', label: '科系' },
                    { key: '姓名', label: '姓名' },
                    { key: '學號', label: '學號' },
                    { key: '電話', label: '電話' },
                    { key: '器材', label: '器材' },
                    { key: '確認器材數量', label: '確認器材數量' },
                    { key: '其他器材', label: '其他器材' },
                    { key: '備註', label: '備註' },
                    { key: '借閱狀態', label: '借閱狀態' },
                    { key: '圖片連結', label: '圖片連結' },
                    { key: '借閱代碼', label: '借閱代碼' }
                ];
                fields.forEach(field => {
                    const cell = document.createElement('td');
                    if (field.key === '圖片連結' && record['圖片連結']) {
                        const link = document.createElement('a');
                        link.href = record['圖片連結'];
                        link.textContent = "查看圖片";
                        link.target = "_blank";
                        cell.appendChild(link);
                    } else if (field.key === '借閱時間') {
                        cell.textContent = formatDate(record['借閱時間']) || '無';
                    } else {
                        cell.textContent = record[field.key] || '無';
                    }
                    row.appendChild(cell);
                });
                const opCell = document.createElement('td');
                const editBtn = document.createElement('button');
                editBtn.textContent = "編輯";
                editBtn.addEventListener('click', () => {
                    enableEditing(row, record);
                });
                opCell.appendChild(editBtn);
                row.appendChild(opCell);

                recordsTableBody.appendChild(row);
            });
        }
        function enableEditing(row, record) {
            const cells = row.getElementsByTagName('td');
            const statusCell = cells[10];
            const opCell = cells[13];
            const originalStatus = record['借閱狀態'];
            const select = document.createElement('select');
            const optionBorrow = document.createElement('option');
            optionBorrow.value = "借";
            optionBorrow.textContent = "借";
            const optionReturn = document.createElement('option');
            optionReturn.value = "還";
            optionReturn.textContent = "還";
            select.appendChild(optionBorrow);
            select.appendChild(optionReturn);
            select.value = originalStatus;
            statusCell.innerHTML = '';
            statusCell.appendChild(select);

            opCell.innerHTML = '';
            const saveBtn = document.createElement('button');
            saveBtn.textContent = "保存";
            const cancelBtn = document.createElement('button');
            cancelBtn.textContent = "取消";

            saveBtn.addEventListener('click', async () => {
                const newStatus = select.value;
                try {
                    await db.ref('records/' + record.id).update({ status: newStatus });
                    statusCell.textContent = newStatus;
                    record['借閱狀態'] = newStatus;
                    opCell.innerHTML = '';
                    const editBtn = document.createElement('button');
                    editBtn.textContent = "編輯";
                    editBtn.addEventListener('click', () => {
                        enableEditing(row, record);
                    });
                    opCell.appendChild(editBtn);
                    row.classList.remove('status-borrowed', 'status-returned');
                    if(newStatus === '借') {
                        row.classList.add('status-borrowed');
                    } else if(newStatus === '還') {
                        row.classList.add('status-returned');
                    }
                } catch (error) {
                    alert("更新失敗：" + error.message);
                }
            });

            cancelBtn.addEventListener('click', () => {
                statusCell.textContent = originalStatus;
                opCell.innerHTML = '';
                const editBtn = document.createElement('button');
                editBtn.textContent = "編輯";
                editBtn.addEventListener('click', () => {
                    enableEditing(row, record);
                });
                opCell.appendChild(editBtn);
            });

            opCell.appendChild(saveBtn);
            opCell.appendChild(cancelBtn);
        }
        function exportCSV() {
            let csvContent = "data:text/csv;charset=utf-8,";
            csvContent += "借閱時間,學制,科系,姓名,學號,電話,器材,確認器材數量,其他器材,備註,借閱狀態,圖片連結,借閱代碼\n";
            const rows = recordsTableBody.querySelectorAll('tr');
            rows.forEach(row => {
                const cells = row.querySelectorAll('td');
                let rowData = [];
                for (let i = 0; i < 13; i++) {
                    let cellText = cells[i].textContent.replace(/"/g, '""');
                    rowData.push('"' + cellText + '"');
                }
                csvContent += rowData.join(",") + "\n";
            });
            const encodedUri = encodeURI(csvContent);
            const link = document.createElement("a");
            link.setAttribute("href", encodedUri);
            const now = new Date();
            const filename = `records_${now.getFullYear()}-${now.getMonth()+1}-${now.getDate()}.csv`;
            link.setAttribute("download", filename);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
        searchBtn.addEventListener('click', () => {
            const unit = unitInput.value.trim();
            fetchRecords(unit);
        });

        refreshBtn.addEventListener('click', () => {
            unitInput.value = '';
            fetchRecords();
        });

        exportBtn.addEventListener('click', exportCSV);
        fetchRecords();
    </script>
</body>
</html>
