
<!-- Main Content -->
 <link rel="stylesheet" href="<?= site_url('public/assets/css/datatables-custom.css') ?>">
<style>
/* Fix table to fit within page without horizontal scroll */
#example {
    table-layout: fixed;
    width: 100% !important;
}

#example thead th {
    font-size: 0.8rem;
    padding: 8px 4px !important;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

#example tbody td {
    font-size: 0.75rem;
    padding: 5px 3px !important;
    vertical-align: middle;
    word-wrap: break-word;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* Column widths - total should be 100% */
#example th:nth-child(1), #example td:nth-child(1) { width: 3%; }   /* # */
#example th:nth-child(2), #example td:nth-child(2) { width: 10%; }  /* Authority */
#example th:nth-child(3), #example td:nth-child(3) { width: 15%; }  /* Doc Head */
#example th:nth-child(4), #example td:nth-child(4) { width: 16%; }  /* Documents */
#example th:nth-child(5), #example td:nth-child(5) { width: 8%; }   /* Doc Start */
#example th:nth-child(6), #example td:nth-child(6) { width: 7%; }   /* Frequency */
#example th:nth-child(7), #example td:nth-child(7) { width: 7%; }   /* Due Day */
#example th:nth-child(8), #example td:nth-child(8) { width: 8%; }   /* Next Due */
#example th:nth-child(9), #example td:nth-child(9) { width: 5%; }   /* Due In */
#example th:nth-child(10), #example td:nth-child(10) { width: 9%; } /* Owner */
#example th:nth-child(11), #example td:nth-child(11) { width: 12%; } /* Action */

/* Column Search Styles */
.column-search-row input {
    width: 100%;
    padding: 4px 6px;
    border: 1px solid #e2e8f0;
    border-radius: 4px;
    font-size: 0.7rem;
    background: #fff;
    transition: all 0.2s;
}
.column-search-row input: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 4px !important;
}

/* Smaller input height to match header */
.filters-row input.column-search {
  padding: 46px 6px;
  font-size: 13px;
  box-sizing: border-box;
}

/* Hide DataTables global search box */
.dataTables_filter,
.dataTables_filter label,
.dataTables_filter input,
.dt-search {
    display: none !important;
}

/* Page-length buttons match pagination */
.dt-length-buttons {
  display: flex;
  gap: 0;
}

/* Keep bottom-right aligned */
.dt-paging {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* "Showing X to Y" inline with pagination */
.dt-info {
  white-space: nowrap;
}

/* Force bottom controls into one clean row */
#example_wrapper .row.mt-2.justify-content-between {
  display: flex !important;
  align-items: center !important;
}

/* Left side: 10 / 20 / 50 / All */
#example_wrapper .dt-layout-start {
  display: flex;
  align-items: center;
  gap: 6px;
}

/* Right side: Showing X to Y */
#example_wrapper .dt-layout-end {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

/* Keep info text compact and aligned */
#example_wrapper .dt-info {
  margin: 0;
  white-space: nowrap;
}

/* ===== Rounded top corners ONLY for table header ===== */
#example {
  border-collapse: separate !important;
  border-spacing: 0;
  overflow: hidden;
}

/* Prevent background bleed on header */
#example thead tr:first-child th {
  background-clip: padding-box;
}

.dataTables_scrollHead thead tr.column-search-row {
  display: none;
}
</style>

