<!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>
        </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 parseTimestamp(ts) {
      if (typeof ts === 'string') {
        const match = ts.match(/(\d{4})\/(\d{1,2})\/(\d{1,2})\s*(上午|下午)(\d{1,2}):(\d{1,2}):(\d{1,2})/);
        if (match) {
          const year = parseInt(match[1]);
          const month = parseInt(match[2]) - 1;
          const day = parseInt(match[3]);
          const period = match[4]; 
          let hour = parseInt(match[5]);
          const minute = parseInt(match[6]);
          const second = parseInt(match[7]);
          if (period === '下午' && hour < 12) {
            hour += 12;
          }
          if (period === '上午' && hour === 12) {
            hour = 0;
          }
          return new Date(year, month, day, hour, minute, second).getTime();
        } else {
          return 0;
        }
      } else if (typeof ts === 'number') {
        return ts;
      }
      return 0;
    }

    function formatDate(timestamp) {
      const ms = parseTimestamp(timestamp);
      if (ms === 0) return "";
      const date = new Date(ms);
      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}`;
    }

    async function fetchRecords() {
      try {
        const snapshot = await db.ref('sport').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);
          }
        }
        const unitFilter = unitInput.value.trim().toLowerCase();
        if (unitFilter) {
          records = records.filter(record => {
            return record.department && record.department.toLowerCase().includes(unitFilter);
          });
        }
        const dateRange = dateRangeSelect.value;
        if (dateRange !== 'all') {
          const days = parseInt(dateRange, 10);
          const now = Date.now();
          records = records.filter(record => {
            if (record.timestamp) {
              return now - parseTimestamp(record.timestamp) <= days * 24 * 60 * 60 * 1000;
            }
            return false;
          });
        }
        records.sort((a, b) => parseTimestamp(b.timestamp) - parseTimestamp(a.timestamp));
        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="12">資料格式錯誤。</td></tr>';
        return;
      }
      if (records.length === 0) {
        const noDataRow = document.createElement('tr');
        const noDataCell = document.createElement('td');
        noDataCell.colSpan = 12;
        noDataCell.textContent = '沒有找到相關紀錄。';
        noDataRow.appendChild(noDataCell);
        recordsTableBody.appendChild(noDataRow);
        return;
      }
      records.forEach(record => {
        const row = document.createElement('tr');
        if (record.status === '借') {
          row.classList.add('status-borrowed');
        } else if (record.status === '還') {
          row.classList.add('status-returned');
        }
        const timeCell = document.createElement('td');
        timeCell.textContent = record.timestamp ? formatDate(record.timestamp) : '';
        row.appendChild(timeCell);
        const educationCell = document.createElement('td');
        educationCell.textContent = record.education || '';
        row.appendChild(educationCell);
        const departmentCell = document.createElement('td');
        departmentCell.textContent = record.department || '';
        row.appendChild(departmentCell);

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

        // 學號
        const studentIdCell = document.createElement('td');
        studentIdCell.textContent = record.studentId || '';
        row.appendChild(studentIdCell);
        const phoneCell = document.createElement('td');
        phoneCell.textContent = record.phone || '';
        row.appendChild(phoneCell);
        const equipmentCell = document.createElement('td');
        equipmentCell.textContent = record.equipment || '';
        row.appendChild(equipmentCell);
        const otherEquipmentCell = document.createElement('td');
        otherEquipmentCell.textContent = record.otherEquipment || '';
        row.appendChild(otherEquipmentCell);
        const remarksCell = document.createElement('td');
        remarksCell.textContent = record.remarks || '';
        row.appendChild(remarksCell);
        const statusCell = document.createElement('td');
        statusCell.textContent = record.status || '';
        row.appendChild(statusCell);
        const loanCodeCell = document.createElement('td');
        loanCodeCell.textContent = record.loanCode || '';
        row.appendChild(loanCodeCell);
        const actionCell = document.createElement('td');
        const editButton = document.createElement('button');
        editButton.textContent = "編輯";
        editButton.addEventListener('click', () => {
          enableEditing(row, record);
        });
        actionCell.appendChild(editButton);
        row.appendChild(actionCell);

        recordsTableBody.appendChild(row);
      });
    }
    function enableEditing(row, record) {
      const cells = row.getElementsByTagName('td');
      const statusCell = cells[9];
      const actionCell = cells[11];
      const originalStatus = record.status;
      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);
      actionCell.innerHTML = '';
      const saveButton = document.createElement('button');
      saveButton.textContent = "保存";
      const cancelButton = document.createElement('button');
      cancelButton.textContent = "取消";
      saveButton.addEventListener('click', async () => {
        const newStatus = select.value;
        try {
          await db.ref('sport/' + record.id).update({ status: newStatus });
          statusCell.textContent = newStatus;
          record.status = newStatus;
          actionCell.innerHTML = '';
          const editBtn = document.createElement('button');
          editBtn.textContent = "編輯";
          editBtn.addEventListener('click', () => {
            enableEditing(row, record);
          });
          actionCell.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);
        }
      });
      cancelButton.addEventListener('click', () => {
        statusCell.textContent = originalStatus;
        actionCell.innerHTML = '';
        const editBtn = document.createElement('button');
        editBtn.textContent = "編輯";
        editBtn.addEventListener('click', () => {
          enableEditing(row, record);
        });
        actionCell.appendChild(editBtn);
      });

      actionCell.appendChild(saveButton);
      actionCell.appendChild(cancelButton);
    }
    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 < 11; 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', fetchRecords);
    refreshBtn.addEventListener('click', () => {
      unitInput.value = '';
      dateRangeSelect.value = '7';
      fetchRecords();
    });
    exportBtn.addEventListener('click', exportCSV);
    window.onload = () => {
      dateRangeSelect.value = '7';
      fetchRecords();
    };
  </script>
</body>
</html>
