<?php require_once __DIR__ . '/../includes/auth.php'; require_login(); ?>
<div class="page-company_licenses">
  <div class="container-fluid p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h4>Company Licenses</h4>
      <button id="cl_btnNew" class="btn btn-primary btn-sm">Add License</button>
    </div>

    <div id="cl_alerts" class="mb-2"></div>

    <div class="card shadow-sm">
      <div class="card-body">
        <div class="table-responsive">
          <table class="table table-sm align-middle" id="cl_table">
            <thead>
              <tr>
                <th>Institute</th>
                <th>License Name</th>
                <th>License No</th>
                <th>Renew Date</th>
                <th>Expiry Date</th>
                <th>Contact</th>
                <th>Remark</th>
                <th style="width:110px">Actions</th>
              </tr>
            </thead>
            <tbody></tbody>
          </table>
        </div>
      </div>
    </div>

    <input type="hidden" id="cl_csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>" />
  </div>
</div>

<div class="modal fade" id="cl_modal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">License</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form id="cl_form">
        <div class="modal-body">
          <input type="hidden" name="csrf" id="cl_form_csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
          <input type="hidden" name="id" id="cl_id">
          <div class="row g-2">
            <div class="col-md-6">
              <label class="form-label">Institute Name<span class="text-danger">*</span></label>
              <input type="text" class="form-control" name="institute_name" id="cl_institute_name" required>
            </div>
            <div class="col-md-6">
              <label class="form-label">Address</label>
              <input type="text" class="form-control" name="address" id="cl_address">
            </div>
            <div class="col-md-4">
              <label class="form-label">Contact Person</label>
              <input type="text" class="form-control" name="contact_person" id="cl_contact_person">
            </div>
            <div class="col-md-4">
              <label class="form-label">Contact Number</label>
              <input type="text" class="form-control" name="contact_number" id="cl_contact_number">
            </div>
            <div class="col-md-4">
              <label class="form-label">License Name</label>
              <input type="text" class="form-control" name="license_name" id="cl_license_name">
            </div>
            <div class="col-md-4">
              <label class="form-label">License No</label>
              <input type="text" class="form-control" name="license_no" id="cl_license_no">
            </div>
            <div class="col-md-4">
              <label class="form-label">Renew Date</label>
              <input type="date" class="form-control" name="renew_date" id="cl_renew_date">
            </div>
            <div class="col-md-4">
              <label class="form-label">Expiry Date</label>
              <input type="date" class="form-control" name="expiry_date" id="cl_expiry_date">
            </div>
            <div class="col-12">
              <label class="form-label">Remark</label>
              <textarea class="form-control" name="remark" id="cl_remark" rows="2"></textarea>
            </div>
          </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(){
  if (!$('.page-company_licenses').length) return;
  const $tbody = $('#cl_table tbody');
  const $csrf = $('#cl_csrf');

  function loadLicenses(){
    $.get('api/company_licenses.php', { action:'list' }, function(res){
      const rows = res.data || [];
      $tbody.empty();
      let expiredCount = 0;
      const today = new Date().toISOString().slice(0,10);
      rows.forEach(r => {
        const tr = $('<tr>').attr('data-id', r.id);
        let isExpired = false;
        if (r.expiry_date){
          if (r.expiry_date < today){
            isExpired = true;
            expiredCount++;
          }
        }
        if (isExpired){ tr.addClass('table-danger'); }
        tr.append(`<td>${$('<div>').text(r.institute_name||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(r.license_name||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(r.license_no||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(r.renew_date||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(r.expiry_date||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text((r.contact_person||'') + (r.contact_number? ' / '+r.contact_number : '')).html()}</td>`);
        tr.append(`<td>${$('<div>').text(r.remark||'').html()}</td>`);
        tr.append(`<td>
          <button class="btn btn-sm btn-outline-primary me-1 cl-edit" data-id="${r.id}"><i class="bi bi-pencil"></i></button>
          <button class="btn btn-sm btn-outline-danger cl-del" data-id="${r.id}"><i class="bi bi-trash"></i></button>
        </td>`);
        $tbody.append(tr);
      });
      renderAlerts(expiredCount);
      if (!rows.length){
        $tbody.append('<tr><td colspan="8" class="text-center text-muted">No licenses</td></tr>');
      }
    }).fail(xhr => {
      alert((xhr.responseJSON && xhr.responseJSON.message) || 'Failed to load licenses');
    });
  }

  function renderAlerts(expiredCount){
    const $wrap = $('#cl_alerts');
    $wrap.empty();
    if (expiredCount > 0){
      $wrap.append(`<div class="alert alert-danger py-1 mb-2">${expiredCount} license(s) have expired. Please review.</div>`);
    }
  }

  $('#cl_btnNew').on('click', function(){
    $('#cl_form')[0].reset();
    $('#cl_id').val('');
    $('#cl_modal').modal('show');
  });

  $tbody.on('click', '.cl-edit', function(){
    const id = $(this).data('id');
    $.get('api/company_licenses.php', { action:'get', id }, function(res){
      const d = res.data || {};
      $('#cl_id').val(d.id||'');
      $('#cl_institute_name').val(d.institute_name||'');
      $('#cl_address').val(d.address||'');
      $('#cl_contact_person').val(d.contact_person||'');
      $('#cl_contact_number').val(d.contact_number||'');
      $('#cl_license_name').val(d.license_name||'');
      $('#cl_license_no').val(d.license_no||'');
      $('#cl_renew_date').val(d.renew_date||'');
      $('#cl_expiry_date').val(d.expiry_date||'');
      $('#cl_remark').val(d.remark||'');
      $('#cl_modal').modal('show');
    });
  });

  $tbody.on('click', '.cl-del', function(){
    if (!confirm('Delete this license?')) return;
    const id = $(this).data('id');
    const fd = new FormData();
    fd.append('csrf', $csrf.val());
    fd.append('action', 'delete');
    fd.append('id', id);
    $.ajax({ url:'api/company_licenses.php', method:'POST', data:fd, processData:false, contentType:false })
      .done(function(){ loadLicenses(); })
      .fail(xhr => alert((xhr.responseJSON && xhr.responseJSON.message) || 'Delete failed'));
  });

  $('#cl_form').on('submit', function(e){
    e.preventDefault();
    const fd = new FormData(this);
    fd.append('action','save');
    $.ajax({ url:'api/company_licenses.php', method:'POST', data:fd, processData:false, contentType:false })
      .done(function(){ $('#cl_modal').modal('hide'); loadLicenses(); })
      .fail(xhr => alert((xhr.responseJSON && xhr.responseJSON.message) || 'Save failed'));
  });

  loadLicenses();
})();
</script>
