<?php require_once __DIR__ . '/../includes/auth.php'; require_login(); ?>
<div class="page-services">
  <div class="container-fluid p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h4>Services</h4>
      <?php if (has_role(['admin','super_admin'])): ?>
        <button class="btn btn-primary" id="btnAddService">Add Service</button>
      <?php endif; ?>
    </div>

    <div class="card shadow-sm">
      <div class="card-body">
        <input type="hidden" id="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
        <div class="table-responsive">
          <table class="table table-striped align-middle" id="servicesTable">
            <thead>
              <tr>
                <th style="width:70px;">ID</th>
                <th>Name</th>
                <th style="width:120px;">Active</th>
                <th style="width:160px;"></th>
              </tr>
            </thead>
            <tbody></tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="serviceModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="serviceModalTitle">Service</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form id="serviceForm">
        <div class="modal-body">
          <input type="hidden" id="svc_id" name="id">
          <div class="mb-2">
            <label class="form-label">Name</label>
            <input type="text" class="form-control" id="svc_name" name="name" required>
          </div>
          <div class="form-check">
            <input class="form-check-input" type="checkbox" id="svc_active" checked>
            <label class="form-check-label" for="svc_active">Active</label>
          </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</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
(function($){
$(function(){
  if (!$('.page-services').length) return;

  const isAdmin = <?php echo json_encode(has_role(['admin','super_admin'])); ?>;

  function loadServices(){
    $.get('api/services.php', { action:'list' }, function(res){
      const rows = res.data || [];
      const $tb = $('#servicesTable tbody').empty();
      if (!rows.length){
        $tb.append('<tr><td colspan="4" class="text-center text-muted">No services</td></tr>');
        return;
      }
      rows.forEach(r=>{
        const active = String(r.is_active||'0')==='1';
        const tr = $('<tr>');
        tr.append(`<td>${r.id}</td>`);
        tr.append(`<td>${$('<div>').text(r.name||'').html()}</td>`);
        tr.append(`<td>${active ? '<span class="badge bg-success">Yes</span>' : '<span class="badge bg-secondary">No</span>'}</td>`);
        if (isAdmin){
          tr.append(`<td class="text-end">
            <button class="btn btn-sm btn-outline-primary btn-svc-edit" data-id="${r.id}">Edit</button>
            <button class="btn btn-sm btn-outline-danger btn-svc-del" data-id="${r.id}">Delete</button>
          </td>`);
        } else {
          tr.append('<td></td>');
        }
        $tb.append(tr);
      });
    });
  }

  function openModal(mode, data){
    $('#serviceForm')[0].reset();
    $('#svc_id').val('');
    $('#svc_active').prop('checked', true);
    if (mode==='add'){
      $('#serviceModalTitle').text('Add Service');
    } else {
      $('#serviceModalTitle').text('Edit Service');
      $('#svc_id').val(data.id);
      $('#svc_name').val(data.name||'');
      $('#svc_active').prop('checked', String(data.is_active||'0')==='1');
    }
    bootstrap.Modal.getOrCreateInstance(document.getElementById('serviceModal')).show();
  }

  $('#btnAddService').on('click', function(){
    if (!isAdmin) return;
    openModal('add', {});
  });

  $(document).on('click', '.btn-svc-edit', function(){
    if (!isAdmin) return;
    const id = $(this).data('id');
    $.get('api/services.php', { action:'list' }, function(res){
      const row = (res.data||[]).find(x=>String(x.id)===String(id));
      if (!row) return;
      openModal('edit', row);
    });
  });

  $(document).on('click', '.btn-svc-del', function(){
    if (!isAdmin) return;
    const id = $(this).data('id');
    if (!confirm('Delete this service?')) return;
    const fd = new FormData();
    fd.append('csrf', $('#csrf').val());
    fd.append('action', 'delete');
    fd.append('id', id);
    $.ajax({ url:'api/services.php', method:'POST', data:fd, processData:false, contentType:false })
      .done(()=>loadServices())
      .fail(xhr=>alert((xhr.responseJSON&&xhr.responseJSON.message)||'Failed'));
  });

  $('#serviceForm').on('submit', function(e){
    e.preventDefault();
    if (!isAdmin) return;
    const id = ($('#svc_id').val()||'').trim();
    const fd = new FormData();
    fd.append('csrf', $('#csrf').val());
    fd.append('name', $('#svc_name').val());
    fd.append('is_active', $('#svc_active').is(':checked') ? '1' : '0');
    if (id){
      fd.append('action','update');
      fd.append('id', id);
    } else {
      fd.append('action','create');
    }
    $.ajax({ url:'api/services.php', method:'POST', data:fd, processData:false, contentType:false })
      .done(function(){
        bootstrap.Modal.getOrCreateInstance(document.getElementById('serviceModal')).hide();
        loadServices();
      })
      .fail(xhr=>alert((xhr.responseJSON&&xhr.responseJSON.message)||'Failed'));
  });

  loadServices();
});
})(jQuery);
</script>
