<%- header %>
<main class="dashboard-main">
  <%- navbar %>

  <div class="container flex-1 pt-20 w-full my-4">
    <%- include('../../partials/utils/title.ejs', {title: "Configurations Manager"}) %>

    <% 
    const breadcrumbs = [
      { label: "Dashboard", href: "/admin/dashboard", icon: "bi bi-house-door" },
      { label: "Configurations Manager" }
    ];
    %>
    <%- include('../../partials/utils/breadcrumb', { breadcrumbs }) %>

    <div class="card basic-data-table" style="margin-top: 20px;">
      <div class="card-header">
        <h5 class="card-title mb-0">Total Configurations: <span id="totalRows"><%= settingsData.length %></span></h5>
      </div>

      <!-- Responsive Table -->
      <div style="padding-inline: 20px; padding-block: 20px; overflow-x: auto;">
        <div class="table-responsive bordered-table">
          <table id="settingsTable" class="table table-striped table-bordered">
            <thead>
              <tr>
                <th>ID</th>
                 <th>Title</th>
                <th>Value</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <% if (settingsData.length > 0) { %>
              <% settingsData.forEach(setting => { %>
              <tr data-setting-id="<%= setting.id %>" data-setting-type="<%= setting.type %>">
                <td><%= setting.id %></td>
    
                <td><%= setting.title %></td>
                <td class="text-truncate" style="max-width: 300px;" title="<%= setting.value %>">
                  <%= setting.value && setting.value.length > 50 ? setting.value.substring(0, 50) + '...' : setting.value || 'N/A' %>
                </td>

                <td>

                  <button data-bs-toggle="tooltip" data-tooltip="Edit configurations" onclick="openEditModal('<%= setting.type %>', '<%= setting.id %>')">
                    <a href="javascript:void(0)" class="w-32-px h-32-px bg-success-focus text-success-main rounded-circle d-inline-flex align-items-center justify-content-center">
                      <iconify-icon icon="lucide:edit"></iconify-icon>
                    </a>
                  </button>

                </td>
              </tr>
              <% }); %>
              <% } else { %>
              <tr>
                <td colspan="7" class="text-center">No settings found</td>
              </tr>
              <% } %>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</main>

<!-- Edit Settings Modal -->
<div class="modal fade" id="editSettingModal" tabindex="-1" aria-labelledby="editSettingModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" style="font-size: 18px !important; font-weight: 600 !important;" id="editSettingModalLabel">Edit Setting</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="editSettingForm">
          <input type="hidden" id="editType" name="type">
          <input type="hidden" id="editId" name="id">

          <div class="row">
            <div class="col-md-6">
              <div class="mb-3">
                <label for="editTitle" class="form-label">Title</label>
                <input type="text" class="form-control" id="editTitle" readonly>
              </div>
            </div>
            <div class="col-md-6">
              <div class="mb-3">
                <label for="editKey" class="form-label">Key</label>
                <input type="text" class="form-control" id="editKey" readonly>
              </div>
            </div>
          </div>

          <div class="mb-3">
            <label for="editValue" class="form-label">Value</label>
            <textarea class="form-control" id="editValue" name="value" rows="6" placeholder="Enter setting value..." required></textarea>
          </div>

          <div class="alert alert-info">
            <small>
              <i class="bi bi-info-circle"></i>
              This will update the <span id="typeBadge" class="badge bg-primary">setting</span> value immediately.
            </small>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <!-- <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button> -->
        <button type="button" class="btn btn-primary" onclick="updateSetting()">
        Update
        </button>
      </div>
    </div>
  </div>
</div>

