<!-- Main Content -->
<link rel="stylesheet" href="<?= site_url('public/assets/css/datatables-custom.css') ?>">
<style>
#example { table-layout: fixed; width: 100% !important; }
#example th, #example td { overflow: hidden; text-overflow: ellipsis; }
#example .btn-icon { padding: 4px 8px; font-size: 0.75rem; }
#example thead th { font-size: 0.8rem; padding: 8px 4px !important; }
#example tbody td { font-size: 0.8rem; padding: 6px 4px !important; vertical-align: middle; }

/* Column widths */
#example th:nth-child(1), #example td:nth-child(1) { width: 4%; }
#example th:nth-child(2), #example td:nth-child(2) { width: 28%; }
#example th:nth-child(3), #example td:nth-child(3) { width: 15%; }
<?php if (!empty($company_id)): ?>
#example th:nth-child(4), #example td:nth-child(4) { width: 13%; }
#example th:nth-child(5), #example td:nth-child(5) { width: 15%; }
#example th:nth-child(6), #example td:nth-child(6) { width: 25%; white-space: nowrap; }
<?php else: ?>
#example th:nth-child(4), #example td:nth-child(4) { width: 18%; }
#example th:nth-child(5), #example td:nth-child(5) { width: 35%; white-space: nowrap; }
<?php endif; ?>

/* Column Search Styles */
.column-search-row input, .column-search-row select {
    width: 100%;
    padding: 4px 6px;
    border: 1px solid #e2e8f0;
    border-radius: 4px;
    font-size: 0.7rem;
    background: #fff;
}
.column-search-row input:focus, .column-search-row select:focus {
    outline: none;
    border-color: #3b82f6;
    box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}
