   <%- header %>
   <!-- pre-rendered navbar inserted -->
   <main class="dashboard-main">
     <%- navbar %>
     <!-- pre-rendered navbar inserted -->


  <div class="container pt-20 ">

    <%- include('../../partials/utils/title.ejs', {title: "Add Reward Manager"}) %>



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


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

    <div class="  mt-4">
      <form id="rewardForm" class=" bg-white shadow-md rounded-lg" style="padding: 20px;">
        <h4 class="text-lg font-semibold mb-4">General Info</h4>

        <div class="row">
          <!-- City -->
             <div class="">
  <label for="city_id" class="form-label">Location</label>
  <select class="form-select" id="city_id" name="city_id">
    <option value="">Loading cities...</option>
  </select>
</div>


          <!-- Reward Mode -->
          <div class="col-md-12 mb-4">
            <label class="form-label">Reward Mode</label>
            <select id="rewardmode" name="rewardmode" class="form-select" >
              <option value="">Select Reward Mode</option>
              <option value="user">User</option>
              <option value="driver">Driver</option>
            </select>
          </div>

          <!-- Reward Value -->
          <div class="col-md-12 mb-4">
            <label class="form-label">Reward Value</label>
            <input type="number" id="amount" name="amount" class="form-control" >
          </div>

          <!-- Reward Description (textarea) -->
          <div class="col-md-12 mb-4">
            <label class="form-label">Reward Description</label>
            <textarea id="des" name="des" class="form-control" rows="4" ></textarea>
          </div>

          <!-- Submit Button -->
          <div class="col-md-12 text-center" style="display: flex; justify-content:end; margin-top: 20px;">
            <button type="submit" class="btn btn-primary">Add Reward</button>
          </div>
        </div>
      </form>
    </div>

  </div>
  </div>
  <script>
    // Define form configuration
    const formConfig = {
      formId: "rewardForm",
      fields: [
        {
          name: "city_id",
          type: "select",
          required: true,
          messages: {
            required: "location is required"
          }
        },{
          name: "rewardmode",
          type: "select",
          required: true,
          messages: {
            required: "Value is required"
          }
        },
        {
          name: "amount",
          type: "text",
          required: true,
          messages: {
            required: "Amount is required"
          }
        },
   
      ]
    };
  </script>

  <script src="/js/validator/validation.js"></script>
  <script>
    const formValidator = setupFormValidation(
      formConfig.formId,
      formConfig.fields
    );

    $(document).ready(function() {
      $("#rewardForm").on("submit", function(e) {
        e.preventDefault();
        if (!formValidator.validateForm()) {
          console.log('Form validation failed');
          return;
        }

        const data = {
          cityId: $("#city_id").val(),
          rewardmode: $("#rewardmode").val(),
          amount: $("#amount").val(),
          des: $("#des").val()
        };

        $.ajax({
          url: "/admin/addReward", // <-- your API endpoint
          type: "POST",
          data: data,
          success: function(response) {
            console.log("Reward added successfully:", response);
            // Redirect after success
            window.location.href = "/admin/rewards-manager"; // <-- redirect page
          },
          error: function(xhr, status, error) {
          console.error("Error updating reward:", xhr.responseText);
          let message = "Failed to update reward. Please try again.";

          // If backend sends a message
          if (xhr.responseJSON && xhr.responseJSON.message) {
            message = xhr.responseJSON.message;
          }

          Swal.fire({
            icon: "error",
            title: "Error",
            text: message,
            confirmButtonColor: "#d33"
          });
          }
        });
      });
    });
  </script>
<script>
  document.addEventListener('DOMContentLoaded', function () {

    fetch('/admin/getcities')
      .then(res => res.json())
      .then(cities => {
        initDropdowns(cities);
      });

    function initDropdowns(cities, selectedId = null) {
      const cityDropdown = document.getElementById('city_id');
      cityDropdown.innerHTML = '<option value="">Select City</option>';

      // ✅ Populate dropdown
      cities.data.forEach(city => {
        const option = document.createElement('option');
        option.value = city.city_id;
        option.textContent = city.city_name;

        // Preselect if matches selectedId
        if (String(city.city_id) === String(selectedId)) {
          option.selected = true;
        }

        cityDropdown.appendChild(option);
      });

      // ✅ Auto-select and disable if only one city
if (cities.data.length === 1) {
  const singleCity = cities.data[0];
  cityDropdown.value = singleCity.city_id;

  // 🔥 Do NOT disable — instead lock it visually
  cityDropdown.setAttribute("readonly", true);
  cityDropdown.style.pointerEvents = "none";
  cityDropdown.style.opacity = "0.7";
  cityDropdown.style.background = "#f3f4f6";
} else {
  cityDropdown.removeAttribute("readonly");
  cityDropdown.style.pointerEvents = "auto";
  cityDropdown.style.opacity = "1";
}

    }
  });
</script>

  <%- footer %>