<script>
  // Global variables
  let currentSetting = null;
  let editModal = null;

  // Initialize modal once when page loads
  // Initialize modal once
  function initializeModal() {
    if (!editModal) {
      const modalElement = document.getElementById('editSettingModal');
      editModal = new bootstrap.Modal(modalElement);

      modalElement.addEventListener('hidden.bs.modal', () => {
        document.getElementById('editSettingForm').reset();
        currentSetting = null;
        document.getElementById('editSettingModalLabel').textContent = 'Edit Setting';
      });
    }
  }

  // Open edit modal
  // Open edit modal
  async function openEditModal(type, id) {
    initializeModal(); // Ensure modal is initialized

    // Reset form and show loading
    document.getElementById('editSettingForm').reset();
    const modalTitle = document.getElementById('editSettingModalLabel');
    modalTitle.innerHTML = '<i   class="bi bi-hourglass-split"></i> Loading...';
    editModal.show();

    try {
      const response = await fetch(`/admin/settings/get/${type}/${id}`);
      const result = await response.json();

      if (result) {
        currentSetting = result.data;
        populateEditForm(result.data);
      } else {
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: result.message || 'Failed to load setting data',
          toast: true,
          position: 'top-end',
          timer: 4000,
          showConfirmButton: false
        });
        editModal.hide();
      }
    } catch (error) {
      console.error('Error fetching setting:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Failed to load setting data',
        toast: true,
        position: 'top-end',
        timer: 4000,
        showConfirmButton: false
      });
      editModal.hide();
    }
  }
  // Populate edit form
  function populateEditForm(data) {
    document.getElementById('editType').value = data.type;
    document.getElementById('editId').value = data.id;
    document.getElementById('editTitle').value = data.title;
    document.getElementById('editKey').value = data.key;
    document.getElementById('editValue').value = data.value;
    document.getElementById('editSettingModalLabel').textContent = `Edit: ${data.title}`;

    // Update type badge
    const typeBadge = document.getElementById('typeBadge');
    typeBadge.textContent = data.type;
    typeBadge.className = `badge bg-${data.type === 'constant' ? 'primary' : 'success'}`;
  }

  // Update setting - Send as JSON in request body
  // Update setting
  function updateSetting() {
    const value = document.getElementById('editValue').value.trim();

    if (!value) {
      Swal.fire({
        icon: 'warning',
        title: 'Warning',
        text: 'Please enter a value',
        toast: true,
        position: 'top-end',
        timer: 4000,
        showConfirmButton: false
      });
      return;
    }

    // Max value validation for driver_radius
if (currentSetting.key === "driver_radius") {
  const numericValue = Number(value);

  if (isNaN(numericValue) || numericValue > 50) {
    Swal.fire({
      icon: 'warning',
      title: 'Invalid Value',
      text: 'Driver radius cannot be more than 50.',
      toast: true,
      position: 'top-end',
      timer: 4000,
      showConfirmButton: false
    });
    return;
  }
}

    const submitBtn = document.querySelector('#editSettingModal .btn-primary');
    const originalText = submitBtn.innerHTML;
    submitBtn.innerHTML = '<i class="bi bi-hourglass-split"></i> Updating...';
    submitBtn.disabled = true;

    const requestData = {
      id: currentSetting.id,
      type: currentSetting.type,
      value: value
    };

    fetch(`/admin/settings/edit/${currentSetting.type}/${currentSetting.id}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify(requestData)
      })
      .then(response => response.json())
      .then(result => {

        console.log('Update result:', result.success == true);

        if (result.success == true) {
          Swal.fire({
            icon: 'success',
            title: 'Success',
            text: result.message,
            toast: true,
            position: 'top-end',
            timer: 3000,
            showConfirmButton: false
          });
          editModal.hide();
          updateTableRow(currentSetting.id, currentSetting.type, value);
        } else {
          Swal.fire({
            icon: 'error',
            title: 'Error',
            text: result.message,
            toast: true,
            position: 'top-end',
            timer: 4000,
            showConfirmButton: false
          });
        }
      })
      .catch(error => {
        console.error('Error:', error);
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: 'Failed to update setting',
          toast: true,
          position: 'top-end',
          timer: 4000,
          showConfirmButton: false
        });
      })
      .finally(() => {
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
      });
  }
  // Update specific table row with new value using data attributes
function updateTableRow(id, type, newValue) {
  const row = document.querySelector(`tr[data-setting-id="${id}"][data-setting-type="${type}"]`);

  if (row) {
    const valueCell = row.cells[2]; // <-- fixed index

    const displayValue = newValue.length > 50 ?
      newValue.substring(0, 50) + '...' :
      newValue;

    valueCell.innerHTML = displayValue;
    valueCell.title = newValue;

    valueCell.style.backgroundColor = '#d4edda';
    valueCell.style.transition = 'background-color 0.5s ease';
    setTimeout(() => {
      valueCell.style.backgroundColor = '';
    }, 2000);

    console.log(`Updated row ${id} with new value:`, newValue);
  } else {
    console.warn(`Row not found for id: ${id}, type: ${type}`);
  }
}

  // Show alert message
  function showAlert(message, type) {
    // Remove any existing alerts first
    const existingAlerts = document.querySelectorAll('.alert');
    existingAlerts.forEach(alert => alert.remove());

    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
    alertDiv.innerHTML = `
    ${message}
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
  `;

    document.querySelector('.container').insertBefore(alertDiv, document.querySelector('.card'));

    // Auto remove after 5 seconds
    setTimeout(() => {
      if (alertDiv.parentElement) {
        alertDiv.remove();
      }
    }, 5000);
  }

  // Initialize tooltips and modal when page loads
  document.addEventListener('DOMContentLoaded', function() {
    // Initialize Bootstrap tooltips
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    const tooltipList = tooltipTriggerList.map(function(tooltipTriggerEl) {
      return new bootstrap.Tooltip(tooltipTriggerEl);
    });

    // Initialize modal
    initializeModal();

    // Add Enter key support in modal textarea
    const editValueTextarea = document.getElementById('editValue');
    if (editValueTextarea) {
      editValueTextarea.addEventListener('keydown', function(e) {
        if (e.key === 'Enter' && e.ctrlKey) {
          updateSetting();
        }
      });
    }
  });
</script>

<%- footer %>