<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Admin Panel - Roles</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;
    }

    h2 {
      margin-top: 20px;
    }

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

    .roles-table {
      width: 100%;
      border-collapse: collapse;
      font-size: 14px;
      min-width: 600px; /* optional, helps layout */
    }

    .roles-table th, .roles-table td {
      border: 1px solid #ccc;
      padding: 12px;
      vertical-align: top;
      text-align: left;
      position: relative;
    }

    .roles-table th {
      background-color: #f0f0f0;
    }
    
    /* Sticky header */
    .roles-table thead th {
      position: sticky;
      top: 0;
      background-color: #f0f0f0;
      z-index: 10;
      box-shadow: 0 2px 5px -1px rgba(0,0,0,0.1);
    }
    
    input.role-input {
      width: 100%;
      box-sizing: border-box;
      padding: 6px 8px;
      font-size: 14px;
      border: 1px solid #ccc;
      border-radius: 3px;
    }

    textarea.pages-textarea {
      width: 100%;
      box-sizing: border-box;
      padding: 6px 8px;
      font-size: 14px;
      min-height: 70px;
      border: 1px solid #ccc;
      border-radius: 3px;
      resize: vertical;
      font-family: Arial, sans-serif;
      cursor: pointer;
    }

    .multiselect-checkboxes {
      display: none;
      position: absolute;
      top: 100%;
      left: 0;
      width: 100%;
      max-height: 200px;
      overflow-y: auto;
      background: white;
      border: 1px solid #ccc;
      border-radius: 4px;
      z-index: 1000;
      box-shadow: 0 2px 8px rgba(0,0,0,0.15);
      padding: 8px;
    }

    .multiselect-checkboxes input[type="text"] {
      position: sticky;
      top: 0;
      background: white;
      z-index: 1;
      padding: 6px 8px;
      margin-bottom: 8px;
      box-sizing: border-box;
      border: 1px solid #ccc;
      border-radius: 3px;
      width: 100%;
    }

    .multiselect-checkboxes label {
      display: block;
      margin-bottom: 5px;
      cursor: pointer;
      user-select: none;
      font-size: 13px;
    }

    .multiselect-checkboxes label input {
      margin-right: 6px;
      cursor: pointer;
    }

    .error-message {
      color: red;
      font-weight: bold;
      margin-top: 20px;
    }

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

    .action-buttons button {
      padding: 10px 16px;
      margin-right: 10px;
      font-size: 14px;
      cursor: pointer;
      border: none;
      border-radius: 4px;
      background-color: #4CAF50; /* Updated background color */
      color: white;
      display: inline-flex;
      align-items: center;
      gap: 6px;
    }
    
    .action-buttons button:hover {
      background-color: #45a049;
    }
    
    .action-buttons i {
      font-size: 16px;
    }

    .delete-btn {
      background: none;
      border: none;
      cursor: pointer;
      color: #e74c3c;
      font-size: 16px;
    }

    .delete-btn:hover {
      color: #c0392b;
    }
  </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 class="content-wrapper" id="content">
    <h2>Roles and Accessible Pages</h2>

    <div class="action-buttons">
      <button onclick="addNewRow()" title="Add Row">
        <i class="fas fa-plus"></i> Add Row
      </button>
      <button onclick="saveRoles()" title="Save Changes">
        <i class="fas fa-save"></i> Save
      </button>
    </div>

    <div class="table-container">
      <table class="roles-table" id="roles-table">
        <thead>
          <tr>
            <th>Role</th>
            <th>Pages Can Access (comma separated)</th>
            <th style="width: 60px;">Delete</th>
          </tr>
        </thead>
        <tbody>
          <!-- Rows injected here -->
        </tbody>
      </table>
    </div>

    <div id="error" class="error-message" style="display:none;"></div>
  </div>
</div>