<div class="content">
  <div class="card">
  <div class="card position-relative shadow-sm rounded-4">
    <!-- Action buttons fixed inside card -->
    <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('type/addType') ?>" 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" style="overflow-x: hidden;">
      <div>
        <table id="example" class="table align-middle text-center mb-0">
          <thead>
            <tr>
              <th>#</th>
              <th style="text-align:left;">Authority</th>
              <th style="text-align:left;">Doc Head</th>
              <th style="text-align:left;">Documents</th>
              <th style="text-align:left;">Start Date</th>
              <th style="text-align:left;">Freq</th>
              <th style="text-align:left;">Due Day</th>
              <th style="text-align:left;">Next Due</th>
              <th style="text-align:left;">Due In</th>
              <th style="text-align:left;">Owner</th>
              <th style="text-align:center;">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>
              <th><input type="text" class="column-search" data-column="3" placeholder="Search..."></th>
              <th><input type="text" class="column-search" data-column="4" placeholder="Search..."></th>
              <th><input type="text" class="column-search" data-column="5" placeholder="Search..."></th>
              <th><input type="text" class="column-search" data-column="6" placeholder="Search..."></th>
              <th><input type="text" class="column-search" data-column="7" placeholder="Search..."></th>
              <th><input type="text" class="column-search" data-column="8" placeholder="Search..."></th>
              <th><input type="text" class="column-search" data-column="9" placeholder="Search..."></th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($authority_list as $aut): ?>
              <tr>
                <td></td>
                <td style="text-align:left;"><?= $aut['authority_name']; ?></td>
                <td style="text-align:left;" ><?= $aut['type_name'] . ' (' . $aut['alias_name'] . ')' ?></td>
                <td style="text-align:left;">
                  <?php foreach (explode(',', $aut['document_names'] ?? '') as $dc => $doc): ?>
                    <?php if (!empty(trim($doc))): ?>
                      <?= ($dc + 1) . '. ' . trim($doc) ?><br>
                    <?php endif; ?>
                  <?php endforeach; ?>
                </td>
                <?php 
                  // Use company custom_start_date if set, otherwise use master document_start_date
                  $effective_start_date = !empty($aut['custom_start_date']) ? $aut['custom_start_date'] : $aut['document_start_date'];
                ?>
                <td style="text-align:left; width: 50px;">
                  <?= !empty($effective_start_date) ? date('d-M-Y', strtotime($effective_start_date)) : '-'; ?>
                </td>
                <td style="text-align:left; width: 50px;"><?= $aut['frequency']; ?></td>
                <td style="text-align:left; width: 120px;">
                  <?php
                    $doc_date = !empty($aut['frequency_start_date']) 
                                    ? $aut['frequency_start_date'] 
                                    : $aut['document_expiry_date'];

                    // Check if it's a valid full date
                    if (!empty($doc_date) && strtotime($doc_date) && strlen($doc_date) >= 8) {
                        echo date('d-M-Y', strtotime($doc_date));
                    }
                    // If it's just a number (day)
                    elseif (ctype_digit($doc_date) && (int)$doc_date >= 1 && (int)$doc_date <= 31) {
                        echo 'Day: ' . str_pad($doc_date, 2, '0', STR_PAD_LEFT);
                    }
                    else {
                        echo '-';
                    }
                  ?>
                </td>
                <?php
                  // Calculate Next Due Date dynamically based on frequency and custom_start_date
                  $next_due = '-';
                  $due_day = (int)($aut['frequency_start_date'] ?? 0);
                  $frequency = strtolower(trim($aut['frequency'] ?? ''));
                  $due_in_next = (int)($aut['due_in_same_next_month'] ?? 0);
                  
                  if ($due_day >= 1 && $due_day <= 31 && !empty($frequency)) {
                      // Get fiscal year start month from company (default jan-dec)
                      $fy = isset($fiscal_year) ? strtolower(trim($fiscal_year)) : 'jan-dec';
                      $fiscal_map = ['jan'=>1,'feb'=>2,'mar'=>3,'apr'=>4,'may'=>5,'jun'=>6,'jul'=>7,'aug'=>8,'sep'=>9,'oct'=>10,'nov'=>11,'dec'=>12];
                      $fiscal_start = 1;
                      foreach ($fiscal_map as $abbr => $month) {
                          if (strpos($fy, $abbr) === 0) {
                              $fiscal_start = $month;
                              break;
                          }
                      }
                      
                      // Parse effective start date
                      $start_date = !empty($effective_start_date) ? strtotime($effective_start_date) : strtotime('2024-01-01');
                      $start_month = (int)date('n', $start_date);
                      $start_year = (int)date('Y', $start_date);
                      
                      $current_month = (int)date('n');
                      $current_year = (int)date('Y');
                      $today = date('Y-m-d');
                      
                      // Calculate period end months based on frequency and fiscal year
                      $period_end_months = [];
                      if ($frequency == 'monthly') {
                          for ($m = 1; $m <= 12; $m++) {
                              $period_end_months[] = $m;
                          }
                      } elseif ($frequency == 'quarterly') {
                          for ($i = 0; $i < 4; $i++) {
                              $end_m = (($fiscal_start - 1 + ($i + 1) * 3) % 12);
                              $period_end_months[] = $end_m == 0 ? 12 : $end_m;
                          }
                      } elseif ($frequency == 'half yearly') {
                          $period_end_months[] = (($fiscal_start + 5 - 1) % 12) + 1;
                          $period_end_months[] = (($fiscal_start + 11 - 1) % 12) + 1;
                      } elseif ($frequency == 'yearly') {
                          $period_end_months[] = $fiscal_start == 1 ? 12 : $fiscal_start - 1;
                      }
                      
                      // Find next due date - start from start_year (from custom_start_date)
                      if (!empty($period_end_months)) {
                          // Start checking from the year of custom_start_date, check up to 2 years ahead
                          for ($check_year = $start_year; $check_year <= $start_year + 2; $check_year++) {
                              foreach ($period_end_months as $period_month) {
                                  $due_month = $due_in_next ? ($period_month == 12 ? 1 : $period_month + 1) : $period_month;
                                  $due_year = $due_in_next && $period_month == 12 ? $check_year + 1 : $check_year;
                                  
                                  // Adjust due day for month length
                                  $days_in_month = cal_days_in_month(CAL_GREGORIAN, $due_month, $due_year);
                                  $actual_due_day = min($due_day, $days_in_month);
                                  
                                  $due_date = sprintf('%04d-%02d-%02d', $due_year, $due_month, $actual_due_day);
                                  
                                  // Check if this due date is valid (period >= start date month)
                                  $period_date = sprintf('%04d-%02d-01', $check_year, $period_month);
                                  $start_date_str = date('Y-m-01', $start_date);
                                  
                                  if ($period_date >= $start_date_str) {
                                      $next_due = date('d-M-Y', strtotime($due_date));
                                      break 2;
                                  }
                              }
                          }
                      }
                  }
                ?>
                <td style="text-align:left; width: 100px;"><?= $next_due; ?></td>
                
                <td style="text-align:left;">
                    <?= ($aut['due_in_same_next_month'] == 1) ? 'Next' : 'Same'; ?>
                </td>
                <td style="text-align:left;"><?= $aut['first_name']." ".$aut['last_name']; ?></td>
                <td style="width: 200px;">
                  <?php $company_id = $this->session->userdata('company_id'); ?>
                  <?php if (!can_edit()): ?>
                  <!-- View only mode for User role -->
                  <a href="<?= base_url('type/viewType/'.$aut['id'].'/'.$company_id) ?>" class="btn btn-info btn-icon" title="View">
                    <i class="fas fa-eye"></i>
                  </a>
                  <?php if ($aut['status'] == '1'): ?>
                    <span class="badge bg-success">Active</span>
                  <?php else: ?>
                    <span class="badge bg-secondary">Inactive</span>
                  <?php endif; ?>
                  <?php elseif (!empty($aut['has_uploads']) && $aut['has_uploads'] > 0): ?>
                  <a href="<?= base_url('type/viewType/'.$aut['id'].'/'.$company_id) ?>" class="btn btn-info btn-icon" title="View (<?= $aut['has_uploads'] ?> uploads)">
                    <i class="fas fa-eye"></i>
                  </a>
                  <?php else: ?>
                  <a href="<?= base_url('type/editType/'.$aut['id'].'/'.$company_id) ?>" class="btn btn-warning btn-icon" title="Edit">
                    <i class="fas fa-edit"></i>
                  </a>
                  <?php if (can_delete()): ?>
                  <button onclick="confirmDelete(<?= $aut['id'] ?>)" class="btn btn-danger btn-icon" title="Delete">
                    <i class="fas fa-trash-alt"></i>
                  </button>
                  <?php endif; ?>
                  <?php endif; ?>
                  <?php if (can_edit() && (empty($aut['has_uploads']) || $aut['has_uploads'] == 0)): ?>
                  <?php if ($aut['status'] == '1'): ?>
                    <button onclick="statusChange(<?= $aut['id'] ?>, '0')" 
                            class="btn btn-success btn-icon rounded-circle" 
                            title="Active">
                      <i class="fas fa-check"></i>
                    </button>
                  <?php else: ?>
                    <button onclick="statusChange(<?= $aut['id'] ?>, '1')" 
                            class="btn btn-secondary btn-icon rounded-circle"
                            title="Inactive">
                      <i class="fas fa-times"></i>
                    </button>
                  <?php endif; ?>
                  <?php endif; ?>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
    
  </div>
  </div>
