<!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>
  <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);
    }
    .admin-content {
      padding-top: 140px;
      width: 90%;
      max-width: 1200px;
      margin: 0 auto;
    }

    .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);
    }
    .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 {
      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;
      font-size: 1em;
    }
    .logout-button:hover,
    .export-btn:hover,
    .add-item-btn:hover {
      background: var(--secondary-color);
    }
    .admin-table {
      width: 100%;
      border-collapse: collapse;
    }
    .admin-table th, .admin-table td {
      border: 1px solid #ddd;
      padding: 10px 15px;
      text-align: left;
    }
    .admin-table th {
      background: #f0f0f0;
    }
    .admin-table td.actions {
      display: flex;
      gap: 10px;
    }
    .admin-table button {
      padding: 5px 10px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 0.9em;
      transition: background var(--transition-speed) ease;
    }
    .admin-table .edit-btn {
      background: #4CAF50;
      color: #fff;
    }
    .admin-table .edit-btn:hover {
      background: #45a049;
    }
    .admin-table .delete-btn {
      background: #f44336;
      color: #fff;
    }
    .admin-table .delete-btn:hover {
      background: #da190b;
    }
    @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) {
      .filters {
        flex-direction: column;
      }
      .admin-table th, .admin-table td {
        padding: 8px 10px;
      }
      .logout-button,
      .export-btn,
      .add-item-btn {
        width: 100%;
        text-align: center;
      }
    }
    .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: 500px;
      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 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;
    }
  </style>
</head>

