<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Admin Panel</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />
  <link rel="stylesheet" href="css/main/main.css?ver=<?php echo time(); ?>" />
  <script src="js/main/main.js?ver=<?php echo time(); ?>" defer></script>
  <style>
    h3 {
      margin-bottom: 10px;
    }

    .action-buttons {
      margin-bottom: 10px;
    }

    .action-buttons button {
      margin-right: 10px;
      padding: 8px 12px;
      font-size: 14px;
      cursor: pointer;
      background-color: #4CAF50;
      color: white;
      border: none;
      border-radius: 4px;
      display: inline-flex;
      align-items: center;
    }

    .action-buttons button i {
      margin-right: 5px;
    }

    .table-container {
      max-height: calc(100vh - 200px);
      overflow-y: auto;
      border: 1px solid #ccc;
    }

    table {
      width: 100%;
      border-collapse: collapse;
      /* Ensure table-layout fixed or auto works nicely with sticky headers */
      table-layout: auto;
    }
    
    thead th {
      position: sticky;
      top: 0;
      background-color: #f2f2f2; /* Same as before or your preferred bg */
      z-index: 10; /* To make sure it stays above other cells */
      box-shadow: 0 2px 2px -1px rgba(0, 0, 0, 0.4);
    }

    th,
    td {
      border: 1px solid #ccc;
      padding: 8px;
      vertical-align: middle;
    }

    th {
      background-color: #f2f2f2;
    }

    td {
      background-color: #fff;
    }

    td[contenteditable='true']:focus {
      outline: 2px solid #007BFF;
    }

    /* Style for delete buttons */
    .delete-btn {
      cursor: pointer;
      color: #dc3545;
      font-size: 16px;
      text-align: center;
    }

    .delete-btn:hover {
      color: #a71d2a;
    }
  </style>
</head>
<body>
  <!-- Left Panel (Navigation) -->
  <div class="left-panel left-panel-show" id="left-panel"></div>
  <!-- Main Content Area -->
  <div class="main-content main-content-normal" id="main-content">
    <!-- Content Area (Dynamic Content Based on the selected menu) -->
    <div id="content">
      <h3><i class="fas fa-box"></i> Manage Trays</h3>

      <div class="action-buttons">
        <button onclick="addRow()"><i class="fas fa-plus"></i> Add Row</button>
        <button onclick="saveTable()"><i class="fas fa-save"></i> Save</button>
      </div>

      <div class="table-container" id="table-container">
        <p>Loading trays...</p>
      </div>
    </div>
  </div>

  <script>
    let headers = [];

    async function fetchTrayData() {
      try {
        const response = await fetch('../php/fetch_tray.php');
        if (!response.ok) throw new Error('Failed to load tray data');
        const data = await response.json();

        if (!Array.isArray(data) || data.length === 0) {
          document.getElementById('table-container').innerHTML = '<p>No data available.</p>';
          return;
        }

        headers = Object.keys(data[0]);
        renderTable(data);
      } catch (error) {
        document.getElementById('table-container').innerHTML = `<p style="color:red;">${error.message}</p>`;
      }
    }

    function renderTable(data) {
      const container = document.getElementById('table-container');
      let tableHTML = `<table id="tray-table"><thead><tr>`;

      headers.forEach((header) => {
        tableHTML += `<th>${header}</th>`;
      });

      // Add extra header for delete column
      tableHTML += `<th>Delete</th>`;

      tableHTML += `</tr></thead><tbody>`;

      data.forEach((row, rowIndex) => {
        tableHTML += `<tr>`;
        headers.forEach((header) => {
          tableHTML += `<td contenteditable="true">${row[header]}</td>`;
        });
        // Add delete button cell
        tableHTML += `<td class="delete-btn" title="Delete row" onclick="deleteRow(this)"><i class="fas fa-trash"></i></td>`;
        tableHTML += `</tr>`;
      });

      tableHTML += `</tbody></table>`;
      container.innerHTML = tableHTML;
    }

    function addRow() {
      const table = document.getElementById('tray-table');
      if (!table || headers.length === 0) return;

      const newRow = table.insertRow(-1);
      headers.forEach((header, i) => {
        const cell = newRow.insertCell();
        cell.contentEditable = "true";

        if (header.toLowerCase().includes("tray")) {
          // Get max tray no from existing rows
          const trayNos = Array.from(
            table.querySelectorAll('tbody tr td:nth-child(' + (i + 1) + ')')
          ).map((td) => parseInt(td.innerText) || 0);
          const maxTrayNo = trayNos.length ? Math.max(...trayNos) : 0;
          cell.innerText = maxTrayNo + 1;
        } else {
          cell.innerText = "";
        }
      });

      // Add the delete button cell
      const deleteCell = newRow.insertCell();
      deleteCell.className = "delete-btn";
      deleteCell.title = "Delete row";
      deleteCell.innerHTML = `<i class="fas fa-trash"></i>`;
      deleteCell.onclick = function () {
        deleteRow(deleteCell);
      };
    }

    function deleteRow(button) {
      const row = button.closest('tr');
      if (!row) return;

      Swal.fire({
        title: 'Are you sure?',
        text: "You won't be able to revert this deletion!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#dc3545',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Yes, delete it!'
      }).then((result) => {
        if (result.isConfirmed) {
          row.remove();
          Swal.fire('Deleted!', 'The row has been deleted.', 'success');
        }
      });
    }

function saveTable() {
  const table = document.getElementById('tray-table');
  if (!table) return;

  const rows = table.querySelectorAll('tbody tr');
  const dataToSend = [];

  rows.forEach((row) => {
    const cells = row.querySelectorAll('td');
    const obj = {};
    headers.forEach((header, index) => {
      let value = cells[index]?.innerText.trim();

      // Convert "Tray No" to number
      if (header === "Tray No") {
        value = value === "" ? null : Number(value);
      }
      // Add more conversions here if needed for other numeric fields
      obj[header] = value;
    });
    dataToSend.push(obj);
  });

  Swal.fire({
    title: 'Save changes?',
    icon: 'question',
    showCancelButton: true,
    confirmButtonText: 'Yes, save it!',
    cancelButtonText: 'Cancel',
  }).then((result) => {
    if (result.isConfirmed) {
      fetch('../php/save_trays.php', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(dataToSend),
      })
        .then((res) => res.json())
        .then((response) => {
          if (response.success) {
            Swal.fire('Saved!', 'Tray data saved successfully.', 'success');
          } else {
            Swal.fire('Error', response.error || 'Failed to save trays.', 'error');
          }
        })
        .catch(() => {
          Swal.fire('Error', 'Failed to save trays.', 'error');
        });
    }
  });
}

    window.addEventListener('DOMContentLoaded', fetchTrayData);
  </script>
</body>
</html>