</div>

<!-- Scripts -->
<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="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
  // DataTable with column search
  var table = new DataTable('#example', {
      scrollX: false,
      autoWidth: false,
      orderCellsTop: true,

      order: [[1, 'asc']],
      
      columnDefs: [
          { orderable: false, targets: [0, 10] },
          { searchable: false, targets: [0, 10] },
          {
            targets: '_all',
            orderSequence: ['asc', 'desc']
          }
      ]
  });

  // 🔹 FORCE initial serial numbering (DataTables v2 fix)
  const info = table.page.info();
  table.column(0, { page: 'current' }).nodes().each(function (cell, i) {
      cell.innerHTML = info.start + i + 1;
  });

  // Column search functionality
  $('#example .column-search').on('keyup change', function() {
      var columnIdx = $(this).data('column');
      table.column(columnIdx).search(this.value).draw();
  });
  
  function resetSearch() {
      $('#example .column-search').val('');
      table.columns().search('');
      //table.order([[1, 'asc']]).draw();
      table.draw(false);
  }

  // SweetAlert flash message
  <?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; ?>

  // 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('type/deleteType/') ?>${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');
          }
        });
      }
    });
  }

  function buildLengthButtons() {
      const wrapper = document.querySelector('#example_wrapper');
      const length  = wrapper.querySelector('.dt-length');

      if (!length || length.querySelector('.dt-length-buttons')) return;

      const values = [10, 20, 50, -1];
      const current = table.page.len();

      // Hide default select + label
      length.querySelector('select')?.classList.add('d-none');
      length.querySelector('label')?.classList.add('d-none');

      const ul = document.createElement('ul');
      ul.className = 'pagination pagination-sm dt-length-buttons mb-0';

      values.forEach(v => {
          const li = document.createElement('li');
          li.className =
            'page-item ' +
            ((v === -1 && current === -1) || current === v ? 'active' : '');

          const btn = document.createElement('button');
          btn.className = 'page-link';
          btn.textContent = v === -1 ? 'All' : v;

          btn.onclick = () => {
              table.page.len(v).draw();
              ul.querySelectorAll('.page-item').forEach(x => x.classList.remove('active'));
              li.classList.add('active');
          };

          li.appendChild(btn);
          ul.appendChild(li);
      });

      length.appendChild(ul);
  }

  function moveBottomControls() {
    const wrapper = document.querySelector('#example_wrapper');
    if (!wrapper) return;

    const rows = wrapper.querySelectorAll('.row.mt-2.justify-content-between');
    if (rows.length < 2) return;

    const topRow    = rows[0];
    const bottomRow = rows[rows.length - 1];

    const dtLength = topRow.querySelector('.dt-length');
    const dtInfo   = bottomRow.querySelector('.dt-info');
    const paging   = bottomRow.querySelector('.dt-paging');

    const bottomLeft  = bottomRow.querySelector('.dt-layout-start');
    const bottomRight = bottomRow.querySelector('.dt-layout-end');

    // Move length buttons → bottom-left
    if (dtLength && bottomLeft && !bottomLeft.contains(dtLength)) {
        bottomLeft.appendChild(dtLength);
    }

    // Move info → beside pagination
    if (dtInfo && paging && !paging.contains(dtInfo)) {
        paging.prepend(dtInfo);
    }
}


  // 3️⃣ RUN ONCE after DataTable is ready
  moveBottomControls();
  buildLengthButtons();

  // 4️⃣ RUN AGAIN on every redraw (pagination, sort, length change)
  table.on('draw', function () {

  // ✅ SERIAL NUMBER (global, continuous)
  const info  = table.page.info();
  const start = info.start;

  table.column(0, { page: 'current' }).nodes().each(function (cell, i) {
      cell.innerHTML = start + i + 1;
  });

  // ✅ KEEP EXISTING BEHAVIOR
  moveBottomControls();
  buildLengthButtons();
  });

</script>