   <%- header %>
   <!-- pre-rendered navbar inserted -->
   <main class="dashboard-main">
     <%- navbar %>
     <!-- pre-rendered navbar inserted -->
          <%- include('../../partials/utils/mask.ejs') %>
<script src="/js/pagination.js"></script>
<style>
  .row-expired {
    background-color: #ffe5e5;
    color: #a94442 !important;
    /* font-weight: bold; */
  }

    .row-expired td{
    background-color: #ffe5e5;
    color: #760e0c !important;
    /* font-weight: bold; */
  }

  .row-active {
    background-color: #e9fce9;
    color: #2e7d32;
  }

  .status-badge {
    display: inline-block;
    padding: 4px 10px;
    border-radius: 6px;
    font-size: 14px;
    font-weight: 600;
  }

  .status-badge.subscribed {
    background-color: #d4edda;
    color: #155724;
  }

  .status-badge.expired {
    background-color: #f8d7da;
    color: #721c24;
  }

  .driver-name {
    /* font-weight: 600; */
    /* color: #333; */
  }

  .driver-phone {
    font-size: 13px;
    color: #777;
  }
</style>

 
  <div class="container flex-1 pt-20 w-full my-4">

    <%- include('../../partials/utils/title.ejs', {title: "Driver Subscriptions"}) %>

    <% 
    const breadcrumbs = [
      { label: "Dashboard", href: "/admin/dashboard", icon: "bi bi-house-door" },
       { label: "Driver Subscriptions" }
    ];
  %>

    <%- include('../../partials/utils/breadcrumb', { breadcrumbs }) %>
    <div style="display: flex; justify-content: space-between; align-items: center;">

      <%- include('../../partials/utils/export-buttons.ejs') %>
      <!-- Offcanvas for Search Filter Panel -->
      <%- include('../../partials/utils/searchFilter-withApi.ejs') %>
    </div>


    <div class="card basic-data-table" style="margin-top: 20px;">
      <div class="card-header">
        <h5 class="card-title mb-0">Total Driver Subscriptions: <span id="totalRows"></span> </h5>
      </div>

      <%- include('../../partials/globalSearch.ejs') %>


      <div style="padding-inline: 20px; overflow-x: auto;">
        <div class="table-responsive bordered-table">
          <table id="tripsTable" class="table table-striped table-bordered">
            <thead>

              <th data-sort="subscription_id">Subscription ID <span class="sort-icons">
                  <i class="fa fa-sort sort-neutral"></i>
                  <i class="fa fa-sort-up sort-asc"></i>
                  <i class="fa fa-sort-down sort-desc"></i>
                </span></th>
              <th data-sort="driver_id">Driver ID <span class="sort-icons">
                  <i class="fa fa-sort sort-neutral"></i>
                  <i class="fa fa-sort-up sort-asc"></i>
                  <i class="fa fa-sort-down sort-desc"></i>
                </span></th>
              <th>Driver Detail</th>
              <th>
                Package
              </th>
              <th>
                Pay Mode
              </th>

              <th>Paid Amount</th>
              <th>Commission</th>
              <th>Start Date</th>
              <th>Expiry Date</th>
              <th>Status</th>

              </tr>
            </thead>
            <tbody></tbody>
          </table>
        </div>
      </div>


      <div class="pagination">
        <div id="pagination"></div>
      </div>

    </div>


  </div>

</main>



