<!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, .generate-btn, .low-budget-btn, .mid-budget-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,
    .generate-btn:hover,
    .low-budget-btn:hover,
    .mid-budget-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,
      .generate-btn,
      .low-budget-btn,
      .mid-budget-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, .modal form select {
      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;
    }
    .history-menu {
      margin-top: 40px;
    }

    .history-menu table {
      margin-top: 20px;
    }
  </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>

    <div class="filters" style="margin-top: 10px;">
      <input type="text" id="itemName" placeholder="食物名稱" required/>
      <input type="number" id="itemPrice" placeholder="價格" required/>
      <select id="itemCategory" multiple>
        <option value="早餐">早餐</option>
        <option value="午餐">午餐</option>
        <option value="晚餐">晚餐</option>
      </select>
      <button class="add-item-btn" id="addItemBtn">新增食物</button>
      <button class="export-btn" id="exportCsvBtn">匯出 CSV</button>
    </div>

    <div class="filters" style="margin-top: 20px;">
      <button class="low-budget-btn" id="lowBudgetBtn">預算低</button>
      <button class="mid-budget-btn" id="midBudgetBtn">預算中高</button>
      <button class="generate-btn" id="generateMenuBtn">隨機抽籤</button>
    </div>

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

    <table class="admin-table" id="budgetTable">
      <thead>
        <tr>
          <th>食物名稱</th>
          <th>價格</th>
          <th>類別</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>

    <div class="section-title" style="margin-top: 40px;">
      <h2>每日菜單</h2>
      <p>自動生成的每日菜單。</p>
    </div>

    <table class="admin-table" id="dailyMenuTable">
      <thead>
        <tr>
          <th>餐別</th>
          <th>食物名稱</th>
          <th>價格</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
    <div class="history-menu">
      <div class="section-title">
        <h2>歷史菜單</h2>
        <p>查看之前生成的每日菜單。</p>
      </div>
      <table class="admin-table" id="historyMenuTable">
        <thead>
          <tr>
            <th>日期</th>
            <th>餐別</th>
            <th>食物名稱</th>
            <th>價格</th>
          </tr>
        </thead>
        <tbody></tbody>
      </table>
    </div>
  </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>

        <label for="editItemCategory">類別:</label>
        <select id="editItemCategory" multiple required>
          <option value="早餐">早餐</option>
          <option value="午餐">午餐</option>
          <option value="晚餐">晚餐</option>
        </select>

        <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 itemCategorySelect = document.getElementById('itemCategory');
    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');
    const editItemCategorySelect = document.getElementById('editItemCategory');
    const lowBudgetBtn = document.getElementById('lowBudgetBtn');
    const midBudgetBtn = document.getElementById('midBudgetBtn');
    const generateMenuBtn = document.getElementById('generateMenuBtn');
    const dailyMenuTableBody = document.querySelector('#dailyMenuTable tbody');
    const historyMenuTableBody = document.querySelector('#historyMenuTable tbody');

    auth.onAuthStateChanged(user => {
      if (user) {
        adminContent.style.display = 'block';
        loadBudgetData(user.uid);
        loadHistoryMenus(user.uid);
      } else {
        window.location.href = '/404.html';
      }
    });

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

    let allData = {};
    function loadBudgetData(uid) {
      const ref = db.ref(`menus/${uid}/items`); 
      ref.on('value', snapshot => {
        const data = snapshot.val() || {};
        allData = data;
        renderTable();
      });
    }
    function loadHistoryMenus(uid) {
      const ref = db.ref(`menus/${uid}/history`); 
      ref.on('value', snapshot => {
        const data = snapshot.val() || {};
        renderHistoryMenus(data);
      });
    }
    function renderTable() {
      budgetTableBody.innerHTML = '';

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

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

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

        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 categoryTd = document.createElement('td');
        categoryTd.textContent = categories.join(', ');
        tr.appendChild(categoryTd);

        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();
    }
    function renderHistoryMenus(menus) {
      historyMenuTableBody.innerHTML = '';

      const keys = Object.keys(menus).sort((a, b) => menus[b].timestamp - menus[a].timestamp); 

      if (keys.length === 0) {
        historyMenuTableBody.innerHTML = '<tr><td colspan="4">目前沒有歷史菜單</td></tr>';
        return;
      }

      keys.forEach(key => {
        const menu = menus[key];
        const date = menu.date || '未知日期';
        const timestamp = menu.timestamp || 0;

        ['breakfast', 'lunch', 'dinner'].forEach(meal => {
          const tr = document.createElement('tr');

          const dateTd = document.createElement('td');
          dateTd.textContent = date;
          tr.appendChild(dateTd);

          const mealTd = document.createElement('td');
          mealTd.textContent = meal === 'breakfast' ? '早餐' : (meal === 'lunch' ? '午餐' : '晚餐');
          tr.appendChild(mealTd);

          const nameTd = document.createElement('td');
          nameTd.textContent = menu[meal] ? menu[meal].name : '無選擇';
          tr.appendChild(nameTd);

          const priceTd = document.createElement('td');
          priceTd.textContent = menu[meal] ? menu[meal].price : '0';
          tr.appendChild(priceTd);

          historyMenuTableBody.appendChild(tr);
        });
        const totalTr = document.createElement('tr');

        const totalLabelTd = document.createElement('td');
        totalLabelTd.colSpan = 3;
        totalLabelTd.style.textAlign = 'right';
        totalLabelTd.textContent = '總計：';
        totalTr.appendChild(totalLabelTd);

        const totalValueTd = document.createElement('td');
        totalValueTd.textContent = `${menu.total} 元`;
        totalTr.appendChild(totalValueTd);

        historyMenuTableBody.appendChild(totalTr);
      });
    }
    addItemBtn.addEventListener('click', () => {
      const name = itemNameInput.value.trim();
      const price = parseFloat(itemPriceInput.value.trim());
      const selectedOptions = Array.from(itemCategorySelect.selectedOptions).map(option => option.value);

      if (!name || isNaN(price) || selectedOptions.length === 0) {
        alert('請輸入正確的食物名稱、價格和至少一個類別');
        return;
      }

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

      const ref = db.ref(`menus/${user.uid}/items`); 
      const newItemRef = ref.push();
      newItemRef.set({
        name,
        price,
        categories: selectedOptions,
        timestamp: Date.now()
      }).then(() => {
        itemNameInput.value = '';
        itemPriceInput.value = '';
        itemCategorySelect.selectedIndex = -1;
      }).catch(error => {
        console.error('新增食物失敗:', error);
        alert('新增失敗，請稍後再試');
      });
    });
    function deleteRecord(key) {
      if (!auth.currentUser) return;
      if (confirm('您確定要刪除此食物嗎？')) {
        db.ref(`menus/${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;
      editItemCategorySelect.value = '';
      if (item.categories) {
        Array.from(editItemCategorySelect.options).forEach(option => {
          if (item.categories.includes(option.value)) {
            option.selected = true;
          }
        });
      }
      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());
      const updatedCategories = Array.from(editItemCategorySelect.selectedOptions).map(option => option.value);

      if (!updatedName || isNaN(updatedPrice) || updatedCategories.length === 0) {
        alert('請輸入正確的食物名稱、價格和至少一個類別');
        return;
      }

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

      db.ref(`menus/${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'}"`,
          `"${item.categories ? item.categories.join('; ').replace(/"/g, '""') : ''}"`
        ];
        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', 'food_budget_data.csv');
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    });
    lowBudgetBtn.addEventListener('click', () => {
      generateDailyMenu('low');
    });

    midBudgetBtn.addEventListener('click', () => {
      generateDailyMenu('mid');
    });

    generateMenuBtn.addEventListener('click', () => {
      generateDailyMenu('random');
    });
    function generateDailyMenu(mode) {
      const breakfastItems = [];
      const lunchItems = [];
      const dinnerItems = [];

      Object.values(allData).forEach(item => {
        if (item.categories.includes('早餐')) breakfastItems.push(item);
        if (item.categories.includes('午餐')) lunchItems.push(item);
        if (item.categories.includes('晚餐')) dinnerItems.push(item);
      });

      let selectedBreakfast, selectedLunch, selectedDinner;

      if (mode === 'low') {
        selectedBreakfast = selectCheapestItem(breakfastItems);
        selectedLunch = selectCheapestItem(lunchItems);
        selectedDinner = selectCheapestItem(dinnerItems);
      } else if (mode === 'mid') {
        selectedBreakfast = selectMedianPriceItem(breakfastItems);
        selectedLunch = selectMedianPriceItem(lunchItems);
        selectedDinner = selectMedianPriceItem(dinnerItems);
      } else if (mode === 'random') {
        selectedBreakfast = getRandomItem(breakfastItems);
        selectedLunch = getRandomItem(lunchItems);
        selectedDinner = getRandomItem(dinnerItems);
      }

      const dailyMenu = {
        date: new Date().toISOString().split('T')[0], 
        breakfast: selectedBreakfast ? { name: selectedBreakfast.name, price: selectedBreakfast.price } : null,
        lunch: selectedLunch ? { name: selectedLunch.name, price: selectedLunch.price } : null,
        dinner: selectedDinner ? { name: selectedDinner.name, price: selectedDinner.price } : null,
        total: 0,
        timestamp: Date.now()
      };

      ['breakfast', 'lunch', 'dinner'].forEach(meal => {
        if (dailyMenu[meal]) {
          dailyMenu.total += parseFloat(dailyMenu[meal].price);
        }
      });
      if (dailyMenu.total > 300) {
        alert('生成的菜單總價格超過 300 元，請調整您的食物價格或重新生成。');
        return;
      }

      renderDailyMenu(dailyMenu);
      saveDailyMenu(dailyMenu);
    }
    function selectCheapestItem(items) {
      if (items.length === 0) return null;
      return items.reduce((prev, curr) => (prev.price < curr.price ? prev : curr));
    }
    function selectMedianPriceItem(items) {
      if (items.length === 0) return null;
      const sorted = items.slice().sort((a, b) => a.price - b.price);
      return sorted[Math.floor(sorted.length / 2)];
    }
    function getRandomItem(items) {
      if (items.length === 0) return null;
      const index = Math.floor(Math.random() * items.length);
      return items[index];
    }
    function renderDailyMenu(menu) {
      dailyMenuTableBody.innerHTML = '';
      let total = 0;

      ['breakfast', 'lunch', 'dinner'].forEach(meal => {
        const tr = document.createElement('tr');

        const mealTd = document.createElement('td');
        mealTd.textContent = meal === 'breakfast' ? '早餐' : (meal === 'lunch' ? '午餐' : '晚餐');
        tr.appendChild(mealTd);

        const nameTd = document.createElement('td');
        nameTd.textContent = menu[meal] ? menu[meal].name : '無選擇';
        tr.appendChild(nameTd);

        const priceTd = document.createElement('td');
        priceTd.textContent = menu[meal] ? menu[meal].price : '0';
        tr.appendChild(priceTd);

        if (menu[meal]) {
          total += parseFloat(menu[meal].price);
        }

        dailyMenuTableBody.appendChild(tr);
      });
      const totalTr = document.createElement('tr');

      const totalLabelTd = document.createElement('td');
      totalLabelTd.colSpan = 2;
      totalLabelTd.style.textAlign = 'right';
      totalLabelTd.textContent = '總計：';
      totalTr.appendChild(totalLabelTd);

      const totalValueTd = document.createElement('td');
      totalValueTd.textContent = `${total} 元`;
      totalTr.appendChild(totalValueTd);

      dailyMenuTableBody.appendChild(totalTr);
    }
    function saveDailyMenu(menu) {
      const user = auth.currentUser;
      if (!user) return;

      const ref = db.ref(`menus/${user.uid}/history`); 
      const newMenuRef = ref.push();
      newMenuRef.set({
        date: menu.date,
        breakfast: menu.breakfast,
        lunch: menu.lunch,
        dinner: menu.dinner,
        total: menu.total,
        timestamp: menu.timestamp
      }).then(() => {
        console.log('每日菜單已儲存');
      }).catch(error => {
        console.error('儲存每日菜單失敗:', error);
        alert('儲存每日菜單失敗，請稍後再試');
      });
    }
    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>
