<!DOCTYPE html>
<html lang="zh-TW">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <meta name="robots" content="noindex, nofollow">
  <title>1zTeSt總管理系統</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/>
  <style>
    body {
      font-family: 'Roboto', sans-serif;
      background: #1e1e2f;
      color: #e0e0e0;
      margin: 0;
      padding-top: 80px;
      transition: background 0.5s ease;
    }
    header {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      z-index: 1100;
      background: rgba(30, 30, 47, 0.95);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
    }
    .navbar-brand {
      font-weight: 500;
      font-size: 1.5rem;
      color: #e0e0e0 !important;
    }
    .nav-link {
      color: #c0c0c0;
      cursor: pointer;
      transition: color 0.3s;
    }
    .nav-link:hover {
      color: #80b3ff;
    }
    #loginSection {
      max-width: 400px;
      margin: 120px auto;
      background: #2e2e44;
      border-radius: 8px;
      padding: 30px;
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.4);
    }
    #loginSection h2 {
      text-align: center;
      margin-bottom: 25px;
      font-weight: 500;
      color: #ffffff;
    }
    #loginSection .form-control {
      background: #3b3b55;
      border: none;
      border-radius: 6px;
      color: #e0e0e0;
    }
    #loginSection .form-control::placeholder {
      color: #a0a0a0;
    }
    #loginSection .btn-primary {
      border: none;
      border-radius: 6px;
      background: #80b3ff;
      color: #1e1e2f;
      font-weight: 500;
      transition: background 0.3s ease;
    }
    #loginSection .btn-primary:hover {
      background: #99ccff;
    }
    #mainContent {
      margin: 20px auto 40px;
      max-width: 1200px;
      padding: 0 15px;
    }
    .card {
      background: #2e2e44;
      border-radius: 8px;
      padding: 20px;
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.4);
      margin-bottom: 20px;
    }
    #pageHeader, #scorePageHeader {
      padding: 20px;
      margin-bottom: 20px;
    }
    #pageHeader h2, #scorePageHeader h2 {
      font-weight: 500;
      margin-bottom: 5px;
      color: #80b3ff;
    }
    .btn-group .btn {
      border: 1px solid #80b3ff;
      border-radius: 6px;
      background: transparent;
      color: #e0e0e0;
      transition: background 0.3s;
    }
    .btn-group .btn.active, .btn-group .btn:hover {
      background: #80b3ff;
      color: #1e1e2f;
    }
    .table-responsive {
      background: #2e2e44;
      border-radius: 8px;
      padding: 20px;
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.4);
    }
    table {
      margin-bottom: 0;
    }
    th {
      background: #80b3ff;
      color: #1e1e2f;
      font-weight: 500;
    }
    td, th {
      vertical-align: middle;
    }
    .btn {
      border-radius: 6px;
      transition: transform 0.2s ease;
    }
    .btn:hover {
      transform: scale(1.05);
    }
    .btn-danger {
      background: #e74c3c;
      border: none;
    }
    .btn-danger:hover {
      background: #c0392b;
    }
    .btn-warning {
      background: #f39c12;
      border: none;
    }
    .btn-warning:hover {
      background: #d68910;
    }
    #logoutBtn {
      border-radius: 20px;
      background: transparent;
      color: #e0e0e0;
      border: 1px solid #80b3ff;
      transition: background 0.3s;
    }
    #logoutBtn:hover {
      background: #80b3ff;
      color: #1e1e2f;
    }
    #exportAccountCsvBtn, #exportScoreCsvBtn {
      border-radius: 6px;
      background: #6c757d;
      color: #fff;
      border: none;
      padding: 6px 12px;
      margin-bottom: 10px;
      transition: background 0.3s;
    }
    #exportAccountCsvBtn:hover, #exportScoreCsvBtn:hover {
      background: #5a6268;
    }
  </style>
