<!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>NasifyTech後台管理系統</title>
  <script async src="https://www.googletagmanager.com/gtag/js?id=G-286HZQTWFH"></script>
  <script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', 'G-286HZQTWFH');
  </script>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    *, *::before, *::after {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    :root {
      --primary-color: #333;
      --secondary-color: #555;
      --accent-color: #ae7d2f;
      --background-color: #f9f9f9;
      --header-height: 70px;
      --transition-speed: 0.3s;
      --font-family-primary: 'Noto Sans TC', sans-serif;
      --font-family-secondary: 'Exo 2', sans-serif;
    }

    body {
      font-family: var(--font-family-primary);
      color: var(--primary-color);
      background-color: #fff;
      line-height: 1.6;
      overflow-x: hidden;
    }

    a {
      color: var(--primary-color);
      text-decoration: none;
      transition: color var(--transition-speed) ease;
    }
    a:hover {
      color: var(--secondary-color);
    }

    img {
      max-width: 100%;
      height: auto;
      display: block;
      margin: 0 auto;
    }

    header {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      background: rgba(255, 255, 255, 0.95);
      padding: 15px 0;
      z-index: 1000;
      transition: background var(--transition-speed) ease, box-shadow var(--transition-speed) ease;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    header.scrolled {
      background: #fff;
      box-shadow: 0 2px 8px rgba(0,0,0,0.2);
    }

    .container {
      width: 90%;
      max-width: 1200px;
      margin: 0 auto;
      display: flex;
      align-items: center;
      justify-content: space-between;
      flex-wrap: wrap;
    }

    header h1 {
      font-family: var(--font-family-secondary);
      font-size: 1.8em;
      color: var(--primary-color);
      transition: color var(--transition-speed) ease;
    }

    nav ul {
      list-style: none;
      display: flex;
      gap: 20px;
      align-items: center;
    }
    nav ul li a {
      font-size: 1em;
      font-weight: 600;
      position: relative;
      padding: 5px 0;
      color: var(--primary-color);
      display: flex;
      align-items: center;
      gap: 8px;
    }
    nav ul li a::after {
      content: '';
      position: absolute;
      width: 0%;
      height: 2px;
      background: var(--primary-color);
      left: 0;
      bottom: -2px;
      transition: width var(--transition-speed) ease;
    }
    nav ul li a:hover::after {
      width: 100%;
    }

    .menu-toggle {
      display: none;
      flex-direction: column;
      justify-content: space-between;
      width: 25px;
      height: 20px;
      cursor: pointer;
    }
    .menu-toggle div {
      width: 100%;
      height: 3px;
      background: var(--primary-color);
      border-radius: 1.5px;
      transition: all var(--transition-speed) ease;
    }
    .menu-toggle.active div:nth-child(1) {
      transform: rotate(45deg) translate(5px, 5px);
    }
    .menu-toggle.active div:nth-child(2) {
      opacity: 0;
    }
    .menu-toggle.active div:nth-child(3) {
      transform: rotate(-45deg) translate(5px, -5px);
    }

    /* 美化後的登入畫面 */
    #loginSection {
      max-width: 400px;
      margin: 120px auto;
      padding: 40px 30px;
      border-radius: 10px;
      background: #ffffff;
      box-shadow: 0 10px 20px rgba(0,0,0,0.1);
      position: relative;
      z-index: 1500;
    }
    #loginSection::before {
      content: "";
      position: absolute;
      top: -4px;
      left: -4px;
      right: -4px;
      bottom: -4px;
      background: linear-gradient(45deg, #f093fb, #f5576c);
      z-index: -1;
      border-radius: 12px;
    }
    #loginSection h2 {
      margin-bottom: 30px;
      font-weight: 600;
      color: var(--primary-color);
    }
    #loginSection .form-control {
      border-radius: 5px;
    }
    #loginSection button {
      border-radius: 5px;
      padding: 10px;
      font-weight: bold;
    }
    #loginFeedback {
      margin-top: 15px;
      font-size: 0.9em;
      color: red;
    }

    /* 後台管理內容 */
    .admin-content {
      padding-top: 140px;
      width: 90%;
      max-width: 1200px;
      margin: 0 auto;
      overflow-x: auto;
      display: none;
    }

    .section-title {
      margin-bottom: 20px;
    }

    .section-title h2 {
      font-size: 1.5em;
      margin-bottom: 10px;
    }

    .section-title p {
      font-size: 1em;
      color: var(--secondary-color);
    }

    .toggle-buttons, .filters {
      display: flex;
      gap: 20px;
      margin-bottom: 20px;
      flex-wrap: wrap;
    }

    .filters input, .filters select {
      padding: 8px 12px;
      border: 1px solid #ccc;
      border-radius: 4px;
      font-size: 1em;
    }

    .logout-button,
    .export-btn,
    .add-item-btn,
    .delete-btn,
    .edit-btn,
    .template-btn {
      display: inline-block;
      margin: 10px 10px 10px 0;
      padding: 10px 20px;
      border: none;
      background: var(--primary-color);
      color: #fff;
      cursor: pointer;
      border-radius: 4px;
      transition: background var(--transition-speed) ease, transform 0.2s ease;
      font-size: 1em;
    }
    .logout-button:hover,
    .export-btn:hover,
    .add-item-btn:hover,
    .delete-btn:hover,
    .edit-btn:hover,
    .template-btn:hover {
      background: var(--secondary-color);
      transform: scale(1.05);
    }

    .admin-table {
      width: 100%;
      font-size: 0.9em;
      border-collapse: collapse;
      table-layout: fixed;
      min-width: 800px;
    }

    .admin-table th, .admin-table td {
      vertical-align: middle;
      text-align: left;
      padding: 12px 15px;
      border: 1px solid #ddd;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      cursor: pointer;
    }

    .admin-table th {
      background: #f0f0f0;
      font-weight: 600;
      position: sticky;
      top: 0;
      z-index: 2;
      user-select: none;
    }

    .admin-table th.sortable:hover {
      background: #e0e0e0;
    }

    .admin-table th .sort-indicator {
      margin-left: 5px;
      font-size: 0.8em;
    }

    .admin-table tbody tr:nth-child(even) {
      background-color: #fafafa;
    }

    .admin-table tbody tr:hover {
      background-color: #f1f1f1;
    }

    .admin-table td.actions {
      display: flex;
      gap: 4px;
      min-width: 80px;
      position: sticky;
      right: 0;
      background: inherit;
      z-index: 1;
    }

    .admin-table .edit-btn,
    .admin-table .delete-btn {
      padding: 4px 8px;
      font-size: 0.8em;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: background var(--transition-speed) ease, transform 0.2s ease;
    }

    .admin-table .edit-btn {
      background-color: #4CAF50;
      color: #fff;
    }

    .admin-table .edit-btn:hover {
      background-color: #45a049;
      transform: scale(1.05);
    }

    .admin-table .delete-btn {
      background-color: #f44336;
      color: #fff;
    }

    .admin-table .delete-btn:hover {
      background-color: #da190b;
      transform: scale(1.05);
    }

    .status-active {
      background-color: #d0f3d0;
    }
    .status-inactive,
    .status-deleted {
      background-color: #fbdada;
    }
    .status-rejected {
      background-color: #ffe5e5;
    }

    /* Modal 樣式 */
    .modal {
      display: none;
      position: fixed;
      z-index: 2000;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      overflow: auto;
      background-color: rgba(0,0,0,0.5);
    }

    .modal-content {
      background-color: #fefefe;
      margin: 10% auto;
      padding: 20px;
      border: 1px solid #888;
      width: 80%;
      max-width: 600px;
      border-radius: 8px;
    }

    .modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
    }

    .close {
      color: #aaa;
      font-size: 28px;
      font-weight: bold;
      cursor: pointer;
    }

    .close:hover,
    .close:focus {
      color: black;
      text-decoration: none;
    }

    .modal form {
      display: flex;
      flex-direction: column;
      gap: 10px;
    }

    .modal form input,
    .modal form select,
    .modal form textarea {
      padding: 8px 12px;
      border: 1px solid #ccc;
      border-radius: 4px;
      font-size: 1em;
      width: 100%;
    }

    .modal form button {
      padding: 10px;
      border: none;
      background: var(--accent-color);
      color: #fff;
      cursor: pointer;
      border-radius: 4px;
      transition: background var(--transition-speed) ease;
      font-size: 1em;
    }

    .modal form button:hover {
      background: #c89a2f;
    }

    @media (max-width: 1024px) {
      .menu-toggle {
        display: flex;
      }
      nav ul {
        flex-direction: column;
        align-items: center;
        background: rgba(255, 255, 255, 0.95);
        position: absolute;
        top: var(--header-height);
        right: 0;
        width: 220px;
        display: none;
        padding: 20px 0;
        border-radius: 0 0 8px 8px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
      }
      nav ul.active {
        display: flex;
        max-height: calc(100vh - var(--header-height));
        overflow-y: auto;
      }
    }

    @media (max-width: 768px) {
      .toggle-buttons, .filters {
        flex-direction: column;
      }
      .admin-table th, .admin-table td {
        padding: 8px 10px;
        font-size: 0.85em;
      }
      .logout-button,
      .export-btn,
      .add-item-btn,
      .delete-btn,
      .edit-btn,
      .template-btn {
        width: 100%;
        text-align: center;
      }
    }
  </style>
