<%- 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: "Drivers Asset Manager" }) %>

            <% const breadcrumbs=[ { label: "Dashboard" , href: "/admin/dashboard" , icon: "bi bi-house-door" }, {
              label: " Driver Asset Manager" } ]; %>
              <%- include('../../partials/utils/breadcrumb', { breadcrumbs }) %>

                <div style="display: flex; justify-content: end; align-items: center;">

                  <!-- 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: <span id="totalRows"></span> </h5>
                  </div>

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

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


                              <th data-sort="driver_id">
                                SR No.
                                <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>Expire Date</th>
                            </tr>
                          </thead>
                          <tbody></tbody>
                        </table>
                      </div>
                    </div>


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

                </div>
                <!-- Responsive Table -->

        </div>
  </main>
  <!-- Image Popup Modal -->
  <div id="imagePopup" class="popup-overlay" style="display: none;">
    <div class="popup-content">
      <button class="close-btn" onclick="closeImage()">
        x
      </button>
      <img id="popupImage" src="" alt="Preview" onerror="this.onerror=null;this.src='/car.jpg';" />
    </div>
  </div>
  <style>
    .popup-overlay {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.8);
      z-index: 9999;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .popup-content {
      position: relative;
      max-width: 90%;
      max-height: 90%;
    }

    .popup-content img {
      max-width: 100%;
      max-height: 100%;
      border-radius: 8px;
    }

    .close-btn {
      position: absolute;
      top: -15px;
      right: -15px;
      font-size: 24px;
      color: white;
      background-color: #ff4d4f;
      border: none;
      border-radius: 50%;
      width: 36px;
      height: 36px;
      display: flex;
      align-items: center;
      justify-content: center;
      line-height: 36px;
      text-align: center;
      cursor: pointer;
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
      transition: background-color 0.3s ease, transform 0.2s ease;
    }

    .close-btn:hover {
      background-color: #e60023;
      transform: scale(1.1);
    }

    .close-btn:focus {
      outline: 2px solid white;
      outline-offset: 2px;
    }
  </style>

  <script>
    // Configure the export component
    window.exportConfig = {
      csv: {
        headers: ["Driver ID", "First Name", "Last Name", "Asset", "Asset Type", "Side", "Expiry Date", "Status"],
        dataMapper: (driver) => {
          const rows = [];
          const now = new Date();

          if (driver.driverAssets?.length > 0) {
            driver.driverAssets.forEach((asset, index) => {
              try {
                const expiryDate = asset.expire_date ? new Date(asset.expire_date) : null;
                const isExpired = expiryDate ? expiryDate < now : false;
                const dateString = expiryDate ? expiryDate.toDateString() : "N/A";

                rows.push([
                  driver.driver_id,
                  maskName(driver.d_fname || ''), // masked first name
                  maskName(driver.d_fname || ''), // masked last name
                  index + 1,
                  asset.asset_type || "N/A",
                  asset.is_front ? "Front" : "Back",
                  dateString,
                  isExpired ? "Expired" : expiryDate ? "Valid" : "N/A"
                ]);
              } catch (e) {
                console.error("Error processing asset:", asset, e);
              }
            });
          } else {
            rows.push([
              driver.driver_id,
              driver.d_fname || "N/A",
              driver.d_lname || "",
              "N/A", "No Asset", "-", "-", "-"
            ]);
          }
          return rows;
        },
        filename: 'drivers_assets.csv'
      },
      pdf: {
        headers: ["Driver ID", "First Name", "Last Name", "Asset", "Asset Type", "Side", "Expiry Date", "Status"],
        dataMapper: (driver) => {
          // Same implementation as CSV for consistency
          return window.exportConfig.csv.dataMapper(driver);
        },
        title: 'Drivers Assets Report',
        filename: 'drivers_assets.pdf',
        // PDF-specific options:
        pageSize: 'A4',
        margin: {
          top: 20,
          right: 10,
          bottom: 20,
          left: 10
        },
        fontSize: 10
      },
      fetchAllUrl: '/admin/assetDrivers?limit=99999',
      currentData: []
    };
    // Set global search input for pagination
    window.globalSearchInput = '#globalSearch';

    // Initialize pagination
    let driverCounter = 0; // global counter

    const pagination = new Pagination({
      fetchUrl: '/admin/assetDrivers',
      defaultSort: {
        column: 'driver_id',
        order: 'DESC'
      },
      dataMapper: (driver) => {
        const driverIndex = driverCounter++; // increment for each driver
        const driverBgClass = driverIndex % 2 === 0 ? 'bg-light' : 'bg-white-important';

        return `
      <tr class="driver-row ${driverBgClass} border border-dark" data-driver-id="${driver.driver_id}">
        <td colspan="3" class="text-dark ${driverBgClass} p-2">
          <i class="fas fa-user"></i> Driver: ${maskName(driver.d_fname, driver.d_lname)} (ID: ${driver.driver_id})
          <button class="btn btn-sm btn-secondary float-end toggle-assets-btn" data-driver-id="${driver.driver_id}">
            <i class="fas fa-chevron-down"></i> Show Assets
          </button>
        </td>
      </tr>
      <tr class="driver-assets-row" id="assets-${driver.driver_id}" style="display: none;">
        <td colspan="3">
          <table class="table table-bordered mb-0">
            <tbody>
              ${driver.driverAssets && driver.driverAssets.length > 0
            ? driver.driverAssets.map((asset, index) => {
              const isExpired = new Date(asset.expire_date) < new Date();
              const expiredClass = isExpired ? 'text-danger' : 'text-success';
              const expiredText = isExpired ? 'Expired' : 'Valid';
              const sideIcon = asset.is_front
                ? '<i class="fas fa-car-side text-primary"></i> Front'
                : '<i class="fas fa-car-side text-secondary"></i> Back';
              const assetBgClass = index % 2 === 0 ? 'bg-light' : 'bg-white';
              return `
                      <tr class="${assetBgClass}">
                        <td>${index + 1}</td>
                        <td>
                          ${asset.image && asset.image.img_path
                  ? (asset.image.img_path.toLowerCase().endsWith('.pdf')
                      ? `<a href="${asset.image.img_path.startsWith('http') ? asset.image.img_path : '<%=IMAGE_FOLDER_PATH %>' + asset.image.img_path}" target="_blank" class="text-danger text-decoration-none" style="display:inline-block; text-align:center; padding: 5px; border: 1px dashed #dc3545; border-radius: 5px; width: 80px; background-color: #fffafb;">
                           <i class="fas fa-file-pdf fa-2x"></i><br><small style="font-weight:bold; font-size: 11px;">View PDF</small>
                         </a>`
                      : `<a href="javascript:void(0)" onclick="openImage('${asset.image.img_path.startsWith('http') ? asset.image.img_path : '<%=IMAGE_FOLDER_PATH %>' + asset.image.img_path}')" style="display:inline-block; border: 1px solid #ddd; border-radius: 5px; padding: 2px;">
                           <img src="${asset.image.img_path.startsWith('http') ? asset.image.img_path : '<%=IMAGE_FOLDER_PATH %>' + asset.image.img_path}" class="rounded" width="80px" height="50px" style="object-fit:cover;"
                                 onerror="this.onerror=null;this.src='/car.jpg';">
                         </a>`)
                  : `<em class="text-muted">No Image</em>`}
                          <br>
                          <span class="badge text-black bg-info">${asset.asset_type}</span> <br>
                          ${sideIcon}
                        </td>
<td class="${expiredClass}">
  ${asset.expire_date ? `<span class="badge ${expiredClass}">${expiredText}</span><br>` : ""}
  ${asset.expire_date
                  ? new Date(asset.expire_date).toLocaleDateString('en-GB')
                  : "N/A"}
</td>

                      </tr>
                    `;
            }).join('')
            : ` <tr> <td colspan = "3"
         class = "text-center text-muted" > No assets available </td></tr>`
          }
            </tbody>
          </table>
        </td>
      </tr>
    `;
      }
    });



    document.addEventListener('click', function (e) {
      if (e.target.closest('.toggle-assets-btn')) {
        const btn = e.target.closest('.toggle-assets-btn');
        const driverId = btn.getAttribute('data-driver-id');
        const assetRow = document.getElementById(`assets-${driverId}`);

        if (assetRow.style.display === 'none') {
          assetRow.style.display = '';
          btn.innerHTML = '<i class="fas fa-chevron-up"></i> Hide Assets';
        } else {
          assetRow.style.display = 'none';
          btn.innerHTML = '<i class="fas fa-chevron-down"></i> Show Assets';
        }
      }
    });

    // Function to open image in modal
    function openImage(imagePath) {
      document.getElementById("popupImage").src = imagePath;
      document.getElementById("imagePopup").style.display = "flex";
    }

    function closeImage() {
      document.getElementById("imagePopup").style.display = "none";
    }


    // Function to show toast notifications
    function showToast(message, type = 'error') {
      const Toast = Swal.mixin({
        toast: true,
        position: 'top-end',
        showConfirmButton: false,
        timer: 3000,
        timerProgressBar: true,
      });

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

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

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

    // Close modal when clicking outside the image
    document.getElementById('imagePopup').addEventListener('click', function (e) {
      // Check if the click is on the overlay itself, not the image
      if (e.target === this) {
        closeImage();
      }
    });
  </script>

  <%- footer %>