<script>
  // --- Export config with masking ---
  window.exportConfig = {
    csv: {
      headers: ["Subscription ID", "Driver ID", "Driver Name", "Phone", "Category", 
               "Payment Mode", "Amount", "Commission", "Start Date", "End Date", "Status"],
      dataMapper: (driver) => {
        const today = new Date().toISOString().split("T")[0];
        const isExpired = driver.end_date < today;
        const status = isExpired ? "Expired" : "Subscribed";

        return [
          driver.subscription_id,
          driver.driver_id,
          maskName(driver.driver.d_name || "N/A"),
          maskPhone(driver.driver.d_phone || "N/A"),
          driver.category.cat_name || "N/A",
          driver.pay_mode || "N/A",
          driver.pay_amt > 0 ? `${driver.pay_amt.toFixed(2)}` : "0.00",
          driver.comp_comm > 0 ? `${driver.comp_comm.toFixed(2)}` : "0.00",
          driver.start_date,
          driver.end_date,
          status
        ];
      },
      filename: 'driver_subscriptions.csv'
    },
    pdf: {
      headers: ["Subscription ID", "Driver ID", "Driver Name", "Phone", "Category", 
               "Payment Mode", "Amount", "Commission", "Start Date", "End Date", "Status"],
      dataMapper: (driver) => {
        const today = new Date().toISOString().split("T")[0];
        const isExpired = driver.end_date < today;
        const status = isExpired ? "Expired" : "Subscribed";

        return [
          driver.subscription_id,
          driver.driver_id,
          maskName(driver.driver.d_name || "N/A"),
          maskPhone(driver.driver.d_phone || "N/A"),
          driver.category.cat_name || "N/A",
          driver.pay_mode || "N/A",
          `${(driver.pay_amt || 0).toFixed(2)}`,
          `${(driver.comp_comm || 0).toFixed(2)}`,
          driver.start_date,
          driver.end_date,
          status
        ];
      },
      title: 'Driver Subscriptions Report',
      filename: 'driver_subscriptions.pdf',
      styles: {
        header: { fillColor: '#2c3e50', textColor: '#ffffff' },
        alternateRow: { fillColor: '#f8f9fa' }
      }
    },
    fetchAllUrl: '/admin/driver-subscription?limit=all',
    currentData: []
  };

  window.globalSearchInput = '#globalSearch';

  const pagination = new Pagination({
    fetchUrl: '/admin/driver-subscription',
    defaultSort: { column: 'end_date', order: 'DESC' },
    dataMapper: (driver) => {
      const today = new Date().toISOString().split("T")[0];
      const isExpired = driver.end_date < today;
      const statusLabel = isExpired ? "Expired" : "Subscribed";

      const maskedName = maskName(driver.driver.d_name || "N/A");
      const maskedPhone = maskPhone(driver.driver.d_phone || "N/A");

      return `
        <tr class="${isExpired ? 'row-expired' : 'row-active'}">
          <td>${driver.subscription_id}</td>
          <td>${driver.driver_id}</td>
          <td>
            <div class="driver-name">${maskedName}</div>
            <div class="driver-phone">${maskedPhone}</div>
          </td>
          <td>${driver.category.cat_name}</td>
          <td>${driver.pay_mode}</td>
          <td>${driver.pay_amt.toFixed(2)}</td>
          <td>${driver.comp_comm.toFixed(2)}</td>
<td>${formatDate(driver.start_date)}</td>
<td>${formatDate(driver.end_date)}</td>
          <td>
            <span class="status-badge ${isExpired ? 'expired' : 'subscribed'}">
              ${statusLabel}
            </span>
          </td>
        </tr>
      `;
    },
    onDataLoaded: (data) => {
      window.exportConfig.currentData = data;
    }
  });
 

  function exportData(format) {
    const config = window.exportConfig[format];
    if (window.exportConfig.currentData.length === 0) {
      showToast('No data to export', 'warning');
      return;
    }

    if (config.fetchAllUrl) {
      fetch(config.fetchAllUrl)
        .then(response => response.json())
        .then(data => {
          if (data.success && data.data.length > 0) {
            generateExportFile(data.data, format);
          } else {
            showToast('Failed to fetch data for export', 'error');
          }
        })
        .catch(error => {
          console.error('Export error:', error);
          showToast('Export failed', 'error');
        });
    } else {
      generateExportFile(window.exportConfig.currentData, format);
    }
  }

  function generateExportFile(data, format) {
    const config = window.exportConfig[format];
    const exportData = data.map(config.dataMapper);

    if (format === 'csv') {
      let csvContent = config.headers.join(',') + '\n';
      exportData.forEach(row => {
        csvContent += row.map(field => `"${field}"`).join(',') + '\n';
      });

      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.setAttribute('href', url);
      link.setAttribute('download', config.filename);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } else if (format === 'pdf') {
      const { jsPDF } = window.jspdf;
      const doc = new jsPDF();
      doc.setFontSize(18);
      doc.text(config.title, 14, 15);
      doc.setFontSize(10);
      doc.text(`Generated on: ${new Date().toLocaleString()}`, 14, 22);
      const tableData = [config.headers, ...exportData];
      doc.autoTable({
        startY: 30,
        head: [tableData[0]],
        body: tableData.slice(1),
        theme: 'grid',
        styles: { fontSize: 8, cellPadding: 3, overflow: 'linebreak' },
        headStyles: config.styles?.header,
        alternateRowStyles: config.styles?.alternateRow
      });
      doc.save(config.filename);
    }
  }

  function showToast(message, type = 'error') {
    Swal.mixin({
      toast: true,
      position: 'top-end',
      showConfirmButton: false,
      timer: 3000,
      timerProgressBar: true,
    }).fire({ icon: type, title: message });
  }

  $(document).ready(function() {
    const defaultLimit = $("#pageLength").val();
    pagination.loadData(1, defaultLimit);

    $("#pageLength").change(function() {
      const newLimit = $(this).val();
      pagination.loadData(1, newLimit);
    });

    $("#export-csv").click(() => exportData('csv'));
    $("#export-pdf").click(() => exportData('pdf'));
  });
</script>

<%- footer %>