<script>
  let allPages = [];
  let currentTextarea = null;
  let currentDropdown = null;

  async function fetchAllPages() {
    try {
      const res = await fetch('../php/fetch_pages.php');
      allPages = await res.json();
    } catch(e) {
      console.error('Failed to fetch all pages:', e);
    }
  }

  async function fetchRoles() {
    try {
      const response = await fetch('../php/fetch_roles.php');
      const roles = await response.json();

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

      roles.forEach(role => addRow(role.role, role.pages));
    } catch (err) {
      console.error('Error fetching roles:', err);
      const errorDiv = document.getElementById('error');
      errorDiv.textContent = 'Failed to load roles data.';
      errorDiv.style.display = 'block';
    }
  }

  function addNewRow() {
    addRow('', []);
  }

  function addRow(roleName, pages) {
    const tbody = document.querySelector('#roles-table tbody');

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

    const roleCell = document.createElement('td');
    const roleInput = document.createElement('input');
    roleInput.type = 'text';
    roleInput.classList.add('role-input');
    roleInput.value = roleName;
    roleCell.appendChild(roleInput);

    const pagesCell = document.createElement('td');
    pagesCell.style.position = 'relative';

    const pagesTextarea = document.createElement('textarea');
    pagesTextarea.classList.add('pages-textarea');
    pagesTextarea.value = (pages || []).join(', ');
    pagesTextarea.readOnly = true;
    pagesCell.appendChild(pagesTextarea);

    const multiSelectDiv = document.createElement('div');
    multiSelectDiv.classList.add('multiselect-checkboxes');

    const searchInput = document.createElement('input');
    searchInput.type = 'text';
    searchInput.placeholder = 'Search pages...';
    multiSelectDiv.appendChild(searchInput);

    const checkboxesWrapper = document.createElement('div');
    multiSelectDiv.appendChild(checkboxesWrapper);

    function populateCheckboxes(filter = '') {
      checkboxesWrapper.innerHTML = '';
      allPages.forEach(page => {
        if (page.toLowerCase().includes(filter.toLowerCase())) {
          const label = document.createElement('label');
          const checkbox = document.createElement('input');
          checkbox.type = 'checkbox';
          checkbox.value = page;
          label.appendChild(checkbox);
          label.appendChild(document.createTextNode(page));
          checkboxesWrapper.appendChild(label);
        }
      });

      const selectedPages = pagesTextarea.value.split(',').map(p => p.trim());
      checkboxesWrapper.querySelectorAll('input[type="checkbox"]').forEach(cb => {
        cb.checked = selectedPages.includes(cb.value);
      });
    }

    populateCheckboxes();

    searchInput.addEventListener('input', (e) => {
      populateCheckboxes(e.target.value);
    });

    pagesCell.appendChild(multiSelectDiv);

    pagesTextarea.addEventListener('click', () => {
      if (currentTextarea === pagesTextarea && currentDropdown?.style.display === 'block') {
        currentDropdown.style.display = 'none';
        currentDropdown = null;
        currentTextarea = null;
        return;
      }

      if (currentDropdown) {
        currentDropdown.style.display = 'none';
      }

      currentTextarea = pagesTextarea;
      currentDropdown = multiSelectDiv;

      populateCheckboxes();
      multiSelectDiv.style.display = 'block';
    });

    document.addEventListener('click', (e) => {
      if (
        currentTextarea &&
        currentDropdown &&
        !currentTextarea.contains(e.target) &&
        !currentDropdown.contains(e.target)
      ) {
        currentDropdown.style.display = 'none';
        currentDropdown = null;
        currentTextarea = null;
      }
    });

    multiSelectDiv.addEventListener('change', () => {
      const selected = Array.from(multiSelectDiv.querySelectorAll('input[type="checkbox"]:checked'))
                            .map(cb => cb.value);
      pagesTextarea.value = selected.join(', ');
    });

    // Delete column
    const deleteCell = document.createElement('td');
    const deleteBtn = document.createElement('button');
    deleteBtn.innerHTML = '<i class="fas fa-trash-alt"></i>';
    deleteBtn.className = 'delete-btn';
    deleteBtn.title = 'Delete this row';
    deleteBtn.onclick = () => {
      row.remove();
    };
    deleteCell.appendChild(deleteBtn);

    row.appendChild(roleCell);
    row.appendChild(pagesCell);
    row.appendChild(deleteCell);
    tbody.appendChild(row);
  }

  function saveRoles() {
    showProcessingMessage('Saving data pls wait....');

    const rows = document.querySelectorAll('#roles-table tbody tr');
    const data = [];

    rows.forEach(row => {
      const roleInput = row.querySelector('.role-input');
      const pagesTextarea = row.querySelector('.pages-textarea');

      const role = roleInput.value.trim();
      const pages = pagesTextarea.value
        .split(',')
        .map(p => p.trim())
        .filter(p => p);

      if (role) {
        data.push({ role, pages });
      }
    });

    if (data.length === 0) {
      showErrorMessage('No valid roles to save.');
      return;
    }

    fetch('../php/save_roles.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
    })
    .then(res => {
      if (!res.ok) {
        throw new Error('Server responded with an error');
      }
      return res.json();
    })
    .then(response => {
      showSuccessMessage('Roles saved successfully!');
    })
    .catch(err => {
      console.error('Save failed:', err);
      showErrorMessage('Failed to save roles.');
    });
  }

  // Utility functions for messages (assuming you have them defined elsewhere)
  function showProcessingMessage(msg) {
    const errorDiv = document.getElementById('error');
    errorDiv.style.color = 'blue';
    errorDiv.textContent = msg;
    errorDiv.style.display = 'block';
  }
  function showErrorMessage(msg) {
    const errorDiv = document.getElementById('error');
    errorDiv.style.color = 'red';
    errorDiv.textContent = msg;
    errorDiv.style.display = 'block';
  }
  function showSuccessMessage(msg) {
    const errorDiv = document.getElementById('error');
    errorDiv.style.color = 'green';
    errorDiv.textContent = msg;
    errorDiv.style.display = 'block';
    setTimeout(() => {
      errorDiv.style.display = 'none';
    }, 3000);
  }

  (async function init() {
    await fetchAllPages();
    await fetchRoles();
  })();
</script>
</body>
</html>
