<!DOCTYPE html>
<html lang="en">
<head>
  <?= view('shared/head') ?>
  <!-- Custom library CSS (optional) -->
  <link rel="stylesheet" type="text/css" href="<?= base_url('css/library.css') ?>">
  <!-- (Optional) Bootstrap CSS for styling tables/forms -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

  <style>
    /* Example styling for the edit-popup (modal) */
    #editModal .modal-dialog {
      max-width: 600px; /* e.g. 800px */
      max-height: 80vh; /* or 70vh, etc. */
    }
    #editModal .modal-body {
      overflow-y: auto; /* adds a vertical scrollbar if content is too tall */
    }
  </style>
</head>

<body>
  <div class="wrapper">
    <!-- Navbar (shared across pages) -->
    <?= view('layouts/navbar', ['menuItems' => $menuItems]) ?>

    <!-- Page Content -->
    <div class="content-wrapper p-4 text-navy">
      <h1>Library Database Explorer</h1>

      <!-- Simple form: table dropdown, show-limit, search box -->
      <form method="get" action="" class="form-inline mb-3">
        <!-- Table dropdown -->
        <div class="form-group mr-2">
          <label for="table_name" class="mr-2">Select a table:</label>
          <select name="table_name" id="table_name" class="form-control" onchange="this.form.submit()">
            <option value="">-- Choose a table --</option>
            <?php foreach ($tables as $tbl): ?>
              <option value="<?= esc($tbl) ?>" <?= ($tbl === $tableName) ? 'selected' : '' ?>>
                <?= esc($tbl) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <!-- Optional: "View Table" button -->
        <button type="submit" class="btn btn-primary mr-2">View Table</button>

        <!-- Show-limit dropdown -->
        <div class="form-group mr-2">
          <label for="limit" class="mr-2">Show:</label>
          <select name="limit" id="limit" class="form-control" onchange="this.form.submit()">
            <?php
              $options = [100, 250, 500, 'ALL'];
              foreach ($options as $opt):
                $selected = ($opt == $limit) ? 'selected' : '';
            ?>
              <option value="<?= $opt ?>" <?= $selected ?>><?= $opt ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <!-- Filter By Column (NEW) -->
        <?php if (!empty($tableName) && !empty($fieldNames)): ?>
          <div class="form-group mr-2">
            <label for="search_field" class="mr-2">Filter By:</label>
            <select name="search_field" id="search_field" class="form-control" onchange="this.form.submit()">
              <!-- Default = ALL -->
              <option value="ALL" <?= ('ALL' === ($searchField ?? 'ALL')) ? 'selected' : '' ?>>ALL</option>
              <?php foreach ($fieldNames as $field): ?>
                <option value="<?= esc($field) ?>" <?= ($field === ($searchField ?? 'ALL')) ? 'selected' : '' ?>>
                  <?= esc($field) ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>
        <?php endif; ?>

        <!-- Server-side Search box -->
        <div class="form-group ml-auto">
          <input
            type="text"
            name="search"
            class="form-control"
            placeholder="Search (Server-Side)"
            value="<?= esc($searchTerm ?? '') ?>"
            style="min-width: 200px;"
          >
          <!-- Optional: a 'Search' button that triggers the form submit. -->
          <button type="submit" class="btn btn-secondary ml-2">Search</button>
        </div>
      </form>

      <hr />

      <?php if ($tableName): ?>
        <h3>Table: <strong><?= esc($tableName) ?></strong></h3>

        <?php if (! empty($fieldNames)): ?>
          <!-- Pagination controls at TOP (only if limit != ALL) -->
          <?php if ($totalRows > 0 && $limit !== 'ALL'): ?>
            <nav aria-label="Table pagination (top)">
              <ul class="pagination">
                <?php for ($p = 1; $p <= $totalPages; $p++): ?>
                  <li class="page-item <?= ($p == $currentPage) ? 'active' : '' ?>">
                    <a class="page-link"
                       href="?table_name=<?= urlencode($tableName) ?>&limit=<?= urlencode($limit) ?>&search=<?= urlencode($searchTerm) ?>&search_field=<?= urlencode($searchField) ?>&page=<?= $p ?>">
                      <?= $p ?>
                    </a>
                  </li>
                <?php endfor; ?>
              </ul>
            </nav>
          <?php endif; ?>

          <div class="table-responsive">
            <table class="table table-bordered table-striped" id="libraryTable">
              <thead>
                <tr>
                  <?php foreach ($fieldNames as $field): ?>
                    <th><?= esc($field) ?></th>
                  <?php endforeach; ?>
                </tr>
              </thead>
              <tbody>
                <?php if (count($results) > 0): ?>
                  <?php foreach ($results as $row): ?>
                    <tr>
                      <?php foreach ($fieldNames as $field): ?>
                        <td
                          data-field="<?= esc($field) ?>"
                          data-id="<?= isset($row['id']) ? esc($row['id']) : '' ?>"
                          ondblclick="openEditModal(this)"
                        >
                          <?= isset($row[$field]) ? esc($row[$field]) : '' ?>
                        </td>
                      <?php endforeach; ?>
                    </tr>
                  <?php endforeach; ?>
                <?php else: ?>
                  <tr>
                    <td colspan="<?= count($fieldNames) ?>" class="text-center text-muted">
                      No matching records found.
                    </td>
                  </tr>
                <?php endif; ?>
              </tbody>
            </table>
          </div>

          <!-- Pagination controls at BOTTOM -->
          <?php if ($totalRows > 0 && $limit !== 'ALL'): ?>
            <nav aria-label="Table pagination (bottom)">
              <ul class="pagination">
                <?php for ($p = 1; $p <= $totalPages; $p++): ?>
                  <li class="page-item <?= ($p == $currentPage) ? 'active' : '' ?>">
                    <a class="page-link"
                       href="?table_name=<?= urlencode($tableName) ?>&limit=<?= urlencode($limit) ?>&search=<?= urlencode($searchTerm) ?>&search_field=<?= urlencode($searchField) ?>&page=<?= $p ?>">
                      <?= $p ?>
                    </a>
                  </li>
                <?php endfor; ?>
              </ul>
            </nav>
          <?php endif; ?>

        <?php else: ?>
          <p>No fields found for table <strong><?= esc($tableName) ?></strong> or the table is empty.</p>
        <?php endif; ?>
      <?php else: ?>
        <p>Please select a table to view its data.</p>
      <?php endif; ?>
    </div>
  </div>

  <!-- Modal for Editing -->
  <div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-scrollable">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="editModalLabel">Edit Field</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <textarea id="editContent" class="form-control" rows="5"></textarea>
          <input type="hidden" id="editFieldName" value="" />
          <input type="hidden" id="editRowId" value="" />
          <input type="hidden" id="editTableName" value="<?= esc($tableName) ?>" />
        </div>
        <div class="modal-footer">
          <!-- Close modal -->
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Go Back</button>
          <!-- Save changes -->
          <button type="button" class="btn btn-success" onclick="saveChanges()">Save</button>
        </div>
      </div>
    </div>
  </div>

  <!-- Bootstrap & jQuery JS -->
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

  <script>
    // Open modal on double-click
    function openEditModal(tdElem) {
      const currentContent = tdElem.innerText;
      const fieldName      = tdElem.getAttribute('data-field');
      const rowId          = tdElem.getAttribute('data-id');

      if (!rowId) {
        alert('This row has no "id" field, so it cannot be edited.');
        return;
      }

      document.getElementById('editContent').value   = currentContent;
      document.getElementById('editFieldName').value = fieldName;
      document.getElementById('editRowId').value     = rowId;

      $('#editModal').modal('show');
    }

    // Save changes via AJAX
    function saveChanges() {
      const newValue  = document.getElementById('editContent').value;
      const fieldName = document.getElementById('editFieldName').value;
      const rowId     = document.getElementById('editRowId').value;
      const tableName = document.getElementById('editTableName').value;

      $.ajax({
        url: '<?= base_url('library/updateField') ?>',
        method: 'POST',
        data: {
          table: tableName,
          id: rowId,
          field: fieldName,
          value: newValue
        },
        success: function(response) {
          if (response.success) {
            $('#editModal').modal('hide');
            const selector = 'td[data-id="' + rowId + '"][data-field="' + fieldName + '"]';
            $(selector).text(newValue);
          } else {
            alert('Update failed: ' + (response.message || 'Unknown error'));
          }
        },
        error: function(xhr, status, error) {
          alert('AJAX error: ' + error);
        }
      });
    }
  </script>
</body>
</html>
