<!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="studentId">學號查詢：</label>
      <input type="text" id="studentId" 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",
      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 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 studentIdInput = document.getElementById('studentId');
    const dateRangeSelect = document.getElementById('dateRange');
    function formatDate(input) {
      const date = new Date(input);
      if (isNaN(date)) return input;
      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}`;
    }
    function fetchRecords(studentId = '') {
      const dbRef = db.ref('club');
      if (studentId.trim() !== '') {
        dbRef.orderByChild('studentId').equalTo(studentId.trim()).once('value')
          .then(snapshot => {
            const data = snapshot.val();
            let records = [];
            if (data) {
              Object.keys(data).forEach(key => {
                let rec = data[key];
                rec.id = key;
                records.push(rec);
              });
            }
            records = filterByDate(records);
            displayRecords(records);
          })
          .catch(error => {
            console.error("Error:", error);
            alert("無法取得資料，請稍後再試。\n" + error.message);
          });
      } else {
        dbRef.once('value')
          .then(snapshot => {
            const data = snapshot.val();
            let records = [];
            if (data) {
              Object.keys(data).forEach(key => {
                let rec = data[key];
                rec.id = key;
                records.push(rec);
              });
            }
            records = filterByDate(records);
            displayRecords(records);
          })
          .catch(error => {
            console.error("Error:", error);
            alert("無法取得資料，請稍後再試。\n" + error.message);
          });
      }
    }
    function filterByDate(records) {
      const dateRange = dateRangeSelect.value;
      if (dateRange === 'all') return records;
      const days = parseInt(dateRange, 10);
      const now = Date.now();
      return records.filter(record => {
        if (record.timestamp) {
          const recTime = new Date(record.timestamp).getTime();
          return (now - recTime) <= days * 24 * 60 * 60 * 1000;
        }
        return false;
      });
    }
    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 timestampCell = document.createElement('td');
        timestampCell.textContent = record.timestamp ? formatDate(record.timestamp) : '';
        row.appendChild(timestampCell);
        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.borrowEquipment || '';
        row.appendChild(equipmentCell);
        const borrowTimeCell = document.createElement('td');
        borrowTimeCell.textContent = record.borrowTime ? formatDate(record.borrowTime) : '';
        row.appendChild(borrowTimeCell);
        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 photoCell = document.createElement('td');
        if (record.googleDriveLink) {
          const link = document.createElement('a');
          link.href = record.googleDriveLink;
          link.textContent = "查看圖片";
          link.target = "_blank";
          photoCell.appendChild(link);
        } else {
          photoCell.textContent = '無';
        }
        row.appendChild(photoCell);
        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[9];
      const opCell = 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);

      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('club/' + record.id).update({ status: newStatus });
          statusCell.textContent = newStatus;
          record.status = 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 < 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', () => {
      const studentId = studentIdInput.value;
      fetchRecords(studentId);
    });
    refreshBtn.addEventListener('click', () => {
      studentIdInput.value = '';
      fetchRecords();
    });
    exportBtn.addEventListener('click', exportCSV);
    window.onload = () => {
      fetchRecords();
    };
  </script>
</body>
</html>