.column-search-row input::placeholder { color: #94a3b8; font-size: 0.65rem; }
.column-search-row th { background: #f8fafc !important; padding: 4px !important; }

table thead tr:first-child th {
  background: linear-gradient(135deg, #1e3a5f 0%, #2d4a6f 100%);
  color: #fff;
  border: none;
}
table thead tr:first-child th a, table thead tr:first-child th i { color: #fff; }

/* Hide Default Search */
.dataTables_filter, .dt-search { display: none !important; }

/* Page-length buttons */
.dt-length-buttons { display: flex; gap: 0; }
.dt-paging { display: flex; align-items: center; gap: 10px; }
.dt-info { white-space: nowrap; }
#example_wrapper .dt-layout-start { display: flex; align-items: center; gap: 6px; }
#example_wrapper .dt-layout-end { display: flex; align-items: center; justify-content: flex-end; }
#example_wrapper .dt-info { margin: 0; white-space: nowrap; }

.btn-disabled {
    pointer-events: none;
    opacity: 0.45;
    cursor: not-allowed;
}

#example_wrapper .dt-info {
    margin-right: 12px;
}
</style>

<div class="content">
  <div class="card">
    <div class="card position-relative shadow-sm rounded-4">
      <div class="fab-top-group" style="display: flex; gap: 8px; position: absolute; top: 8px; right: 25px; z-index: 10;">
        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="resetSearch()" title="Reset Search" style="border-radius: 50%; width: 36px; height: 36px; padding: 0;">
          <i class="fa fa-undo"></i>
        </button>
        <?php if (can_edit()): ?>
        <a href="<?= base_url('authority/create') ?>" class="btn btn-primary btn-sm" style="border-radius: 50%; width: 36px; height: 36px; padding: 0; display: flex; align-items: center; justify-content: center;">
          <i class="fa-solid fa-plus"></i>
        </a>
        <?php endif; ?>
      </div>
      <div class="card-body">
      <?php if(!empty($authorities)): ?>
        <div class="table-responsive">
          <table id="example" class="table align-middle text-center mb-0">
            <thead>
              <tr>
                <th>#</th>
                <th style="text-align:left;">Authority Name</th>
                <th style="text-align:left;">Alias</th>
                <?php if (!empty($company_id)): ?>
                <th>Company Status</th>
                <?php endif; ?>
                <th>Created On</th>
                <th>Action</th>
              </tr>
              <tr class="column-search-row">
                <th></th>
                <th><input type="text" class="column-search" data-column="1" placeholder="Search..."></th>
                <th><input type="text" class="column-search" data-column="2" placeholder="Search..."></th>
                <?php if (!empty($company_id)): ?>
                <th><select class="column-search form-select form-select-sm" data-column="3" style="font-size:0.7rem; padding:2px;">
                    <option value="">All</option>
                    <option value="Enabled">Enabled</option>
                    <option value="Not Activated">Not Activated</option>
                    <option value="Not Added">Not Added</option>
                </select></th>
                <th><input type="text" class="column-search" data-column="4" placeholder="Search..."></th>
                <?php else: ?>
                <th><input type="text" class="column-search" data-column="3" placeholder="Search..."></th>
                <?php endif; ?>
                <th></th>
              </tr>
            </thead>
            <tbody>
                <?php $i = 1; foreach($authorities as $row): 
                
                $is_enabled = false;
                
                if (isset($company_authority_status[$row->id])) {
                    $val = $company_authority_status[$row->id];
                    $is_enabled = ($val === true || $val == '1' || $val == 't');
                }
                ?>
                
              <tr>
                <td></td>
                <td style="text-align:left;"><?= $row->authority_name ?></td>
                <td style="text-align:left;"><?= $row->alias_name ?></td>
                <?php if (!empty($company_id)): ?>
                <td>
                  <?php 
                  if (isset($company_authority_status[$row->id])) {
                      if ($company_authority_status[$row->id] == 't' || $company_authority_status[$row->id] === true || $company_authority_status[$row->id] == '1') {
                          echo '<span class="badge bg-success"><i class="fas fa-check"></i> Enabled</span>';
                      } else {
                          echo '<span class="badge bg-warning text-dark"><i class="fas fa-clock"></i> Not Activated</span>';
                      }
                  } else {
                      echo '<span class="badge bg-danger"><i class="fas fa-times"></i> Not Added</span>';
                  }
                  ?>
                </td>
                <?php endif; ?>
                <td><?= date("d-M-Y", strtotime($row->created_date)); ?></td>
                <td style="white-space: nowrap;">
                  <?php if ($is_enabled): ?>
                    
                    <?php if (!empty($authority_has_uploads[$row->id])): ?>
                      <!-- Show VIEW only if this authority has uploads -->
                      <a href="<?= base_url('authority/viewAuthority/'.$row->id.'/'.$company_id) ?>" 
                        class="btn btn-info btn-icon" title="View">
                        <i class="fas fa-eye"></i>
                      </a>
                    <?php else: ?>
                      <!-- Otherwise allow Edit + Delete (if user has permission) -->
                      <?php if (can_edit()): ?>
                      <a href="<?= base_url('authority/edit/'.$row->id) ?>" class="btn btn-warning btn-icon">
                        <i class="fas fa-edit"></i>
                      </a>
                      <?php endif; ?>
                      <?php if (can_delete()): ?>
                      <button onclick="confirmDelete(<?= $row->id ?>)" class="btn btn-danger btn-icon" title="Delete">
                        <i class="fas fa-trash-alt"></i>
                      </button>
                      <?php endif; ?>
                      <?php if (!can_edit() && !can_delete()): ?>
                      <a href="<?= base_url('authority/viewAuthority/'.$row->id.'/'.$company_id) ?>" 
                        class="btn btn-info btn-icon" title="View">
                        <i class="fas fa-eye"></i>
                      </a>
                      <?php endif; ?>
                    <?php endif; ?>

                  <?php else: ?>
                      <!-- Disabled buttons -->
                      <?php if (can_edit()): ?>
                      <a class="btn btn-warning btn-icon btn-disabled" title="Enable authority to edit">
                          <i class="fas fa-edit"></i>
                      </a>
                      <?php endif; ?>
                  <?php endif; ?>

                  <?php if ($is_enabled && can_edit()): ?>
                      <?php /* if ($row->status == '1'): ?>
                        <a href="<?= site_url('authority/toggle_status/'.$row->id); ?>" 
                          class="btn btn-success btn-icon rounded-circle" 
                          onclick="return confirm('Are you sure to deactivate?');" title="Active">
                          <i class="fas fa-check"></i>
                        </a>
                      <?php else: ?>
                        <a href="<?= site_url('authority/toggle_status/'.$row->id); ?>" 
                          class="btn btn-secondary btn-icon rounded-circle" 
                          onclick="return confirm('Are you sure to activate?');" title="Inactive">
                          <i class="fas fa-times"></i>
                        </a>
                      <?php endif; */ ?>
                  <?php elseif (!can_edit()): ?>
                        <!-- View only mode - show status badge instead -->
                        <?php /*if ($row->status == '1'): ?>
                          <span class="badge bg-success">Active</span>
                        <?php else: ?>
                          <span class="badge bg-secondary">Inactive</span>
                        <?php endif; */ ?>
                  <?php else: ?>
                        <!--<a class="btn btn-success btn-icon rounded-circle btn-disabled">
                            <i class="fas fa-check"></i>
                        </a>-->
                  <?php endif; ?>
                </td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
            <?php else: ?>
              <div class="alert alert-info mt-3">
                  <i class="fas fa-info-circle"></i> No authorities were found.
              </div>
            <?php endif; ?>
      </div>
    </div>
  </div>
</div>

<script src="<?php echo site_url(); ?>public/assets/js/jquery-1.11.1.min.js"></script>
<script src="<?php echo site_url(); ?>public/assets/js/dataTables.js"></script>
<script src="<?php echo site_url(); ?>public/assets/js/dataTables.bootstrap5.js"></script>
<script src="<?php echo site_url(); ?>public/assets/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
let table;

$(document).ready(function () {
  <?php $defaultSortCol = !empty($company_id) ? 4 : 3; ?>
  
  table = $('#example').DataTable({
    orderCellsTop: true,
    fixedHeader: true,
    pageLength: 10,
    order: [[<?= $defaultSortCol ?>, 'desc']],
    columnDefs: [
      { orderable: false, targets: [0, <?= !empty($company_id) ? 5 : 4 ?>] },
      { orderSequence: ['desc', 'asc'], targets: '_all' }
    ]
  });
  

  // Recalculate serial numbers after sort/search/page
  table.on('draw.dt', function () {
    var start = table.page.info().start;
    table.column(0, {page:'current'}).nodes().each(function(cell, i) {
      cell.innerHTML = start + i + 1;
    });
    moveDtControls();
    replaceLengthDropdown();
  });

  table.draw();
  // Column search
  $('#example .column-search').on('keyup change', function () {
    let colIdx = $(this).data('column');
    table.column(colIdx).search(this.value).draw();
  });

  function moveDtControls() {
    const $wrapper = $('#example_wrapper');
    const $topRow = $wrapper.children('.row').first();
    const $dtLength = $topRow.find('.dt-length');
    const $bottomRow = $wrapper.children('.row').last();
    const $bottomLeft = $bottomRow.find('.dt-layout-start');
    const $bottomRight = $bottomRow.find('.dt-layout-end');
    const $dtInfo = $bottomRow.find('.dt-info');
    if (!$bottomLeft.find('.dt-length').length) $dtLength.appendTo($bottomLeft);
    if (!$bottomRight.find('.dt-info').length) $dtInfo.prependTo($bottomRight);
  }

  function replaceLengthDropdown() {
    const $wrapper = $('#example_wrapper');
    const $lengthContainer = $wrapper.find('.dt-length');
    if ($lengthContainer.find('.dt-length-buttons').length) return;
    const pageLengths = [10, 20, 50, -1];
    const currentLength = table.page.len();
    $lengthContainer.find('select, label').hide();
    let html = '<ul class="pagination pagination-sm mb-0 dt-length-buttons">';
    pageLengths.forEach(len => {
      const label = len === -1 ? 'All' : len;
      const isActive = (len === -1 && currentLength === -1) || (len !== -1 && currentLength === len);
      html += `<li class="page-item ${isActive ? 'active' : ''}"><button class="page-link dt-len-btn" data-len="${len}">${label}</button></li>`;
    });
    html += '</ul>';
    $lengthContainer.append(html);
  }

  $(document).on('click', '.dt-len-btn', function () {
    const len = parseInt($(this).data('len'), 10);
    table.page.len(len).draw();
    $(this).closest('.dt-length-buttons').find('.page-item').removeClass('active');
    $(this).parent('.page-item').addClass('active');
  });

  moveDtControls();
  replaceLengthDropdown();
});

function resetSearch() {
  $('#example .column-search').val('');
  table.search('').columns().search('');
  table.order([[<?= $defaultSortCol ?>, 'desc']]);
  table.page('first');
  table.draw();
}

// SweetAlert confirm delete
function confirmDelete(itemId) {
    Swal.fire({
      title: 'Are you sure?',
      text: "This will permanently delete the record!",
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#d33',
      cancelButtonColor: '#3085d6',
      confirmButtonText: 'Yes, delete it!',
      cancelButtonText: 'Cancel'
    }).then((result) => {
      if (result.isConfirmed) {
        window.location.href = `<?= base_url('authority/delete/') ?>${itemId}`;
      }
    });
  }

  // SweetAlert confirm status change
  function statusChange(itemId, status) {
    let actionText = (status === '1') ? 'activate' : 'deactivate';
    Swal.fire({
      title: 'Are you sure?',
      text: `Do you really want to ${actionText} this record?`,
      icon: 'question',
      showCancelButton: true,
      confirmButtonText: `Yes, ${actionText} it!`,
      cancelButtonText: 'Cancel'
    }).then((result) => {
      if (result.isConfirmed) {
        $.ajax({
          url: '<?= base_url("type/changeStatus"); ?>',
          method: 'POST',
          data: { id: itemId, status: status },
          success: function(response) {
            let res = JSON.parse(response);
            if (res.success) {
              Swal.fire('Success!', res.message, 'success').then(() => {
                location.reload();
              });
            } else {
              Swal.fire('Error!', res.message, 'error');
            }
          },
          error: function() {
            Swal.fire('Error!', 'Something went wrong!', 'error');
          }
        });
      }
    });
  }

</script>
