<!-- 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; white-space: nowrap; }
#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: 8%; }
#example th:nth-child(2), #example td:nth-child(2) { width: 60%; }
#example th:nth-child(3), #example td:nth-child(3) { width: 32%; white-space: nowrap; }

/* 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-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; margin-right: 12px; }

.company-badge {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.85rem;
    display: inline-flex;
    align-items: center;
    gap: 6px;
}
</style>

<div class="content">
  <div class="card">
    <div class="card position-relative shadow-sm rounded-4">
      <!-- Company Badge -->
      <?php if (!empty($company_name)): ?>
      <div style="position: absolute; top: 12px; left: 20px; z-index: 10;">
        <span class="company-badge">
          <i class="fas fa-building"></i> <?= htmlspecialchars($company_name) ?>
        </span>
      </div>
      <?php endif; ?>
      
      <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('document/addDocument/' . $company_id) ?>" class="btn btn-primary btn-sm" style="border-radius: 50%; width: 36px; height: 36px; padding: 0; display: flex; align-items: center; justify-content: center;" title="Add New Document">
          <i class="fa-solid fa-plus"></i>
        </a>
        <?php endif; ?>
      </div>
      <div class="card-body" style="padding-top: 50px;">
      <?php if (!empty($authority_list)): ?>
        <div class="table-responsive">
          <table class="table align-middle text-center mb-0" id="example">
            <thead>
              <tr>
                <th>Sr.No</th>
                <th style="text-align:left;">Document Name</th>
                <th>Action</th>
              </tr>
              <tr class="column-search-row">
                <th></th>
                <th><input type="text" class="column-search" data-column="1" placeholder="Search document..."></th>
                <th></th>
              </tr>
            </thead>
            <tbody>
            <?php $i = 1; foreach($authority_list as $doc): 
                $has_uploads = isset($document_has_uploads[$doc['id']]) && $document_has_uploads[$doc['id']] > 0;
                $upload_count = isset($document_has_uploads[$doc['id']]) ? $document_has_uploads[$doc['id']] : 0;
                $is_in_use = isset($document_in_use[$doc['id']]) && $document_in_use[$doc['id']];
            ?>
              <tr>
                <td><?= $i++ ?></td>
                <td style="text-align:left;"><?= htmlspecialchars($doc['document_name']) ?></td>
                <td style="white-space: nowrap;">
                  <?php if (!can_edit()): ?>
                    <!-- User doesn't have edit permission - View only -->
                    <a href="<?= base_url('document/editDocument/'.$doc['id']) ?>" class="btn btn-info btn-icon" title="View">
                      <i class="fas fa-eye"></i>
                    </a>
                  <?php elseif ($has_uploads): ?>
                    <!-- Document has uploads - View only -->
                    <a href="<?= base_url('document/editDocument/'.$doc['id']) ?>" class="btn btn-info btn-icon" title="View (<?= $upload_count ?> uploads)">
                      <i class="fas fa-eye"></i>
                    </a>
                    <?php if (can_delete()): ?>
                    <button class="btn btn-secondary btn-icon" disabled title="Cannot delete - has uploads">
                      <i class="fas fa-trash-alt"></i>
                    </button>
                    <?php endif; ?>
                  <?php else: ?>
                    <!-- Editable state -->
                    <a href="<?= base_url('document/editDocument/'.$doc['id']) ?>" class="btn btn-warning btn-icon" title="Edit">
                      <i class="fas fa-edit"></i>
                    </a>
                    <?php if (can_delete()): ?>
                      <?php if ($is_in_use): ?>
                      <button class="btn btn-secondary btn-icon" disabled title="Cannot delete - linked to document heads">
                        <i class="fas fa-trash-alt"></i>
                      </button>
                      <?php else: ?>
                      <button onclick="confirmDelete(<?= $doc['id'] ?>)" class="btn btn-danger btn-icon" title="Delete">
                        <i class="fas fa-trash-alt"></i>
                      </button>
                      <?php endif; ?>
                    <?php endif; ?>
                  <?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 documents found for this company.
            <?php if (can_edit()): ?>
            <a href="<?= base_url('document/addDocument/' . $company_id) ?>">Create your first document</a>.
            <?php endif; ?>
        </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>
var table;

$(document).ready(function() {
  if ($('#example').length) {
    table = $('#example').DataTable({
      orderCellsTop: true,
      pageLength: 10,
      order: [[1, 'asc']],
      columnDefs: [
        { orderable: false, targets: [0, 2] },
        { searchable: false, targets: [0, 2] }
      ]
    });

    // 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();
    });

    // Column search
    $('#example .column-search').on('keyup change', function() {
      var columnIdx = $(this).data('column');
      table.column(columnIdx).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;
      
      // Only show length buttons if total records > minimum page length (10)
      const totalRecords = table.data().count();
      const minPageLength = 10;
      if (totalRecords <= minPageLength) {
        $lengthContainer.hide();
        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();
  }
  
  <?php if ($this->session->flashdata('message_name')): ?>
  Swal.fire({
    icon: '<?= $this->session->flashdata('message_type') ?? 'success' ?>',
    title: '<?= $this->session->flashdata('message_name') ?>',
    showConfirmButton: false,
    timer: 2000
  });
  <?php endif; ?>
});

function resetSearch() {
  $('#example .column-search').val('');
  table.search('').columns().search('');
  table.order([[1, 'asc']]);
  table.page('first');
  table.draw();
}

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