</head>
<body>
  <!-- 美化後的登入畫面 -->
  <section id="loginSection">
    <h2>管理系統登入</h2>
    <form id="loginForm">
      <div class="mb-3">
        <label for="loginEmail" class="form-label">Email</label>
        <input type="email" class="form-control" id="loginEmail" required>
      </div>
      <div class="mb-3">
        <label for="loginPassword" class="form-label">密碼</label>
        <input type="password" class="form-control" id="loginPassword" required>
      </div>
      <button type="submit" class="btn btn-primary w-100">登入</button>
    </form>
    <div id="loginFeedback"></div>
  </section>

  <!-- 後台管理內容 -->
  <header>
    <div class="container">
      <h1>NasifyTech管理系統</h1>
      <nav>
        <ul></ul>
        <div class="menu-toggle">
          <div></div>
          <div></div>
          <div></div>
        </div>
      </nav>
    </div>
  </header>

  <section class="admin-content" id="adminContent">
    <div class="section-title">
      <h2 id="pageTitle">客戶資料管理</h2>
      <p>Nasify Tech 客戶資料管理系統</p>
    </div>
    <div class="toggle-buttons">
      <button type="button" class="toggle-btn btn btn-primary" id="toggleCustomerDataBtn">客戶資料</button>
      <button type="button" class="toggle-btn btn btn-secondary" id="toggleOtherDataBtn">其他使用者資料</button>
    </div>
    <div class="filters" id="customerFilters">
      <div>
        <label>開始日期：</label>
        <input type="date" id="startDate" class="form-control">
      </div>
      <div>
        <label>結束日期：</label>
        <input type="date" id="endDate" class="form-control">
      </div>
      <div>
        <label>關鍵字搜尋：</label>
        <input type="text" id="searchInput" class="form-control" placeholder="輸入任意關鍵字...">
      </div>
      <button type="button" class="export-btn btn btn-info" id="exportCsvBtn">匯出 CSV</button>
      <button type="button" class="logout-button btn btn-dark" id="logoutBtn">登出</button>
    </div>
    <div style="overflow-x: auto;" id="customerTableContainer">
      <div class="filters" style="margin-top: 10px;">
        <button type="button" class="add-item-btn btn btn-success" id="addItemBtn">新增資料</button>
      </div>
      <table class="admin-table table table-bordered table-striped" id="dataTable">
        <thead>
          <tr id="tableHeaderRow"></tr>
        </thead>
        <tbody id="dataTableBody"></tbody>
      </table>
    </div>
    <div id="editModal" class="modal">
      <div class="modal-content">
        <div class="modal-header">
          <h2 id="modalTitle">編輯資料</h2>
          <span class="close" id="closeModal">&times;</span>
        </div>
        <form id="editForm">
          <input type="hidden" id="recordKey" name="recordKey">
          <div id="editCustomerFields" style="display: none;">
            <div id="editCustomerIdGroup" style="display: none;">
              <label for="editCustomerId">客戶編號:</label>
              <input type="text" id="editCustomerId" name="editCustomerId" class="form-control" readonly />
            </div>
            <div>
              <label for="editName">姓名:</label>
              <input type="text" id="editName" name="editName" class="form-control">
            </div>
            <div>
              <label for="editPhone">電話:</label>
              <input type="text" id="editPhone" name="editPhone" class="form-control">
            </div>
            <div>
              <label for="editInstagram">Instagram:</label>
              <input type="text" id="editInstagram" name="editInstagram" class="form-control">
            </div>
            <div>
              <label for="editLine">LINE ID:</label>
              <input type="text" id="editLine" name="editLine" class="form-control">
            </div>
            <div>
              <label for="editEmail">EMAIL:</label>
              <input type="email" id="editEmail" name="editEmail" class="form-control">
            </div>
            <div>
              <label for="editIdNo">身分證字號:</label>
              <input type="text" id="editIdNo" name="editIdNo" class="form-control">
            </div>
            <div>
              <label for="editBirthday">生日:</label>
              <input type="date" id="editBirthday" name="editBirthday" class="form-control">
            </div>
            <div>
              <label for="editAddress">住址:</label>
              <input type="text" id="editAddress" name="editAddress" class="form-control">
            </div>
            <div>
              <label for="editNote">附註(或銀行帳戶):</label>
              <textarea id="editNote" name="editNote" class="form-control"></textarea>
            </div>
            <div id="editCustomerStatusGroup" style="display: none;">
              <label for="editCustomerStatus">客戶狀態:</label>
              <select id="editCustomerStatus" name="editCustomerStatus" class="form-control">
                <option value="活躍">活躍</option>
                <option value="非活躍">非活躍</option>
                <option value="拒絕往來戶">拒絕往來戶</option>
              </select>
            </div>
          </div>
          <div id="editOtherUsersFields" style="display: none;">
            <div>
              <label for="editOtherName">姓名:</label>
              <input type="text" id="editOtherName" name="editOtherName" class="form-control">
            </div>
            <div>
              <label for="editOtherPhone">電話:</label>
              <input type="text" id="editOtherPhone" name="editOtherPhone" class="form-control">
            </div>
            <div>
              <label for="editOtherInstagram">Instagram:</label>
              <input type="text" id="editOtherInstagram" name="editOtherInstagram" class="form-control">
            </div>
            <div>
              <label for="editOtherLine">LINE ID:</label>
              <input type="text" id="editOtherLine" name="editOtherLine" class="form-control">
            </div>
            <div>
              <label for="editOtherEmail">EMAIL:</label>
              <input type="email" id="editOtherEmail" name="editOtherEmail" class="form-control">
            </div>
            <div>
              <label for="editOtherIdNo">身分證字號:</label>
              <input type="text" id="editOtherIdNo" name="editOtherIdNo" class="form-control">
            </div>
            <div>
              <label for="editOtherBirthday">生日:</label>
              <input type="date" id="editOtherBirthday" name="editOtherBirthday" class="form-control">
            </div>
            <div>
              <label for="editOtherAddress">住址:</label>
              <input type="text" id="editOtherAddress" name="editOtherAddress" class="form-control">
            </div>
            <div>
              <label for="editOtherNote">附註(銀行帳戶):</label>
              <textarea id="editOtherNote" name="editOtherNote" class="form-control"></textarea>
            </div>
          </div>
          <button type="submit" class="btn btn-primary mt-3">保存</button>
        </form>
      </div>
    </div>

    <!-- 內容模態框 -->
    <div id="contentModal" class="modal">
      <div class="modal-content">
        <div class="modal-header">
          <h2>完整內容</h2>
          <span class="close" id="closeContentModal">&times;</span>
        </div>
        <div class="modal-body" id="modalContentBody"></div>
      </div>
    </div>
  </section>

  <!-- Firebase 與 Bootstrap JS -->
  <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-auth-compat.js"></script>
  <script src="https://www.gstatic.com/firebasejs/9.17.2/firebase-database-compat.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    // Firebase 設定
    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",
      appId: "1:330646534360:web:7777b951fccac43fb6bfad",
      measurementId: "G-7HZ5KWXJGP"
    };
    firebase.initializeApp(firebaseConfig);
    const auth = firebase.auth();
    const db = firebase.database();

    // 允許登入的 Email (可依需求調整)
    const allowedEmails = ["it@nasify.org", "nasir.lin@msa.hinet.net"];

    // 取得 DOM 元素
    const loginSection = document.getElementById('loginSection');
    const loginForm = document.getElementById('loginForm');
    const loginFeedback = document.getElementById('loginFeedback');
    const adminContent = document.getElementById('adminContent');
    const logoutBtn = document.getElementById('logoutBtn');

    const toggleCustomerDataBtn = document.getElementById('toggleCustomerDataBtn');
    const toggleOtherDataBtn = document.getElementById('toggleOtherDataBtn');
    const pageTitle = document.getElementById('pageTitle');

    const customerFilters = document.getElementById('customerFilters');
    const customerTableContainer = document.getElementById('customerTableContainer');
    const tableHeaderRow = document.getElementById('tableHeaderRow');
    const dataTableBody = document.getElementById('dataTableBody');
    const addItemBtn = document.getElementById('addItemBtn');

    const editModal = document.getElementById('editModal');
    const closeModal = document.getElementById('closeModal');
    const editForm = document.getElementById('editForm');
    const recordKeyInput = document.getElementById('recordKey');

    // 客戶編輯區域
    const editCustomerFields = document.getElementById('editCustomerFields');
    const editCustomerIdGroup = document.getElementById('editCustomerIdGroup');
    const editCustomerIdInput = document.getElementById('editCustomerId');
    const editNameInput = document.getElementById('editName');
    const editPhoneInput = document.getElementById('editPhone');
    const editInstagramInput = document.getElementById('editInstagram');
    const editLineInput = document.getElementById('editLine');
    const editEmailInput = document.getElementById('editEmail');
    const editIdNoInput = document.getElementById('editIdNo');
    const editBirthdayInput = document.getElementById('editBirthday');
    const editAddressInput = document.getElementById('editAddress');
    const editNoteInput = document.getElementById('editNote');
    const editCustomerStatusGroup = document.getElementById('editCustomerStatusGroup');
    const editCustomerStatusSelect = document.getElementById('editCustomerStatus');

    // 其他使用者編輯區域
    const editOtherUsersFields = document.getElementById('editOtherUsersFields');
    const editOtherNameInput = document.getElementById('editOtherName');
    const editOtherPhoneInput = document.getElementById('editOtherPhone');
    const editOtherInstagramInput = document.getElementById('editOtherInstagram');
    const editOtherLineInput = document.getElementById('editOtherLine');
    const editOtherEmailInput = document.getElementById('editOtherEmail');
    const editOtherIdNoInput = document.getElementById('editOtherIdNo');
    const editOtherBirthdayInput = document.getElementById('editOtherBirthday');
    const editOtherAddressInput = document.getElementById('editOtherAddress');
    const editOtherNoteInput = document.getElementById('editOtherNote');

    const contentModal = document.getElementById('contentModal');
    const closeContentModal = document.getElementById('closeContentModal');
    const modalContentBody = document.getElementById('modalContentBody');

    let currentView = 'customers';
    let customersData = {};
    let otherUsersData = {};
    let customerIdCounter = 0;
    let currentSortKey = null;
    let currentSortOrder = 'asc';

    const customerHeaders = [
      { key: 'customerId', label: '客戶編號' },
      { key: 'name', label: '姓名' },
      { key: 'phone', label: '電話' },
      { key: 'instagram', label: 'Instagram' },
      { key: 'lineId', label: 'LINE ID' },
      { key: 'email', label: 'EMAIL' },
      { key: 'idNo', label: '身分證字號' },
      { key: 'birthday', label: '生日' },
      { key: 'address', label: '住址' },
      { key: 'note', label: '附註' },
      { key: 'customerStatus', label: '客戶狀態' },
      { key: 'timestamp', label: '建立時間' }
    ];

    const otherUserHeaders = [
      { key: 'name', label: '姓名' },
      { key: 'phone', label: '電話' },
      { key: 'instagram', label: 'Instagram' },
      { key: 'lineId', label: 'LINE ID' },
      { key: 'email', label: 'EMAIL' },
      { key: 'idNo', label: '身分證字號' },
      { key: 'birthday', label: '生日' },
      { key: 'address', label: '住址' },
      { key: 'note', label: '附註(銀行帳戶)' },
      { key: 'timestamp', label: '建立時間' }
    ];

    // 登入表單處理
    loginForm.addEventListener('submit', (e) => {
      e.preventDefault();
      const email = document.getElementById('loginEmail').value.trim();
      const password = document.getElementById('loginPassword').value;
      auth.signInWithEmailAndPassword(email, password)
        .then((userCredential) => {
          loginFeedback.textContent = '';
        })
        .catch((error) => {
          loginFeedback.textContent = '登入失敗：' + error.message;
        });
    });

    // Firebase 驗證狀態改變
    auth.onAuthStateChanged(user => {
      if (user) {
        // 可依需求檢查允許的 email
        if (allowedEmails.includes(user.email.toLowerCase())) {
          adminContent.style.display = 'block';
          loginSection.style.display = 'none';
          loadCustomers();
          loadOtherUsers();
        } else {
          adminContent.style.display = 'block';
          loginSection.style.display = 'none';
          loadCustomers();
          loadOtherUsers();
        }
      } else {
        adminContent.style.display = 'none';
        loginSection.style.display = 'block';
      }
    });

    logoutBtn.addEventListener('click', () => {
      auth.signOut();
    });

    function loadCustomers() {
      const ref = db.ref('customers');
      ref.on('value', snapshot => {
        customersData = snapshot.val() || {};
        updateCustomerIdCounter(customersData);
        if (currentView === 'customers') {
          renderTable();
        }
      });
    }

    function loadOtherUsers() {
      const ref = db.ref('otherUsers');
      ref.on('value', snapshot => {
        otherUsersData = snapshot.val() || {};
        if (currentView === 'otherUsers') {
          renderTable();
        }
      });
    }

    function updateCustomerIdCounter(data) {
      let maxId = 0;
      Object.values(data).forEach(item => {
        if (item.customerId && !isNaN(item.customerId)) {
          const idNum = parseInt(item.customerId, 10);
          if (idNum > maxId) maxId = idNum;
        }
      });
      customerIdCounter = maxId;
    }

    toggleCustomerDataBtn.addEventListener('click', () => {
      currentView = 'customers';
      pageTitle.textContent = '客戶資料管理';
      resetViews();
      customerFilters.style.display = 'flex';
      customerTableContainer.style.display = 'block';
      renderTable();
    });

    toggleOtherDataBtn.addEventListener('click', () => {
      currentView = 'otherUsers';
      pageTitle.textContent = '其他使用者資料管理';
      resetViews();
      customerFilters.style.display = 'flex';
      customerTableContainer.style.display = 'block';
      renderTable();
    });

    function resetViews() {
      customerFilters.style.display = 'none';
      customerTableContainer.style.display = 'none';
      editCustomerFields.style.display = 'none';
      editOtherUsersFields.style.display = 'none';
    }

    function renderTable() {
      tableHeaderRow.innerHTML = '';
      dataTableBody.innerHTML = '';

      let headers;
      if (currentView === 'customers') {
        headers = customerHeaders;
      } else if (currentView === 'otherUsers') {
        headers = otherUserHeaders;
      }

      headers.forEach(h => {
        const th = document.createElement('th');
        th.textContent = h.label;
        th.classList.add('sortable');
        th.dataset.key = h.key;

        const sortIndicator = document.createElement('span');
        sortIndicator.classList.add('sort-indicator');
        if (currentSortKey === h.key) {
          sortIndicator.textContent = currentSortOrder === 'asc' ? '▲' : '▼';
        }
        th.appendChild(sortIndicator);
        th.addEventListener('click', () => {
          if (currentSortKey === h.key) {
            currentSortOrder = currentSortOrder === 'asc' ? 'desc' : 'asc';
          } else {
            currentSortKey = h.key;
            currentSortOrder = 'asc';
          }
          renderTable();
        });
        tableHeaderRow.appendChild(th);
      });

      const actionTh = document.createElement('th');
      actionTh.textContent = '操作';
      tableHeaderRow.appendChild(actionTh);

      let dataObj;
      if (currentView === 'customers') {
        dataObj = customersData;
      } else if (currentView === 'otherUsers') {
        dataObj = otherUsersData;
      }

      let dataArray = Object.keys(dataObj).map(key => ({ key, ...dataObj[key] }));
      const searchInput = document.getElementById('searchInput').value.trim().toLowerCase();
      const searchKeywords = searchInput.split(/\s+/).filter(keyword => keyword.length > 0);

      dataArray = dataArray.filter(item => {
        let include = true;
        const startDate = document.getElementById('startDate').value;
        const endDate = document.getElementById('endDate').value;
        if (startDate && item.timestamp && parseInt(item.timestamp) < new Date(startDate).getTime()) {
          include = false;
        }
        if (endDate && item.timestamp && parseInt(item.timestamp) > new Date(endDate).getTime()) {
          include = false;
        }
        if (searchKeywords.length > 0) {
          let allFieldsStr = Object.values(item).map(v => (v + '').toLowerCase()).join(' ');
          const matchesAnyKeyword = searchKeywords.some(keyword => allFieldsStr.includes(keyword));
          if (!matchesAnyKeyword) {
            include = false;
          }
        }
        return include;
      });

      if (currentSortKey) {
        dataArray.sort((a, b) => {
          let aVal = a[currentSortKey] || '';
          let bVal = b[currentSortKey] || '';
          if (currentSortKey === 'timestamp' || currentSortKey === 'birthday') {
            aVal = currentSortKey === 'timestamp' ? parseInt(aVal) : new Date(aVal).getTime();
            bVal = currentSortKey === 'timestamp' ? parseInt(bVal) : new Date(bVal).getTime();
          } else if (currentSortKey === 'customerId') {
            aVal = parseInt(aVal);
            bVal = parseInt(bVal);
          } else {
            aVal = aVal.toString().toLowerCase();
            bVal = bVal.toString().toLowerCase();
          }
          if (aVal < bVal) return currentSortOrder === 'asc' ? -1 : 1;
          if (aVal > bVal) return currentSortOrder === 'asc' ? 1 : -1;
          return 0;
        });
      }

      if (dataArray.length === 0) {
        dataTableBody.innerHTML = '<tr><td colspan="' + (headers.length + 1) + '">目前沒有資料</td></tr>';
        return;
      }

      dataArray.forEach(item => {
        const tr = document.createElement('tr');
        if (currentView === 'customers') {
          if (item.customerStatus === '活躍') {
            tr.classList.add('status-active');
          } else if (item.customerStatus === '非活躍') {
            tr.classList.add('status-inactive');
          } else if (item.customerStatus === '拒絕往來戶') {
            tr.classList.add('status-rejected');
          }
        }
        headers.forEach(h => {
          const td = document.createElement('td');
          let textValue = item[h.key] || '';
          if (h.key === 'timestamp' && textValue) {
            textValue = new Date(textValue).toLocaleString();
          }
          td.textContent = textValue;
          tr.appendChild(td);
        });
        const actionTd = document.createElement('td');
        actionTd.classList.add('actions');
        const editBtn = document.createElement('button');
        editBtn.textContent = '編輯';
        editBtn.classList.add('edit-btn', 'btn', 'btn-sm', 'btn-primary', 'me-2');
        editBtn.type = 'button';
        editBtn.addEventListener('click', () => openEditModal(item.key, item, currentView));
        actionTd.appendChild(editBtn);
        const deleteBtn = document.createElement('button');
        deleteBtn.textContent = '刪除';
        deleteBtn.classList.add('delete-btn', 'btn', 'btn-sm', 'btn-danger');
        deleteBtn.type = 'button';
        deleteBtn.addEventListener('click', () => deleteRecord(item.key, currentView));
        actionTd.appendChild(deleteBtn);
        tr.appendChild(actionTd);
        dataTableBody.appendChild(tr);
      });

      addCellClickEvents();
    }

    addItemBtn.addEventListener('click', () => {
      openEditModal(null, null, currentView);
    });

    function openEditModal(key, item, view) {
      recordKeyInput.value = key || '';
      editForm.reset();
      editCustomerFields.style.display = 'none';
      editOtherUsersFields.style.display = 'none';

      if (view === 'customers') {
        editCustomerFields.style.display = 'block';
        if (!key) {
          editCustomerIdGroup.style.display = 'none';
        } else {
          editCustomerIdGroup.style.display = 'block';
        }
        editCustomerStatusGroup.style.display = 'block';
      } else if (view === 'otherUsers') {
        editOtherUsersFields.style.display = 'block';
      }

      if (key && item) {
        if (view === 'customers') {
          editCustomerIdInput.value = item.customerId || '';
          editCustomerStatusSelect.value = item.customerStatus || '活躍';
          editNameInput.value = item.name || '';
          editPhoneInput.value = item.phone || '';
          editInstagramInput.value = item.instagram || '';
          editLineInput.value = item.lineId || '';
          editEmailInput.value = item.email || '';
          editIdNoInput.value = item.idNo || '';
          editBirthdayInput.value = item.birthday || '';
          editAddressInput.value = item.address || '';
          editNoteInput.value = item.note || '';
        } else if (view === 'otherUsers') {
          editOtherNameInput.value = item.name || '';
          editOtherPhoneInput.value = item.phone || '';
          editOtherInstagramInput.value = item.instagram || '';
          editOtherLineInput.value = item.lineId || '';
          editOtherEmailInput.value = item.email || '';
          editOtherIdNoInput.value = item.idNo || '';
          editOtherBirthdayInput.value = item.birthday || '';
          editOtherAddressInput.value = item.address || '';
          editOtherNoteInput.value = item.note || '';
        }
      }
      editModal.style.display = 'block';
    }

    closeModal.addEventListener('click', () => {
      editModal.style.display = 'none';
    });
    window.addEventListener('click', (event) => {
      if (event.target == editModal) {
        editModal.style.display = 'none';
      }
    });

    editForm.addEventListener('submit', async (e) => {
      e.preventDefault();
      const key = recordKeyInput.value;
      const isNew = !key;
      const nowTimestamp = Date.now();
      let updatedData = {};

      if (currentView === 'customers') {
        if (!isNew) {
          updatedData.customerId = editCustomerIdInput.value;
        }
        updatedData.customerStatus = editCustomerStatusSelect.value;
        updatedData.name = editNameInput.value.trim();
        updatedData.phone = editPhoneInput.value.trim();
        updatedData.instagram = editInstagramInput.value.trim();
        updatedData.lineId = editLineInput.value.trim();
        updatedData.email = editEmailInput.value.trim();
        updatedData.idNo = editIdNoInput.value.trim();
        updatedData.birthday = editBirthdayInput.value;
        updatedData.address = editAddressInput.value.trim();
        updatedData.note = editNoteInput.value.trim();
      } else if (currentView === 'otherUsers') {
        updatedData.name = editOtherNameInput.value.trim();
        updatedData.phone = editOtherPhoneInput.value.trim();
        updatedData.instagram = editOtherInstagramInput.value.trim();
        updatedData.lineId = editOtherLineInput.value.trim();
        updatedData.email = editOtherEmailInput.value.trim();
        updatedData.idNo = editOtherIdNoInput.value.trim();
        updatedData.birthday = editOtherBirthdayInput.value;
        updatedData.address = editOtherAddressInput.value.trim();
        updatedData.note = editOtherNoteInput.value.trim();
        updatedData.timestamp = nowTimestamp;
      }

      try {
        if (isNew) {
          if (currentView === 'customers') {
            updatedData.timestamp = nowTimestamp;
            customerIdCounter++;
            updatedData.customerId = customerIdCounter.toString();
            const ref = db.ref('customers').push();
            await ref.set(updatedData);
            alert('新增成功');
          } else if (currentView === 'otherUsers') {
            updatedData.timestamp = nowTimestamp;
            const ref = db.ref('otherUsers').push();
            await ref.set(updatedData);
            alert('新增成功');
          }
        } else {
          if (currentView === 'customers') {
            updatedData.timestamp = nowTimestamp;
            await db.ref(`customers/${key}`).update(updatedData);
            alert('更新成功');
          } else if (currentView === 'otherUsers') {
            updatedData.timestamp = nowTimestamp;
            await db.ref(`otherUsers/${key}`).update(updatedData);
            alert('更新成功');
          }
        }
        editModal.style.display = 'none';
      } catch (err) {
        console.error('保存失敗:', err);
        alert('操作失敗，請稍後再試');
      }
    });

    function deleteRecord(key, view) {
      if (!confirm('確定要刪除此資料嗎？')) return;
      if (view === 'customers') {
        db.ref(`customers/${key}`).remove()
          .then(() => {
            alert('刪除成功');
          })
          .catch(err => {
            console.error(err);
            alert('刪除失敗');
          });
      } else if (view === 'otherUsers') {
        db.ref(`otherUsers/${key}`).remove()
          .then(() => {
            alert('刪除成功');
          })
          .catch(err => {
            console.error(err);
            alert('刪除失敗');
          });
      }
    }

    exportCsvBtn.addEventListener('click', () => {
      let dataObj;
      let headers;
      let filename;
      if (currentView === 'customers') {
        dataObj = customersData;
        headers = customerHeaders;
        filename = '客戶資料.csv';
      } else if (currentView === 'otherUsers') {
        dataObj = otherUsersData;
        headers = otherUserHeaders;
        filename = '其他使用者資料.csv';
      }
      const csvRows = [];
      const headerLabels = headers.map(h => h.label);
      csvRows.push(headerLabels.join(','));
      let dataArray = Object.keys(dataObj).map(key => ({ key, ...dataObj[key] }));
      const searchInput = document.getElementById('searchInput').value.trim().toLowerCase();
      const searchKeywords = searchInput.split(/\s+/).filter(keyword => keyword.length > 0);
      dataArray = dataArray.filter(item => {
        let include = true;
        const startDate = document.getElementById('startDate').value;
        const endDate = document.getElementById('endDate').value;
        if (startDate && item.timestamp && parseInt(item.timestamp) < new Date(startDate).getTime()) {
          include = false;
        }
        if (endDate && item.timestamp && parseInt(item.timestamp) > new Date(endDate).getTime()) {
          include = false;
        }
        if (searchKeywords.length > 0) {
          let allFieldsStr = Object.values(item).map(v => (v + '').toLowerCase()).join(' ');
          const matchesAnyKeyword = searchKeywords.some(keyword => allFieldsStr.includes(keyword));
          if (!matchesAnyKeyword) {
            include = false;
          }
        }
        return include;
      });
      if (currentSortKey) {
        dataArray.sort((a, b) => {
          let aVal = a[currentSortKey] || '';
          let bVal = b[currentSortKey] || '';
          if (currentSortKey === 'timestamp' || currentSortKey === 'birthday') {
            aVal = currentSortKey === 'timestamp' ? parseInt(aVal) : new Date(aVal).getTime();
            bVal = currentSortKey === 'timestamp' ? parseInt(bVal) : new Date(bVal).getTime();
          } else if (currentSortKey === 'customerId') {
            aVal = parseInt(aVal);
            bVal = parseInt(bVal);
          } else {
            aVal = aVal.toString().toLowerCase();
            bVal = bVal.toString().toLowerCase();
          }
          if (aVal < bVal) return currentSortOrder === 'asc' ? -1 : 1;
          if (aVal > bVal) return currentSortOrder === 'asc' ? 1 : -1;
          return 0;
        });
      }
      if (dataArray.length === 0) {
        alert('沒有符合條件的資料可匯出。');
        return;
      }
      dataArray.forEach(item => {
        const row = [];
        headers.forEach(h => {
          let val = item[h.key] || '';
          if (h.key === 'timestamp' && val) {
            val = new Date(val).toLocaleString();
          }
          val = val.toString().replace(/"/g, '""');
          row.push(`"${val}"`);
        });
        csvRows.push(row.join(','));
      });
      const csvContent = "\uFEFF" + csvRows.join('\n');
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.setAttribute('href', url);
      link.setAttribute('download', filename);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    });

    function addCellClickEvents() {
      const cells = dataTableBody.querySelectorAll('td:not(.actions)');
      cells.forEach(cell => {
        cell.removeEventListener('click', cellClickHandler);
        cell.addEventListener('click', cellClickHandler);
      });
    }

    function cellClickHandler(event) {
      const cell = event.currentTarget;
      if (cell.scrollWidth > cell.clientWidth) {
        const content = cell.textContent.trim();
        modalContentBody.textContent = content;
        contentModal.style.display = 'block';
      }
    }

    let debounceTimeout;
    document.getElementById('searchInput').addEventListener('input', () => {
      clearTimeout(debounceTimeout);
      debounceTimeout = setTimeout(() => {
        renderTable();
      }, 300);
    });

    window.addEventListener('click', (event) => {
      if (event.target == contentModal) {
        contentModal.style.display = 'none';
      }
    });

    closeContentModal.addEventListener('click', () => {
      contentModal.style.display = 'none';
    });

    const menuToggle = document.querySelector('.menu-toggle');
    const navUl = document.querySelector('nav ul');
    menuToggle.addEventListener('click', () => {
      menuToggle.classList.toggle('active');
      navUl.classList.toggle('active');
    });
  </script>
</body>
</html>
