   <%- header %>  <!-- pre-rendered navbar inserted -->
<main class="dashboard-main">
  <%- navbar %>  <!-- pre-rendered navbar inserted -->
  <style>
    .additionalFields {
      margin-block: 20px;
    }
  </style>

  <div class="container flex-1 pt-20 w-full">
    <%- include('../../partials/utils/title.ejs', {title: "Wallet Manager"}) %>

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

    <%- include('../../partials/utils/breadcrumb', { breadcrumbs }) %>

    <div class="">
      <div class="bg-white shadow-md rounded-lg p-3">
        <h4 class="text-lg font-semibold mb-4">General Info</h4>
        <hr />
        <div class="row mt-6">
          <!-- Transaction Type -->
          <div class="col-md-12 mb-4">
            <label class="form-label">Transaction Type *</label>
            <select id="TransactionType" name="Transaction[trans_type]" class="form-select" required>
              <option value="">Select Transaction Type</option>
              <option value="CR">Credit (CR)</option>
              <option value="DR">Debit (DR)</option>
            </select>
          </div>

          <!-- Wallet Type -->
          <div class="col-md-6 mb-4">
            <label class="form-label">Wallet Type *</label>
            <select id="WalletType" name="Transaction[type]" class="form-select" required>
              <option value="">Select Type</option>
              <% if (user.group_id !== 6) { %>
              <option value="Driver">Driver</option>
              <% } %>
              <% if (user.group_id !== 5) { %>
              <option value="User">User</option>
              <% } %>
            </select>
          </div>

          <!-- Payment Mode -->
          <div class="col-md-6 mb-4">
            <label class="form-label">Pay Mode *</label>
            <select id="payMode" name="Transaction[trans_pay_mode]" class="form-select" required>
              <option value="">Select Pay Mode</option>
              <option value="Cash">Cash</option>
              <option value="Wallet">Wallet</option>
              <option value="Card">Card</option>
            </select>
          </div>
        </div>

        <!-- Additional Fields (hidden initially) -->
        <div id="additionalFields" class="hidden-fields" style="display: none;">
          <hr class="my-4">

          <div class="row">
            <div class="col-md-6 mb-3">
              <label class="form-label">Search by ID</label>
              <input type="text" id="TransactionID" name="Transaction[user_id]" class="form-control" placeholder="Enter ID">
            </div>
            <div class="col-md-6 mb-3">
              <label class="form-label">Search by Name</label>
              <input type="text" id="TransactionName" name="Transaction[u_name]" class="form-control" placeholder="Enter name">
            </div>
            <div class="col-md-6 mb-3">
              <label class="form-label">Search by Phone</label>
              <input type="text" id="TransactionPhone" name="Transaction[u_phone]" class="form-control" placeholder="Enter phone">
            </div>
            <div class="col-md-6 mb-3">
              <label class="form-label">Search by Email</label>
              <input type="email" id="TransactionEmail" name="Transaction[u_email]" class="form-control" placeholder="Enter email">
            </div>

            <div class="col-md-6 mb-3">
              <label class="form-label">Amount *</label>
              <input type="text" oninput="
  this.value = this.value
      .replace(/[^0-9.]/g, '')
      .replace(/(\..*)\./g, '$1')
      .replace(/(\.\d{2}).+/g, '$1');" id="TransactionAmount" name="Transaction[user_pay_amount]" class="form-control" required placeholder="Enter amount">
            </div>

            <div class="col-md-12 mb-3">
              <label class="form-label">Transaction Description</label>
              <textarea id="trans_desc" name="trans_desc" class="form-control h-24" placeholder="Optional description"></textarea>
            </div>

            <div class="col-md-12 mb-3">
              <div id="totalWalletAmount" class="font-semibold"></div>
            </div>
          </div>

          <div class="text-end mt-4">
            <button id="rechargeWalletBtn" class="btn btn-primary py-2">
              Recharge Wallet
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</main>

