<div class="d-flex justify-content-between align-items-center mb-4">
    <h2>Manage {{title}}</h2>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addModal"><i class="bi bi-plus"></i> Add New</button>
</div>

<div class="card">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="table-light">
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        {{#if relationships}}<th>{{relationships.label}}</th>{{/if}}
                        <th>Status</th>
                        <th class="text-end">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    {{#each data}}
                    <tr>
                        <td>{{this.id}}</td>
                        <td>{{this.name}}</td>
                        {{#if ../relationships}}<td>{{this.rel_name}}</td>{{/if}}
                        <td>
                            {{#if this.status}}
                                <span class="badge bg-success">Active</span>
                            {{else}}
                                <span class="badge bg-danger">Inactive</span>
                            {{/if}}
                        </td>
                        <td class="text-end">
                            <button class="btn btn-sm btn-outline-secondary" onclick='openEditModal({{json this}})'><i class="bi bi-pencil"></i></button>
                            <button class="btn btn-sm btn-outline-danger" onclick="deleteRecord({{this.id}})"><i class="bi bi-trash"></i></button>
                        </td>
                    </tr>
                    {{/each}}
                    {{#if (eq data.length 0)}}
                    <tr><td colspan="5" class="text-center py-4">No records found.</td></tr>
                    {{/if}}
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Pagination -->
{{#if (gt totalPages 1)}}
<nav class="mt-4">
    <ul class="pagination justify-content-center">
        <li class="page-item {{#unless hasPrev}}disabled{{/unless}}">
            <a class="page-link" href="?page={{prevPage}}">Previous</a>
        </li>
        <li class="page-item disabled"><a class="page-link">Page {{page}} of {{totalPages}}</a></li>
        <li class="page-item {{#unless hasNext}}disabled{{/unless}}">
            <a class="page-link" href="?page={{nextPage}}">Next</a>
        </li>
    </ul>
</nav>
{{/if}}

<!-- Add Modal -->
<div class="modal fade" id="addModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <form id="addForm">
      <div class="modal-header">
        <h5 class="modal-title">Add {{title}}</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
          <input type="hidden" id="addTable" value="{{table}}">
          <div class="mb-3">
              <label>Name</label>
              <input type="text" class="form-control" id="addName" required>
          </div>
          {{#if relationships}}
          <div class="mb-3">
              <label>{{relationships.label}}</label>
              <select class="form-select" id="addRelId" required>
                  <option value="">Select {{relationships.label}}</option>
                  {{#each relationData}}
                  <option value="{{this.id}}">{{this.name}}</option>
                  {{/each}}
              </select>
          </div>
          {{/if}}
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary">Save</button>
      </div>
      </form>
    </div>
  </div>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <form id="editForm">
      <div class="modal-header">
        <h5 class="modal-title">Edit {{title}}</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
          <input type="hidden" id="editTable" value="{{table}}">
          <input type="hidden" id="editId">
          <div class="mb-3">
              <label>Name</label>
              <input type="text" class="form-control" id="editName" required>
          </div>
          {{#if relationships}}
          <div class="mb-3">
              <label>{{relationships.label}}</label>
              <select class="form-select" id="editRelId" required>
                  <option value="">Select {{relationships.label}}</option>
                  {{#each relationData}}
                  <option value="{{this.id}}">{{this.name}}</option>
                  {{/each}}
              </select>
          </div>
          {{/if}}
          <div class="mb-3">
              <label>Status</label>
              <select class="form-select" id="editStatus">
                  <option value="true">Active</option>
                  <option value="false">Inactive</option>
              </select>
          </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary">Save Changes</button>
      </div>
      </form>
    </div>
  </div>
</div>

<script>
document.getElementById('addForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const data = {
        table: document.getElementById('addTable').value,
        name: document.getElementById('addName').value
    };
    const relEl = document.getElementById('addRelId');
    if (relEl) data.rel_id = relEl.value;

    const res = await fetch('/admin/master/add', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) });
    const json = await res.json();
    if (json.success) window.location.reload();
    else alert(json.message);
});

function openEditModal(record) {
    document.getElementById('editId').value = record.id;
    document.getElementById('editName').value = record.name;
    document.getElementById('editStatus').value = record.status ? 'true' : 'false';
    const relEl = document.getElementById('editRelId');
    if (relEl) relEl.value = record.state_id || record.religion_id || '';
    new bootstrap.Modal(document.getElementById('editModal')).show();
}

document.getElementById('editForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const data = {
        table: document.getElementById('editTable').value,
        id: document.getElementById('editId').value,
        name: document.getElementById('editName').value,
        status: document.getElementById('editStatus').value
    };
    const relEl = document.getElementById('editRelId');
    if (relEl) data.rel_id = relEl.value;

    const res = await fetch('/admin/master/edit', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) });
    const json = await res.json();
    if (json.success) window.location.reload();
    else alert(json.message);
});

async function deleteRecord(id) {
    if (!confirm('Are you sure you want to delete this record?')) return;
    const table = document.getElementById('addTable').value;
    const res = await fetch('/admin/master/delete', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ table, id }) });
    const json = await res.json();
    if (json.success) window.location.reload();
    else alert(json.message);
}
</script>
