<!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="action-section" style="margin-bottom: 10px;">
      <button id="exportCSV">匯出 CSV</button>
    </div>
    <table id="recordsTable">
      <thead>
        <tr>
          <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",
      databaseURL: "https://ntubpeo-default-rtdb.firebaseio.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 database = firebase.database();
    auth.onAuthStateChanged((user) => {
      if (!user || localStorage.getItem('isLoggedIn') !== 'true') {
        alert('請先登入！');
        window.location.href = 'index.html';
      }
    });

    const recordsTableBody = document.querySelector('#recordsTable tbody');
    const exportCSVBtn = document.getElementById('exportCSV');
    function parseTimestamp(ts) {
      if (typeof ts === 'number') {
        if (ts < 10000000000) {
          return new Date(ts * 1000);
        } else {
          return new Date(ts);
        }
      }
      return new Date(ts);
    }
    function formatDate(dateInput) {
      const date = parseTimestamp(dateInput);
      if (isNaN(date)) return dateInput;
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}/${month}/${day} ${hours}:${minutes}`;
    }
    async function fetchRecords() {
      try {
        const snapshot = await database.ref('borrow').once('value');
        const recordsObj = snapshot.val();
        let records = [];
        if (recordsObj) {
          for (let key in recordsObj) {
            records.push(recordsObj[key]);
          }
        }
        displayRecords(records);
        currentRecords = records;
      } catch (error) {
        console.error("Error:", error);
        alert("無法取得資料，請稍後再試。\n" + error.message);
      }
    }
    function displayRecords(records) {
      recordsTableBody.innerHTML = '';
      if (!Array.isArray(records) || records.length === 0) {
        const noDataRow = document.createElement('tr');
        const noDataCell = document.createElement('td');
        noDataCell.colSpan = 8;
        noDataCell.textContent = '沒有找到相關紀錄。';
        noDataRow.appendChild(noDataCell);
        recordsTableBody.appendChild(noDataRow);
        return;
      }
      records.forEach(record => {
        const row = document.createElement('tr');

        const borrowTimeCell = document.createElement('td');
        borrowTimeCell.textContent = formatDate(record.timestamp) || '';
        row.appendChild(borrowTimeCell);

        const educationCell = document.createElement('td');
        educationCell.textContent = record.education || '';
        row.appendChild(educationCell);

        const unitCell = document.createElement('td');
        unitCell.textContent = record.unit || '';
        row.appendChild(unitCell);

        const nameCell = document.createElement('td');
        nameCell.textContent = record.name || '';
        row.appendChild(nameCell);

        const phoneCell = document.createElement('td');
        phoneCell.textContent = record.phone || '';
        row.appendChild(phoneCell);

        const borrowEquipmentCell = document.createElement('td');
        borrowEquipmentCell.textContent = record.borrowEquipment || '';
        row.appendChild(borrowEquipmentCell);

        const statusCell = document.createElement('td');
        statusCell.textContent = record.keyStatus || '';
        row.appendChild(statusCell);

        const remarksCell = document.createElement('td');
        remarksCell.textContent = record.remarks || '';
        row.appendChild(remarksCell);

        recordsTableBody.appendChild(row);
      });
    }
    let currentRecords = [];
    function exportToCSV() {
      if (!currentRecords || currentRecords.length === 0) {
        alert("沒有資料可供匯出！");
        return;
      }
      const header = ["借用時間", "學制", "單位", "姓名", "電話", "借用器材", "狀態", "備註"];
      const rows = currentRecords.map(record => [
        formatDate(record.timestamp) || '',
        record.education || '',
        record.unit || '',
        record.name || '',
        record.phone || '',
        record.borrowEquipment || '',
        record.keyStatus || '',
        record.remarks || ''
      ]);
      let csvContent = header.join(",") + "\n";
      rows.forEach(row => {
        csvContent += row.map(field => `"${field}"`).join(",") + "\n";
      });
      const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
      const link = document.createElement("a");
      const url = URL.createObjectURL(blob);
      link.setAttribute("href", url);
      link.setAttribute("download", "records.csv");
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }

    exportCSVBtn.addEventListener('click', exportToCSV);
    window.onload = fetchRecords;
  </script>
</body>
</html>
