$(function () {
  const table = $('#registrations-table').DataTable({
    ajax: {
      url: 'api.php',
      data: { action: 'list' },
      dataSrc: 'data',
      error: function (xhr) {
        let msg = 'Failed to load data';
        try { const j = JSON.parse(xhr.responseText); if (j.error) msg = j.error; } catch (e) {}
        Swal.fire({ icon: 'error', title: 'Error', text: msg });
      }
    },
    processing: true,
    deferRender: true,
    pageLength: 10,
    autoWidth: false,
    responsive: false,
    columnDefs: [
      { targets: 0, className: 'col-id' },
      { targets: 1, className: 'col-name' },
      { targets: 2, className: 'col-email' },
      { targets: 3, className: 'col-phone' },
      { targets: 4, className: 'col-scfhs' },
      { targets: 5, className: 'col-national' },
      { targets: 6, className: 'col-speciality' },
      { targets: 7, className: 'col-hospital' },
      { targets: 8, className: 'col-created' },
      { targets: 9, className: 'col-actions' }
    ],
    columns: [
      { data: 'id', defaultContent: '', width: '44px' },
      { data: null, width: '150px', render: r => `${escapeHtml(r.first_name || '')} ${escapeHtml(r.last_name || '')}`.trim() },
      { data: 'email', width: '200px', render: d => escapeHtml(d || '') },
      { data: 'phone', width: '110px', render: d => escapeHtml(d || '') },
      { data: 'scfhs_id', width: '80px', render: d => escapeHtml(d || '') },
      { data: 'national_id', width: '130px', render: d => escapeHtml(d || '') },
      { data: 'speciality', width: '120px', render: d => escapeHtml(d || '') },
      { data: 'hospital', width: '140px', render: d => escapeHtml(d || '') },
      { data: 'created_at', width: '140px', render: d => escapeHtml(d || '') },
      {
        data: null,
        orderable: false,
        searchable: false,
        width: '140px',
        render: function (row) {
          const uuid = encodeURIComponent(row.uuid || '');
          const viewHref = `../profile.php?id=${uuid}`;
          return `
            <div style="display:flex; gap:8px; flex-wrap:wrap;">
              <a class="btn btn-plain" href="${viewHref}" target="_blank" rel="noopener">View</a>
              <button class="btn btn-outline btn-delete" data-uuid="${uuid}">Delete</button>
            </div>
          `;
        }
      }
    ]
  });

  $('#registrations-table').on('click', '.btn-delete', function () {
    const uuid = $(this).data('uuid');
    if (!uuid) return;
    Swal.fire({
      icon: 'warning',
      title: 'Delete record?',
      text: 'This action cannot be undone.',
      showCancelButton: true,
      confirmButtonText: 'Yes, delete',
      cancelButtonText: 'Cancel'
    }).then((result) => {
      if (!result.isConfirmed) return;
      $.ajax({
        url: 'api.php?action=delete',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ uuid }),
      }).done((res) => {
        if (res && res.success) {
          table.ajax.reload(null, false);
        } else {
          Swal.fire({ icon: 'error', title: 'Error', text: 'Failed to delete record.' });
        }
      }).fail((xhr) => {
        let msg = 'Failed to delete record';
        try { const j = JSON.parse(xhr.responseText); if (j.error) msg = j.error; } catch (e) {}
        Swal.fire({ icon: 'error', title: 'Error', text: msg });
      });
    });
  });

  $('#btn-reset').on('click', function () {
    Swal.fire({
      icon: 'warning',
      title: 'Reset all data?',
      text: 'This will remove all registrations and reset IDs to start from 1.',
      showCancelButton: true,
      confirmButtonText: 'Yes, reset all',
      cancelButtonText: 'Cancel'
    }).then((result) => {
      if (!result.isConfirmed) return;
      $.ajax({
        url: 'api.php?action=reset_all',
        method: 'POST'
      }).done((res) => {
        if (res && res.success) {
          table.ajax.reload(null, true);
          Swal.fire({ icon: 'success', title: 'Done', text: `Removed ${res.deleted || 0} record(s).` });
        } else {
          Swal.fire({ icon: 'error', title: 'Error', text: 'Failed to reset data.' });
        }
      }).fail((xhr) => {
        let msg = 'Failed to reset data';
        try { const j = JSON.parse(xhr.responseText); if (j.error) msg = j.error; } catch (e) {}
        Swal.fire({ icon: 'error', title: 'Error', text: msg });
      });
    });
  });

  function escapeHtml(str) {
    return String(str || '')
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#039;');
  }
});