<style>
  /* Autocomplete styling */
  .ui-autocomplete {
    max-height: 250px;
    overflow-y: auto;
    overflow-x: hidden;
    z-index: 10000 !important;
    background: white;
    border: 1px solid #ddd;
    border-radius: 4px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  }

  .ui-autocomplete .ui-menu-item {
    padding: 8px 12px;
    font-size: 14px;
    border-bottom: 1px solid #eee;
  }

  .ui-autocomplete .ui-menu-item:last-child {
    border-bottom: none;
  }

  .ui-autocomplete .ui-menu-item:hover {
    background-color: #f8f9fa;
    cursor: pointer;
  }

  .ui-state-focus {
    background-color: #e9ecef !important;
    border-color: #dee2e6 !important;
  }

  /* Form styling */
  .hidden-fields {
    transition: all 0.3s ease;
  }

  .form-label {
    font-weight: 500;
    margin-top: 0.8rem;
    margin-bottom: 0.0rem;
  }

  .btn-primary {
    background-color: #0d6efd;
    border-color: #0d6efd;
  }

  .btn-primary:hover {
    background-color: #0b5ed7;
    border-color: #0a58ca;
  }
</style>

<script>
  $(document).ready(function() {


    // Global variables
    let users = [];
    let drivers = [];
    let currentWalletType = '';
    // Show SweetAlert toast notification
    function showAlert(type, message) {
      const Toast = Swal.mixin({
        toast: true,
        position: 'top-end',
        showConfirmButton: false,
        timer: 3000,
        timerProgressBar: true,
        didOpen: (toast) => {
          toast.addEventListener('mouseenter', Swal.stopTimer)
          toast.addEventListener('mouseleave', Swal.resumeTimer)
        }
      });

      Toast.fire({
        icon: type,
        title: message
      });
    }
    // Fetch data functions
    async function fetchUsers() {
      try {
        const response = await fetch('/admin/all/passengers/options');
        if (!response.ok) throw new Error('Failed to fetch users');
        return await response.json();
      } catch (error) {
        console.error('Error fetching users:', error);
        showAlert('error', 'Failed to load users. Please refresh the page.');
        return [];
      }
    }

    async function fetchDrivers() {
      try {
        const response = await fetch('/admin/active/driver/options');
        if (!response.ok) throw new Error('Failed to fetch drivers');
        return await response.json();
      } catch (error) {
        console.error('Error fetching drivers:', error);
        showAlert('error', 'Failed to load drivers. Please refresh the page.');
        return [];
      }
    }

    // Data mapping functions
    function mapUserData(user) {
      return {
        id: user.user_id,
        name: user.u_name,
        phone: user.u_phone,
        email: user.u_email,
        wallet: user.u_wallet,
        display: `${user.user_id} - ${user.u_name} (${user.u_phone})`
      };
    }

    function mapDriverData(driver) {
      return {
        id: driver.driver_id,
        name: driver.d_name,
        phone: driver.d_phone,
        email: driver.d_email,
        wallet: driver.d_wallet,
        display: `${driver.driver_id} - ${driver.d_name} (${driver.d_phone})`
      };
    }

    // Initialize autocomplete for a field
    function initAutocomplete(selector, field, data) {
      $(selector).autocomplete({
        source: function(request, response) {
          const term = request.term.toLowerCase();
          const results = data
            .filter(item => item[field] && item[field].toString().toLowerCase().includes(term))
            .slice(0, 10) // Limit to 10 results
            .map(item => ({
              label: item.display,
              value: item[field],
              fullData: item
            }));
          response(results);
        },
        minLength: 1,
        select: function(event, ui) {
          updateFields(ui.item.fullData);
          return false;
        }
      }).autocomplete("instance")._renderItem = function(ul, item) {
        return $("<li>").append(`<div>${item.label}</div>`).appendTo(ul);
      };
    }

    let city_cur = "<%= city_cur %>"

    // Update form fields with selected data
    function updateFields(selectedItem) {
      $("#TransactionID").val(selectedItem.id);
      $("#TransactionName").val(selectedItem.name);
      $("#TransactionPhone").val(selectedItem.phone);
      $("#TransactionEmail").val(selectedItem.email || 'N/A');

      // Show wallet balance
      if (selectedItem.wallet !== undefined) {
        const balance = parseFloat(selectedItem.wallet).toFixed(2);
        const color = selectedItem.wallet >= 0 ? 'text-success' : 'text-danger';
        $("#totalWalletAmount").html(`Current Wallet Balance: <span class="${color}">${city_cur}${balance}</span>`)
          .data("currentBalance", balance)
          .show();
      }

      // Show additional fields
      $("#additionalFields").slideDown();
    }

    // Clear all additional fields
    function clearAdditionalFields() {
      $("#TransactionID, #TransactionName, #TransactionPhone, #TransactionEmail").val('');
      $("#TransactionAmount, #trans_desc").val('');
      $("#totalWalletAmount").hide().empty();
      $("#additionalFields").slideUp();
    }

    // Add error styling
    const style = document.createElement('style');
    style.textContent = `
      .is-invalid {
        border-color: #dc3545 !important;
      }
      .invalid-feedback {
        display: none;
        width: 100%;
        margin-top: 0.25rem;
        font-size: 0.875em;
        color: #dc3545;
      }
    `;
    document.head.appendChild(style);

    // Create error containers for each field
    function initErrorContainers() {
      const fields = [{
          id: 'WalletType',
          message: 'Please select a wallet type'
        },
        {
          id: 'TransactionType',
          message: 'Please select a transaction type'
        },
        {
          id: 'payMode',
          message: 'Please select a payment mode'
        },
        {
          id: 'TransactionID',
          message: 'Please select a user/driver'
        },
        {
          id: 'TransactionAmount',
          message: 'Please enter a valid amount'
        }
      ];

      fields.forEach(field => {
        const element = $(`#${field.id}`);
        if (element.length && !element.next('.invalid-feedback').length) {
          element.after(`<div class="invalid-feedback">${field.message}</div>`);
        }
      });
    }

    // Show error for a specific field
    function showError(fieldId, message) {
      const field = $(`#${fieldId}`);
      field.addClass('is-invalid');
      field.next('.invalid-feedback').text(message).show();
    }

    // Clear all errors
    function clearErrors() {
      $('.is-invalid').removeClass('is-invalid');
      $('.invalid-feedback').hide();
    }

    // Validate form before submission
    function validateForm() {
      let isValid = true;
      clearErrors();

      const walletType = $("#WalletType").val();
      const transType = $("#TransactionType").val();
      const payMode = $("#payMode").val();
      const userId = $("#TransactionID").val();
      const amount = $("#TransactionAmount").val();

      if (!walletType) {
        showError('WalletType', 'Please select a wallet type');
        isValid = false;
      }
      if (!transType) {
        showError('TransactionType', 'Please select a transaction type');
        isValid = false;
      }
      if (!payMode) {
        showError('payMode', 'Please select a payment mode');
        isValid = false;
      }
      if (!userId) {
        showError('TransactionID', 'Please select a user/driver');
        isValid = false;
      }
      if (!amount || parseFloat(amount) <= 0) {
        showError('TransactionAmount', 'Please enter a valid amount');
        isValid = false;
      }

      return isValid;
    }



    // Handle form submission
    async function handleSubmit() {
      if (!validateForm()) return;

      const walletType = $("#WalletType").val();
      const userId = $("#TransactionID").val();
      const amount = parseFloat($("#TransactionAmount").val());
      const transType = $("#TransactionType").val();
      const payMode = $("#payMode").val();
      const transDesc = $("#trans_desc").val().trim();

      const requestData = {
        amount,
        transType,
        walletType,
        payMode,
        transDesc
      };

      // Add the appropriate ID field based on wallet type
      if (walletType === "User") {
        requestData.userId = userId;
      } else {
        requestData.driverId = userId;
      }

      $("#rechargeWalletBtn").prop("disabled", true).html(`
        <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
        Processing...
      `);

      try {
        const response = await fetch("/admin/recharge-wallet", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(requestData)
        });

        const data = await response.json();

        if (!response.ok) {
          console.log(response, data )
          throw new Error(data.message || "Failed to process transaction");
        }

        showAlert('success', 'Transaction processed successfully!');

        // Update wallet balance display
        const newBalance = parseFloat(data.newBalance).toFixed(2);
        const color = newBalance >= 0 ? 'text-success' : 'text-danger';
        $("#totalWalletAmount").html(`Updated Wallet Balance: <span class="${color}">$${newBalance}</span>`)
          .data("currentBalance", newBalance);

        // Clear form fields
        $("#TransactionAmount, #trans_desc").val('');

      } catch (error) {
        console.error("Error:", error);
        showAlert('error', error.message || "An error occurred while processing the transaction");
      } finally {
        $("#rechargeWalletBtn").prop("disabled", false).text("Process Transaction");
      }
    }

    // Initialize the page
    async function initializePage() {
      // Initialize error containers
      initErrorContainers();
      // Fetch data
      users = await fetchUsers();
      drivers = await fetchDrivers();

      // Auto-select wallet type based on user group (before other initialization)
      const userGroupId = <%= user.group_id %>;
      if (userGroupId === 6) {
        // Corporate admin - auto-select User
        $('#WalletType').val('User');
      } else if (userGroupId === 5) {
        // Company admin - auto-select Driver
        $('#WalletType').val('Driver');
      }

      // Function to check if basic fields are filled
      function checkBasicFields() {
        const transType = $("#TransactionType").val();
        const walletType = $("#WalletType").val();
        const payMode = $("#payMode").val();

        return transType && walletType && payMode;
      }

      // Show/hide additional fields based on basic fields
      function toggleAdditionalFields() {
        if (checkBasicFields()) {
          $("#additionalFields").slideDown();
        } else {
          $("#additionalFields").slideUp();
        }
      }

      // Initialize autocomplete for current wallet type
      function initWalletTypeAutocomplete() {
        currentWalletType = $("#WalletType").val();

        if (currentWalletType) {
          const data = currentWalletType === "User" ? users.data.map(mapUserData) : drivers.data.map(mapDriverData);

          // Initialize autocomplete fields
          initAutocomplete("#TransactionID", "id", data);
          initAutocomplete("#TransactionName", "name", data);
          initAutocomplete("#TransactionPhone", "phone", data);
          initAutocomplete("#TransactionEmail", "email", data);
        }
      }

      // Initialize autocomplete immediately if wallet type is already selected
      if ($("#WalletType").val()) {
        initWalletTypeAutocomplete();
      }

      // Set up change handler for basic fields
      $("#TransactionType, #payMode").change(toggleAdditionalFields);

      // Special handler for WalletType that preserves field visibility
      $("#WalletType").change(function() {
        // Clear any existing selections
        $("#TransactionID, #TransactionName, #TransactionPhone, #TransactionEmail").val('');
        $("#totalWalletAmount").hide().empty();

        // Reinitialize autocomplete for new wallet type
        initWalletTypeAutocomplete();

        // Don't hide fields if other basic fields are still selected
        if (checkBasicFields()) {
          $("#additionalFields").show();
        }
      });

      // Initial check in case any fields are pre-selected
      toggleAdditionalFields();

      // Set up form submission
      $("#rechargeWalletBtn").click(handleSubmit);

      // Amount field validation
      $("#TransactionAmount").on("input", function() {
        this.value = this.value.replace(/[^0-9.]/g, '');
        if (this.value.split('.').length > 2) {
          this.value = this.value.substring(0, this.value.lastIndexOf('.'));
        }
      });
    }

    // Start the page
    initializePage();
  });
</script>

  <%- footer %>  <!-- pre-rendered navbar inserted -->