<body>
  <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" style="display: none;">
    <div class="section-title">
      <h2>留北計畫預算</h2>
      <p>計算留北需要之花費用。</p>
    </div>

    <div class="filters" style="margin-bottom: 0;">
      <div>
        <strong>總花費金額：</strong>
        <span id="totalCost">0</span>
      </div>
    </div>

    <div class="filters" style="margin-top: 10px;">
      <input type="text" id="itemName" placeholder="品項名稱"/>
      <input type="number" id="itemPrice" placeholder="價格"/>
      <button class="add-item-btn" id="addItemBtn">新增品項</button>
      <button class="export-btn" id="exportCsvBtn">匯出 CSV</button>
    </div>

    <button class="logout-button" id="logoutBtn">登出</button>

    <table class="admin-table" id="budgetTable">
      <thead>
        <tr>
          <th>品項</th>
          <th>價格</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
  </section>

  <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">
        <label for="editItemName">品項名稱:</label>
        <input type="text" id="editItemName" name="editItemName" required>

        <label for="editItemPrice">價格:</label>
        <input type="number" id="editItemPrice" name="editItemPrice" required>

        <button type="submit">保存</button>
      </form>
    </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-auth-compat.js"></script>
  <script src="https://www.gstatic.com/firebasejs/9.17.2/firebase-database-compat.js"></script>

  <script>
    const firebaseConfig = {
      apiKey: "AIzaSyCknahg0vqFDiFYDQM1YkS4Sa6j4Eth7ro",
      authDomain: "nasirsweb.firebaseapp.com",
      databaseURL: "https://nasirsweb-default-rtdb.firebaseio.com",
      projectId: "nasirsweb",
      storageBucket: "nasirsweb.firebasestorage.app",
      appId: "1:472577461049:web:00b9cab35ce7b7401bf6e8",
      measurementId: "G-7HZ5KWXJGP"
    };
    firebase.initializeApp(firebaseConfig);
    const auth = firebase.auth();
    const db = firebase.database();
    const adminContent = document.getElementById('adminContent');
    const logoutBtn = document.getElementById('logoutBtn');
    const budgetTableBody = document.querySelector('#budgetTable tbody');
    const addItemBtn = document.getElementById('addItemBtn');
    const itemNameInput = document.getElementById('itemName');
    const itemPriceInput = document.getElementById('itemPrice');
    const totalCostSpan = document.getElementById('totalCost');
    const exportCsvBtn = document.getElementById('exportCsvBtn');
    const editModal = document.getElementById('editModal');
    const closeModal = document.getElementById('closeModal');
    const editForm = document.getElementById('editForm');
    const recordKeyInput = document.getElementById('recordKey');
    const editItemNameInput = document.getElementById('editItemName');
    const editItemPriceInput = document.getElementById('editItemPrice');
    auth.onAuthStateChanged(user => {
      if (user) {
        adminContent.style.display = 'block';
        loadBudgetData(user.uid);
      } else {
        window.location.href = '/404.html';
      }
    });

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

    let allData = {};

    function loadBudgetData(uid) {
      const ref = db.ref(`budgetTool/${uid}/items`);
      ref.on('value', snapshot => {
        const data = snapshot.val() || {};
        allData = data;
        renderTable();
      });
    }

    function renderTable() {
      budgetTableBody.innerHTML = '';

      let totalCost = 0;
      const keys = Object.keys(allData);

      if (keys.length === 0) {
        budgetTableBody.innerHTML = '<tr><td colspan="3">目前沒有資料</td></tr>';
        totalCostSpan.textContent = '0';
        return;
      }

      keys.forEach(key => {
        const item = allData[key];
        const name = item.name || '(無品項)';
        const price = item.price || 0;

        totalCost += parseFloat(price);

        const tr = document.createElement('tr');

        const nameTd = document.createElement('td');
        nameTd.textContent = name;
        tr.appendChild(nameTd);

        const priceTd = document.createElement('td');
        priceTd.textContent = price;
        tr.appendChild(priceTd);

        const actionsTd = document.createElement('td');
        actionsTd.classList.add('actions');

        const editBtn = document.createElement('button');
        editBtn.textContent = '編輯';
        editBtn.classList.add('edit-btn');
        editBtn.addEventListener('click', () => openEditModal(key, item));
        actionsTd.appendChild(editBtn);

        const deleteBtn = document.createElement('button');
        deleteBtn.textContent = '刪除';
        deleteBtn.classList.add('delete-btn');
        deleteBtn.addEventListener('click', () => deleteRecord(key));
        actionsTd.appendChild(deleteBtn);

        tr.appendChild(actionsTd);
        budgetTableBody.appendChild(tr);
      });

      totalCostSpan.textContent = totalCost.toString();
    }

    addItemBtn.addEventListener('click', () => {
      const name = itemNameInput.value.trim();
      const price = parseFloat(itemPriceInput.value.trim());

      if (!name || isNaN(price)) {
        alert('請輸入正確的品項與價格');
        return;
      }

      const user = auth.currentUser;
      if (!user) return;

      const ref = db.ref(`budgetTool/${user.uid}/items`);
      const newItemRef = ref.push();
      newItemRef.set({
        name,
        price,
        timestamp: Date.now()
      }).then(() => {
        itemNameInput.value = '';
        itemPriceInput.value = '';
      }).catch(error => {
        console.error('新增品項失敗:', error);
        alert('新增失敗，請稍後再試');
      });
    });
    function deleteRecord(key) {
      if (!auth.currentUser) return;
      if (confirm('您確定要刪除此品項嗎？')) {
        db.ref(`budgetTool/${auth.currentUser.uid}/items/${key}`).remove()
          .then(() => {
            alert('刪除成功');
          })
          .catch(error => {
            console.error('刪除失敗:', error);
            alert('刪除失敗，請稍後再試');
          });
      }
    }
    function openEditModal(key, item) {
      recordKeyInput.value = key;
      editItemNameInput.value = item.name || '';
      editItemPriceInput.value = item.price || 0;
      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', (e) => {
      e.preventDefault();
      if (!auth.currentUser) return;

      const key = recordKeyInput.value;
      const updatedName = editItemNameInput.value.trim();
      const updatedPrice = parseFloat(editItemPriceInput.value.trim());
      if (!updatedName || isNaN(updatedPrice)) {
        alert('請輸入正確的品項與價格');
        return;
      }

      const updatedData = {
        name: updatedName,
        price: updatedPrice,
        timestamp: Date.now()
      };

      db.ref(`budgetTool/${auth.currentUser.uid}/items/${key}`).update(updatedData)
        .then(() => {
          alert('更新成功');
          editModal.style.display = 'none';
        })
        .catch(error => {
          console.error('更新失敗:', error);
          alert('更新失敗，請稍後再試');
        });
    });
    exportCsvBtn.addEventListener('click', () => {
      const csvRows = [];
      const headers = ['品項', '價格'];
      csvRows.push(headers.join(','));

      Object.keys(allData).forEach(key => {
        const item = allData[key];
        const row = [
          `"${item.name ? item.name.replace(/"/g, '""') : ''}"`,
          `"${item.price ? item.price.toString().replace(/"/g, '""') : '0'}"`
        ];
        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', 'budget_data.csv');
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    });
    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>
