   <%- 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>


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

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

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

       <%- 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 Drivers: <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="driver_id">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>Payout Amount</th>
                 <th>Status</th>
               </thead>
               <tbody></tbody>
             </table>
           </div>
         </div>


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

       </div>
     </div>
   </main>


   <!-- <script>
     let city_cur = "<%= city_cur %>"

     // Configure the export component
     window.exportConfig = {
       csv: {
         headers: ["Driver ID", "Driver Payout ID", "Name", "Email", "Phone", "Wallet", "Payout Amount", "Status"],
         dataMapper: (payout) => [
           payout.driver_id,
           payout.driver_payout_id,
           payout.driver?.d_name || "N/A",
           payout.driver?.d_email || "N/A",
           payout.driver?.c_code ? `+${payout.driver.c_code} ${payout.driver.d_phone || "N/A"}` : payout.driver?.d_phone || "N/A",
           `${(payout.driver?.d_wallet || 0).toFixed(2)}`,
           `${(payout.amount || 0).toFixed(2)}`,
           payout.status
         ],
         filename: 'driver_payouts.csv'
       },
       pdf: {
         headers: ["Driver ID", "Driver Payout ID", "Name", "Email", "Phone", "Wallet", "Payout Amount", "Status"],
         dataMapper: (payout) => [
           payout.driver_id,
           payout.driver_payout_id,
           payout.driver?.d_name || "N/A",
           payout.driver?.d_email || "N/A",
           payout.driver?.c_code ? `+${payout.driver.c_code} ${payout.driver.d_phone || "N/A"}` : payout.driver?.d_phone || "N/A",
           `${(payout.driver?.d_wallet || 0).toFixed(2)}`,
           `${(payout.amount || 0).toFixed(2)}`,
           payout.status
         ],
         title: 'Driver Payouts Report',
         filename: 'driver_payouts.pdf'
       },
       fetchAllUrl: '/admin/payoutDrivers?limit=99999',
       currentData: []
     };

     // Set global search input for pagination
     window.globalSearchInput = '#globalSearch';

     // Initialize pagination
     const pagination = new Pagination({
       fetchUrl: '/admin/payoutDrivers',
       defaultSort: {
         column: 'driver_payout_id',
         order: 'DESC'
       },
       dataMapper: (payout) => {
         const currentStatus = payout.status;
         let statusCell = "";

         if (currentStatus === "request") {
           statusCell = `
          <select class="form-select status-select" data-id="${payout.driver_payout_id}">
            <option value="request" ${currentStatus === "request" ? 'selected' : ''}>Request</option>
            <option value="reject" ${currentStatus === "reject" ? 'selected' : ''}>Reject</option>
            <option value="paid" ${currentStatus === "paid" ? 'selected' : ''}>Paid</option>
          </select>
        `;
         } else {
           statusCell = `<span class="badge ${currentStatus === 'paid' ? 'bg-success' : 'bg-danger'}">${currentStatus}</span>`;
         }

         return `
        <tr>
          <td>${payout.driver_payout_id}</td>
          <td>
            <div class="d-flex align-items-start flex-column">
              <a href="/admin/driver-detailed-report/${payout.driver?.driver_id}">
                <strong>${payout.driver?.d_name || "N/A"}</strong>
              </a>
              <div>${payout.driver?.d_email || "N/A"}</div>
              <span>${payout.driver?.c_code ? `+${payout.driver.c_code} ${payout.driver.d_phone || "N/A"}` : payout.driver?.d_phone || "N/A"}</span>
            </div>
          </td>
          <td>
            ${city_cur}${(payout.amount || 0).toFixed(2)}<br/>
            <small class="text-success">Wallet: ${city_cur}${(payout.driver?.d_wallet || 0).toFixed(2)}</small>
          </td>
          <td>
            ${statusCell}
          </td>
        </tr>
      `;
       }
     });

     // Enhanced showToast function with more options
     function showToast(message, type = 'error', position = 'top-end') {
       const Toast = Swal.mixin({
         toast: true,
         position: position,
         showConfirmButton: false,
         timer: 3000,
         timerProgressBar: true,
         didOpen: (toast) => {
           toast.addEventListener('mouseenter', Swal.stopTimer)
           toast.addEventListener('mouseleave', Swal.resumeTimer)
         }
       });

       Toast.fire({
         icon: type,
         title: message
       });
     }

     // Function to show confirmation dialog
     async function showConfirmation(title, text, confirmButtonText = 'Confirm') {
       const result = await Swal.fire({
         title: title,
         text: text,
         icon: 'question',
         showCancelButton: true,
         confirmButtonColor: '#3085d6',
         cancelButtonColor: '#d33',
         confirmButtonText: confirmButtonText
       });

       return result.isConfirmed;
     }

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

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

       // Handle status change with SweetAlert confirmation
       $(document).on('change', '.status-select', async function() {
         const payoutId = $(this).data('id');
         const newStatus = $(this).val();
         const originalStatus = $(this).val(); // Store original value

         const confirmation = await showConfirmation(
           'Confirm Status Change',
           `Are you sure you want to change the status to ${newStatus}?`,
           'Yes, change it!'
         );

         if (!confirmation) {
           // Reset to original value if cancelled
           $(this).val(originalStatus);
           return;
         }

         try {
           const response = await $.ajax({
             url: '/admin/updatePayoutStatus',
             method: 'POST',
             contentType: 'application/json',
             data: JSON.stringify({
               payout_id: payoutId,
               status: newStatus
             })
           });

           showToast(response.message, 'success');
           pagination.loadData(pagination.currentPage, $("#pageLength").val());
         } catch (error) {
           showToast('Failed to update status', 'error');
           $(this).val(originalStatus); // Revert on error
         }
       });

       // Reset form with confirmation
       $("#resetForm").click(async function() {
         const confirmation = await showConfirmation(
           'Reset Filters',
           'Are you sure you want to reset all search filters?',
           'Yes, reset!'
         );

         if (confirmation) {
           $("#searchForm")[0].reset();
           pagination.loadData(1, $("#pageLength").val());
           showToast('Filters have been reset', 'success');
         }
       });
     });
   </script> -->
   <script>
     let city_cur = "<%= city_cur %>";

     // --- Export config with masking ---
     window.exportConfig = {
       csv: {
         headers: ["Driver ID", "Driver Payout ID", "Name", "Email", "Phone", "Wallet", "Payout Amount", "Status"],
         dataMapper: (payout) => {
           const maskedName = maskName(payout.driver?.d_name || 'N/A');
           const maskedEmail = maskEmail(payout.driver?.d_email || 'N/A');
           const maskedPhone = payout.driver?.c_code ?
             `+${payout.driver.c_code} ${maskPhone(payout.driver?.d_phone || 'N/A')}` :
             maskPhone(payout.driver?.d_phone || 'N/A');

           return [
             payout.driver_id,
             payout.driver_payout_id,
             maskedName,
             maskedEmail,
             maskedPhone,
             `${(payout.driver?.d_wallet || 0).toFixed(2)}`,
             `${(payout.amount || 0).toFixed(2)}`,
             payout.status
           ];
         },
         filename: 'driver_payouts.csv'
       },
       pdf: {
         headers: ["Driver ID", "Driver Payout ID", "Name", "Email", "Phone", "Wallet", "Payout Amount", "Status"],
         dataMapper: (payout) => {
           const maskedName = maskName(payout.driver?.d_name || 'N/A');
           const maskedEmail = maskEmail(payout.driver?.d_email || 'N/A');
           const maskedPhone = payout.driver?.c_code ?
             `+${payout.driver.c_code} ${maskPhone(payout.driver?.d_phone || 'N/A')}` :
             maskPhone(payout.driver?.d_phone || 'N/A');

           return [
             payout.driver_id,
             payout.driver_payout_id,
             maskedName,
             maskedEmail,
             maskedPhone,
             `${(payout.driver?.d_wallet || 0).toFixed(2)}`,
             `${(payout.amount || 0).toFixed(2)}`,
             payout.status
           ];
         },
         title: 'Driver Payouts Report',
         filename: 'driver_payouts.pdf'
       },
       fetchAllUrl: '/admin/payoutDrivers?limit=99999',
       currentData: []
     };

     window.globalSearchInput = '#globalSearch';

     // --- Pagination table rows with masking ---
     const pagination = new Pagination({
       fetchUrl: '/admin/payoutDrivers',
       defaultSort: {
         column: 'driver_payout_id',
         order: 'DESC'
       },
       dataMapper: (payout) => {
         const maskedName = maskName(payout.driver?.d_name || 'N/A');
         const maskedEmail = maskEmail(payout.driver?.d_email || 'N/A');
         const maskedPhone = payout.driver?.c_code ?
           `+${payout.driver.c_code} ${maskPhone(payout.driver?.d_phone || 'N/A')}` :
           maskPhone(payout.driver?.d_phone || 'N/A');

         const currentStatus = payout.status;
         let statusCell = "";
         if (currentStatus === "request") {
           statusCell = `
          <select class="form-select status-select" data-id="${payout.driver_payout_id}">
            <option value="request" ${currentStatus === "request" ? 'selected' : ''}>Request</option>
            <option value="reject" ${currentStatus === "reject" ? 'selected' : ''}>Reject</option>
            <option value="paid" ${currentStatus === "paid" ? 'selected' : ''}>Paid</option>
          </select>
        `;
         } else {
           statusCell = `<span class="badge ${currentStatus === 'paid' ? 'bg-success' : 'bg-danger'}">${currentStatus}</span>`;
         }

         return `
        <tr>
          <td>${payout.driver_payout_id}</td>
          <td>
            <div class="d-flex align-items-start flex-column">
              <a href="/admin/driver-detailed-report/${payout.driver?.driver_id}">
                <strong>${maskedName}</strong>
              </a>
              <div>${maskedEmail}</div>
              <span>${maskedPhone}</span>
            </div>
          </td>
          <td>
            ${city_cur}${(payout.amount || 0).toFixed(2)}<br/>
            <small class="text-success">Wallet: ${city_cur}${(payout.driver?.d_wallet || 0).toFixed(2)}</small>
          </td>
          <td>${statusCell}</td>
        </tr>
      `;
       }
     });

     // --- Toast and confirmation helpers ---
     function showToast(message, type = 'error', position = 'top-end') {
       Swal.mixin({
         toast: true,
         position: position,
         showConfirmButton: false,
         timer: 3000,
         timerProgressBar: true,
         didOpen: (toast) => {
           toast.addEventListener('mouseenter', Swal.stopTimer)
           toast.addEventListener('mouseleave', Swal.resumeTimer)
         }
       }).fire({
         icon: type,
         title: message
       });
     }

     async function showConfirmation(title, text, confirmButtonText = 'Confirm') {
       const result = await Swal.fire({
         title: title,
         text: text,
         icon: 'question',
         showCancelButton: true,
         confirmButtonColor: '#3085d6',
         cancelButtonColor: '#d33',
         confirmButtonText: confirmButtonText
       });
       return result.isConfirmed;
     }

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

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

       // Handle status change
       $(document).on('change', '.status-select', async function() {
         const payoutId = $(this).data('id');
         const newStatus = $(this).val();
         const originalStatus = $(this).val();

         const confirmation = await showConfirmation(
           'Confirm Status Change',
           `Are you sure you want to change the status to ${newStatus}?`,
           'Yes, change it!'
         );

         if (!confirmation) {
          //  $(this).val(originalStatus);
                     pagination.loadData(pagination.currentPage, $("#pageLength").val());

           return;
         } 

         try {
           const response = await $.ajax({
             url: '/admin/updatePayoutStatus',
             method: 'POST',
             contentType: 'application/json',
             data: JSON.stringify({
               payout_id: payoutId,
               status: newStatus
             })
           });
           showToast(response.message, 'success');
           pagination.loadData(pagination.currentPage, $("#pageLength").val());
         } catch (error) {
           showToast('Failed to update status', 'error');
           $(this).val(originalStatus);
         }
       });

       // Reset form with confirmation
       $("#resetForm").click(async function() {
         const confirmation = await showConfirmation(
           'Reset Filters',
           'Are you sure you want to reset all search filters?',
           'Yes, reset!'
         );
         if (confirmation) {
           $("#searchForm")[0].reset();
           pagination.loadData(1, $("#pageLength").val());
           showToast('Filters have been reset', 'success');
         }
       });
     });
   </script>

   <%- footer %>