<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <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>
    body {
      font-family: Arial, sans-serif;
    }

    #action-buttons {
      margin-top: 20px;
    }

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

    .btn:hover {
      background-color: #3e8e41;
    }

    #table-wrapper {
      max-height: calc(100vh - 200px);
      overflow-y: auto;
      margin-top: 15px;
      border: 1px solid #ddd;
    }

    table {
      width: 100%;
      border-collapse: collapse;
      font-size: 14px;
      table-layout: fixed;
    }

    thead th {
      background-color: #f0f0f0;
      position: sticky;
      top: 0;
      z-index: 1;
    }

    th, td {
      border: 1px solid #ccc;
      padding: 10px;
      text-align: left;
    }

    th:nth-child(1),
    td:nth-child(1),
    th:nth-child(3),
    td:nth-child(3) {
      max-width: 70px;
      width: 70px;
      text-align: center;
    }

    td[contenteditable="true"] {
      background-color: #f5f5f5;
    }

    .delete-icon {
      color: #d9534f;
      cursor: pointer;
      font-size: 16px;
    }

    .delete-icon:hover {
      color: #c9302c;
    }
  </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 -->
  <div id="content">
    <h2>Admin Pages</h2>

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

    <div id="table-wrapper">
      <table id="pages-table">
        <thead>
          <tr>
            <th>Serial</th>
            <th>Page</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
          <!-- Rows will be dynamically inserted here -->
        </tbody>
      </table>
    </div>
  </div>

</div>

<script>
  async function fetchPages() {
    try {
      const response = await fetch('../php/fetch_pages.php');
      const pages = await response.json();

      const tbody = document.querySelector('#pages-table tbody');
      tbody.innerHTML = '';

      pages.forEach((page, index) => {
        const row = createRow(index + 1, page);
        tbody.appendChild(row);
      });

    } catch (error) {
      console.error('Error fetching pages:', error);
      document.querySelector('#content').innerHTML = '<p style="color: red;">Failed to load pages.</p>';
    }
  }

  function createRow(serial, page = '') {
    const row = document.createElement('tr');

    row.innerHTML = `
      <td>${serial}</td>
      <td contenteditable="true">${page}</td>
      <td><i class="fas fa-trash delete-icon" onclick="deleteRow(this)"></i></td>
    `;

    return row;
  }

  function addRow() {
    const tbody = document.querySelector('#pages-table tbody');
    const rowCount = tbody.rows.length + 1;
    const newRow = createRow(rowCount, '');
    tbody.appendChild(newRow);
  }

  function deleteRow(icon) {
    const row = icon.closest('tr');
    row.remove();
    updateSerialNumbers();
  }

  function updateSerialNumbers() {
    const rows = document.querySelectorAll('#pages-table tbody tr');
    rows.forEach((row, index) => {
      row.cells[0].textContent = index + 1;
    });
  }

  function savePages() {
    const rows = document.querySelectorAll('#pages-table tbody tr');
    const pages = [];

    rows.forEach(row => {
      const pageName = row.cells[1].textContent.trim();
      if (pageName) {
        pages.push(pageName);
      }
    });

    showProcessingMessage("Saving data, please wait...");

    fetch('../php/save_pages.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(pages)
    })
    .then(res => res.json())
    .then(result => {
      if (result.success) {
        showSuccessMessage('Pages saved successfully!');
        fetchPages();
      } else {
        showErrorMessage('Failed to save pages: ' + (result.message || 'Unknown error'));
      }
    })
    .catch(error => {
      console.error('Error saving pages:', error);
      showErrorMessage('An error occurred while saving.');
    });
  }

  // Load initial data
  fetchPages();
</script>

</body>
</html>