</head>
<body>
  <div id="loginSection" class="container animate__animated animate__fadeInDown">
    <h2>請登入</h2>
    <div class="mb-3">
      <input type="email" id="loginEmail" class="form-control" placeholder="Email">
    </div>
    <div class="mb-3">
      <input type="password" id="loginPassword" class="form-control" placeholder="密碼">
    </div>
    <div class="d-grid gap-2">
      <button id="loginBtn" class="btn btn-primary"><i class="fas fa-sign-in-alt"></i> 登入</button>
    </div>
    <div id="loginError" class="text-danger mt-2 text-center"></div>
  </div>
  <header id="mainHeader" style="display:none;">
    <nav class="navbar navbar-expand-lg">
      <div class="container-fluid">
        <a class="navbar-brand" href="#">1zTeSt總管理系統</a>
        <button class="navbar-toggler text-light" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
          <i class="fas fa-bars"></i>
        </button>
        <div class="collapse navbar-collapse" id="navbarContent">
          <ul class="navbar-nav me-auto mb-2 mb-lg-0">
            <li class="nav-item">
              <span class="nav-link" id="navAccountManage">帳號資料管理</span>
            </li>
            <li class="nav-item">
              <span class="nav-link" id="navScoreManage">總成績管理</span>
            </li>
          </ul>
          <button id="logoutBtn" class="btn"><i class="fas fa-sign-out-alt"></i> 登出</button>
        </div>
      </div>
    </nav>
  </header>
  <div class="container" id="mainContent" style="display:none;">
    <div id="accountManagePage" class="animate__animated animate__fadeIn">
      <div id="pageHeader" class="card">
        <h2 id="pageTitle">帳號資料管理</h2>
      </div>
      <div class="btn-group mb-3" role="group">
        <button type="button" class="btn btn-outline-primary active" id="btnTeacherAccount">教師帳號</button>
        <button type="button" class="btn btn-outline-primary" id="btnStudentAccount">學生帳號</button>
      </div>
      <button id="exportAccountCsvBtn" class="btn">匯出CSV</button>
      <div id="accountManageSection">
        <div class="table-responsive">
          <table class="table table-bordered" id="accountTable">
            <thead id="accountTableHead">
              <tr>
                <th>Email</th>
                <th>Password</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody id="accountTableBody">
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <div id="scoreManagePage" class="animate__animated animate__fadeIn" style="display:none;">
      <div id="scorePageHeader" class="card">
        <h2>總成績管理</h2>
      </div>
      <button id="exportScoreCsvBtn" class="btn">匯出CSV</button>
      <div id="scoreManageSection">
        <div class="table-responsive">
          <table class="table table-bordered" id="scoreTable">
            <thead>
              <tr>
                <th>教師 Email</th>
                <th>測驗日期</th>
                <th>測驗者信箱</th>
                <th>測驗者學號</th>
                <th>成績 (stuscore)</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody id="scoreTableBody">
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
  <script src="https://www.gstatic.com/firebasejs/9.17.2/firebase-app-compat.js"></script>
  <script src="https://www.gstatic.com/firebasejs/9.17.2/firebase-database-compat.js"></script>
  <script src="https://www.gstatic.com/firebasejs/9.17.2/firebase-auth-compat.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    const firebaseConfig = {
      apiKey: "AIzaSyBKAeF_zdIWnbrHhb7qLc-e4DTvNDQaSY0",
      authDomain: "oneztest.firebaseapp.com",
      databaseURL: "https://oneztest-default-rtdb.asia-southeast1.firebasedatabase.app",
      projectId: "oneztest",
      storageBucket: "oneztest.firebasestorage.app",
      messagingSenderId: "330646534360",
      appId: "1:330646534360:web:7777b951fccac43fb6bfad"
    };
    firebase.initializeApp(firebaseConfig);
    const dbMain = firebase.database();
    const auth = firebase.auth();
  </script>
  <script>
    let mode = "teacher";
    document.getElementById("loginBtn").addEventListener("click", function() {
      const email = document.getElementById("loginEmail").value.trim();
      const password = document.getElementById("loginPassword").value;
      document.getElementById("loginError").textContent = "";
      if (!email || !password) {
        document.getElementById("loginError").textContent = "請填寫完整資訊。";
        return;
      }
      auth.signInWithEmailAndPassword(email, password)
        .then(() => {
          document.getElementById("loginSection").style.display = "none";
          document.getElementById("mainHeader").style.display = "block";
          document.getElementById("mainContent").style.display = "block";
          showAccountManagePage();
          loadAccounts();
        })
        .catch(err => {
          console.error("登入錯誤：", err);
          document.getElementById("loginError").textContent = "登入失敗：" + err.message;
        });
    });
    document.getElementById("logoutBtn").addEventListener("click", function() {
      auth.signOut().then(() => {
        document.getElementById("loginSection").style.display = "block";
        document.getElementById("mainHeader").style.display = "none";
        document.getElementById("mainContent").style.display = "none";
      }).catch(err => {
        console.error("登出錯誤：", err);
      });
    });
    auth.onAuthStateChanged(user => {
      if (user) {
        document.getElementById("loginSection").style.display = "none";
        document.getElementById("mainHeader").style.display = "block";
        document.getElementById("mainContent").style.display = "block";
        showAccountManagePage();
        loadAccounts();
      } else {
        document.getElementById("loginSection").style.display = "block";
        document.getElementById("mainHeader").style.display = "none";
        document.getElementById("mainContent").style.display = "none";
      }
    });
    function loadTeacherAccountsAdmin(callback) {
      let data = {}, passData = {};
      dbMain.ref("1zTeStsys/Teacheraccount").on("child_added", snapshot => {
        data[snapshot.key] = snapshot.val();
      });
      dbMain.ref("1zTeStsys/Teacherpassword").on("child_added", snapshot => {
        passData[snapshot.key] = snapshot.val();
      });
      setTimeout(function() {
        Object.keys(data).forEach(key => {
          data[key].Teacherpassword = (passData[key] && passData[key].password) || "";
        });
        dbMain.ref("1zTeStsys/Teacheraccount").off("child_added");
        dbMain.ref("1zTeStsys/Teacherpassword").off("child_added");
        callback(data);
      }, 500);
    }
    function loadStudentAccountsAdmin(callback) {
      let data = {}, passData = {};
      dbMain.ref("1zTeStsys/Studentaccount").on("child_added", snapshot => {
        data[snapshot.key] = snapshot.val();
      });
      dbMain.ref("1zTeStsys/Studentpassword").on("child_added", snapshot => {
        passData[snapshot.key] = snapshot.val();
      });
      setTimeout(function() {
        Object.keys(data).forEach(key => {
          data[key].Studentpassword = (passData[key] && passData[key].password) || "";
        });
        dbMain.ref("1zTeStsys/Studentaccount").off("child_added");
        dbMain.ref("1zTeStsys/Studentpassword").off("child_added");
        callback(data);
      }, 500);
    }
    function renderAccountTable(dataObj) {
      const tbody = document.getElementById("accountTableBody");
      const thead = document.getElementById("accountTableHead");
      tbody.innerHTML = "";
      if (mode === "teacher") {
        thead.innerHTML = `<tr>
          <th>Email</th>
          <th>Password</th>
          <th>操作</th>
        </tr>`;
      } else {
        thead.innerHTML = `<tr>
          <th>Email</th>
          <th>姓名</th>
          <th>學號</th>
          <th>Password</th>
          <th>操作</th>
        </tr>`;
      }
      if (!dataObj || Object.keys(dataObj).length === 0) {
        tbody.innerHTML = `<tr><td colspan="${(mode === "student" ? 5 : 3)}" class="text-center">目前沒有資料</td></tr>`;
        return;
      }
      Object.keys(dataObj).forEach(key => {
        const item = dataObj[key];
        const tr = document.createElement("tr");
        const emailTd = document.createElement("td");
        emailTd.textContent = item.email || "";
        tr.appendChild(emailTd);
        if (mode === "student") {
          const nameTd = document.createElement("td");
          nameTd.textContent = item.name || "";
          tr.appendChild(nameTd);
          const stunumTd = document.createElement("td");
          stunumTd.textContent = item.stunum || "";
          tr.appendChild(stunumTd);
        }
        const passTd = document.createElement("td");
        passTd.textContent = mode === "teacher" ? (item.Teacherpassword || "") : (item.Studentpassword || "");
        tr.appendChild(passTd);
        const actionTd = document.createElement("td");
        const editBtn = document.createElement("button");
        editBtn.className = "btn btn-sm btn-primary";
        editBtn.innerHTML = '<i class="fas fa-edit"></i> 編輯';
        editBtn.onclick = function() {
          if (mode === "teacher") {
            Swal.fire({
              title: '編輯教師帳號',
              html:
                `<input id="swal-input1" class="swal2-input" placeholder="Email" value="${item.email}">
                 <input id="swal-input2" class="swal2-input" placeholder="密碼" value="${item.Teacherpassword}">`,
              focusConfirm: false,
              preConfirm: () => {
                return {
                  email: document.getElementById('swal-input1').value,
                  password: document.getElementById('swal-input2').value
                }
              }
            }).then((result) => {
              if(result.value && result.value.email && result.value.password) {
                Promise.all([
                  dbMain.ref("1zTeStsys/Teacheraccount/" + key).update({ email: result.value.email }),
                  dbMain.ref("1zTeStsys/Teacherpassword/" + key).update({ password: result.value.password })
                ])
                .then(() => { loadAccounts(); })
                .catch(err => { console.error("更新失敗：", err); });
              }
            });
          } else {
            Swal.fire({
              title: '編輯學生帳號',
              html:
                `<input id="swal-input1" class="swal2-input" placeholder="Email" value="${item.email}">
                 <input id="swal-input2" class="swal2-input" placeholder="姓名" value="${item.name}">
                 <input id="swal-input3" class="swal2-input" placeholder="學號" value="${item.stunum}">
                 <input id="swal-input4" class="swal2-input" placeholder="密碼" value="${item.Studentpassword}">`,
              focusConfirm: false,
              preConfirm: () => {
                return {
                  email: document.getElementById('swal-input1').value,
                  name: document.getElementById('swal-input2').value,
                  stunum: document.getElementById('swal-input3').value,
                  password: document.getElementById('swal-input4').value
                }
              }
            }).then((result) => {
              if(result.value && result.value.email && result.value.name && result.value.stunum && result.value.password) {
                Promise.all([
                  dbMain.ref("1zTeStsys/Studentaccount/" + key).update({ 
                    email: result.value.email,
                    name: result.value.name,
                    stunum: result.value.stunum 
                  }),
                  dbMain.ref("1zTeStsys/Studentpassword/" + key).update({ password: result.value.password })
                ])
                .then(() => { loadAccounts(); })
                .catch(err => { console.error("更新失敗：", err); });
              }
            });
          }
        };
        actionTd.appendChild(editBtn);
        const deleteBtn = document.createElement("button");
        deleteBtn.className = "btn btn-sm btn-danger";
        deleteBtn.innerHTML = '<i class="fas fa-trash-alt"></i> 刪除';
        deleteBtn.onclick = function() {
          Swal.fire({
            title: '確定要刪除該帳號？',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: '是，刪除',
            cancelButtonText: '取消'
          }).then((result) => {
            if(result.isConfirmed) {
              if (mode === "teacher") {
                Promise.all([
                  dbMain.ref("1zTeStsys/Teacheraccount/" + key).remove(),
                  dbMain.ref("1zTeStsys/Teacherpassword/" + key).remove()
                ])
                .then(() => { loadAccounts(); })
                .catch(err => { console.error("刪除失敗：", err); });
              } else {
                Promise.all([
                  dbMain.ref("1zTeStsys/Studentaccount/" + key).remove(),
                  dbMain.ref("1zTeStsys/Studentpassword/" + key).remove()
                ])
                .then(() => { loadAccounts(); })
                .catch(err => { console.error("刪除失敗：", err); });
              }
            }
          });
        };
        actionTd.appendChild(deleteBtn);
        const resetBtn = document.createElement("button");
        resetBtn.className = "btn btn-sm btn-warning";
        resetBtn.innerHTML = '<i class="fas fa-key"></i> 重設密碼';
        resetBtn.onclick = function() {
          Swal.fire({
            title: '確定要重設密碼？',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: '重設',
            cancelButtonText: '取消'
          }).then((result) => {
            if(result.isConfirmed) {
              if (mode === "teacher") {
                dbMain.ref("1zTeStsys/Teacherpassword/" + key).update({ password: "00000000" })
                  .then(() => { loadAccounts(); })
                  .catch(err => { console.error("重設失敗：", err); });
              } else {
                dbMain.ref("1zTeStsys/Studentpassword/" + key).update({ password: "00000000" })
                  .then(() => { loadAccounts(); })
                  .catch(err => { console.error("重設失敗：", err); });
              }
            }
          });
        };
        actionTd.appendChild(resetBtn);
        tr.appendChild(actionTd);
        tbody.appendChild(tr);
      });
    }
    function loadTeacherScores(callback) {
      dbMain.ref("1zTeStsys/Teacheraccount").once("value")
        .then(snapshot => {
          const teacherData = snapshot.val() || {};
          let scoresList = [];
          Object.keys(teacherData).forEach(teacherKey => {
            const teacher = teacherData[teacherKey];
            const teacherEmail = teacher.email || "";
            if (teacher.Teacherscores) {
              Object.keys(teacher.Teacherscores).forEach(scoreKey => {
                const scoreItem = teacher.Teacherscores[scoreKey];
                scoresList.push({
                  teacherKey: teacherKey,
                  scoreKey: scoreKey,
                  teacherEmail: teacherEmail,
                  data: scoreItem.data || "",
                  Studentaccount: scoreItem.Studentaccount || "",
                  stunum: scoreItem.stunum || "",
                  stuscore: scoreItem.stuscore || ""
                });
              });
            }
          });
          callback(scoresList);
        })
        .catch(err => {
          console.error("讀取教師成績失敗：", err);
        });
    }
    function renderScoreTable(scoresArray) {
      const tbody = document.getElementById("scoreTableBody");
      tbody.innerHTML = "";
      if (!scoresArray || scoresArray.length === 0) {
        tbody.innerHTML = `<tr><td colspan="6" class="text-center">目前沒有資料</td></tr>`;
        return;
      }
      scoresArray.forEach(item => {
        const tr = document.createElement("tr");
        const emailTd = document.createElement("td");
        emailTd.textContent = item.teacherEmail;
        tr.appendChild(emailTd);
        const dateTd = document.createElement("td");
        dateTd.textContent = item.data;
        tr.appendChild(dateTd);
        const stuEmailTd = document.createElement("td");
        stuEmailTd.textContent = item.Studentaccount;
        tr.appendChild(stuEmailTd);
        const stuNumTd = document.createElement("td");
        stuNumTd.textContent = item.stunum;
        tr.appendChild(stuNumTd);
        const scoreTd = document.createElement("td");
        scoreTd.textContent = item.stuscore;
        tr.appendChild(scoreTd);
        const actionTd = document.createElement("td");
        const editBtn = document.createElement("button");
        editBtn.className = "btn btn-sm btn-primary";
        editBtn.innerHTML = '<i class="fas fa-edit"></i> 編輯';
        editBtn.onclick = function() {
          Swal.fire({
            title: '編輯成績',
            html:
              `<input id="swal-input1" class="swal2-input" placeholder="測驗日期" value="${item.data}">
               <input id="swal-input2" class="swal2-input" placeholder="測驗者信箱" value="${item.Studentaccount}">
               <input id="swal-input3" class="swal2-input" placeholder="測驗者學號" value="${item.stunum}">
               <input id="swal-input4" class="swal2-input" placeholder="成績" value="${item.stuscore}">`,
            focusConfirm: false,
            preConfirm: () => {
              return {
                data: document.getElementById('swal-input1').value,
                Studentaccount: document.getElementById('swal-input2').value,
                stunum: document.getElementById('swal-input3').value,
                stuscore: document.getElementById('swal-input4').value
              }
            }
          }).then((result) => {
            if(result.value && result.value.data && result.value.Studentaccount && result.value.stunum && result.value.stuscore) {
              dbMain.ref("1zTeStsys/Teacheraccount/" + item.teacherKey + "/Teacherscores/" + item.scoreKey)
                .update({ 
                  data: result.value.data,
                  Studentaccount: result.value.Studentaccount,
                  stunum: result.value.stunum,
                  stuscore: result.value.stuscore 
                })
                .then(() => { loadScores(); })
                .catch(err => { console.error("更新成績失敗：", err); });
            }
          });
        };
        actionTd.appendChild(editBtn);
        const deleteBtn = document.createElement("button");
        deleteBtn.className = "btn btn-sm btn-danger";
        deleteBtn.innerHTML = '<i class="fas fa-trash-alt"></i> 刪除';
        deleteBtn.onclick = function() {
          Swal.fire({
            title: '確定要刪除這筆成績？',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: '是，刪除',
            cancelButtonText: '取消'
          }).then(result => {
            if(result.isConfirmed) {
              dbMain.ref("1zTeStsys/Teacheraccount/" + item.teacherKey + "/Teacherscores/" + item.scoreKey)
                .remove()
                .then(() => { loadScores(); })
                .catch(err => { console.error("刪除失敗：", err); });
            }
          });
        };
        actionTd.appendChild(deleteBtn);
        tr.appendChild(actionTd);
        tbody.appendChild(tr);
      });
    }
    function loadScores() {
      loadTeacherScores(scoresList => {
        renderScoreTable(scoresList);
      });
    }
    function showAccountManagePage() {
      document.getElementById("accountManagePage").style.display = "block";
      document.getElementById("scoreManagePage").style.display = "none";
      document.getElementById("pageTitle").textContent = (mode === "teacher" ? "教師帳號管理" : "學生帳號管理");
      loadAccounts();
    }
    function showScoreManagePage() {
      document.getElementById("accountManagePage").style.display = "none";
      document.getElementById("scoreManagePage").style.display = "block";
      loadScores();
    }
    function loadAccounts() {
      if (mode === "teacher") {
        loadTeacherAccountsAdmin(data => {
          renderAccountTable(data);
        });
      } else if (mode === "student") {
        loadStudentAccountsAdmin(data => {
          renderAccountTable(data);
        });
      }
    }
    document.getElementById("btnTeacherAccount").addEventListener("click", function() {
      mode = "teacher";
      document.getElementById("pageTitle").textContent = "教師帳號管理";
      document.getElementById("btnTeacherAccount").classList.add("active");
      document.getElementById("btnStudentAccount").classList.remove("active");
      loadAccounts();
    });
    document.getElementById("btnStudentAccount").addEventListener("click", function() {
      mode = "student";
      document.getElementById("pageTitle").textContent = "學生帳號管理";
      document.getElementById("btnStudentAccount").classList.add("active");
      document.getElementById("btnTeacherAccount").classList.remove("active");
      loadAccounts();
    });
    document.getElementById("navAccountManage").addEventListener("click", function() {
      showAccountManagePage();
    });
    document.getElementById("navScoreManage").addEventListener("click", function() {
      showScoreManagePage();
    });
    function exportTableToCSV(tableId, filename) {
      const table = document.getElementById(tableId);
      let csv = [];
      const rows = table.querySelectorAll("tr");
      rows.forEach(row => {
        const cols = row.querySelectorAll("th, td");
        let rowData = [];
        cols.forEach(col => {
          let data = col.textContent.replace(/"/g, '""');
          rowData.push('"' + data + '"');
        });
        csv.push(rowData.join(","));
      });
      const csvFile = new Blob([csv.join("\n")], { type: "text/csv" });
      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);
    }
    document.getElementById("exportAccountCsvBtn").addEventListener("click", function() {
      exportTableToCSV("accountTable", "account_data.csv");
    });
    document.getElementById("exportScoreCsvBtn").addEventListener("click", function() {
      exportTableToCSV("scoreTable", "score_data.csv");
    });
  </script>
</body>
</html>
