   <%- 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: "Edit Reward Manager"}) %>


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


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




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

        <input type="hidden" id="rewardId" value="<%= reward.reward_id %>">

        <div class="row">
          <!-- City -->
          <div class="col-md-12 mb-6">
   <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-6">
            <label class="form-label">Reward Mode</label>
            <select id="rewardmode" name="rewardmode" class="form-select">
              <option value="">Select Reward Mode</option>
              <option value="user" <%= reward.type == "user" ? "selected" : "" %>>User</option>
              <option value="driver" <%= reward.type == "driver" ? "selected" : "" %>>Driver</option>
            </select>
          </div>

          <!-- Reward Value -->
          <div class="col-md-12 mb-6">
            <label class="form-label">Reward Value</label>
            <input type="number" id="amount" name="amount" class="form-control" value="<%= reward.r_value %>">
          </div>

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

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

  </div>
</main>
<script>
  // Define form configuration
  const formConfig = {
    formId: "editRewardForm",
    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() {
    $("#editRewardForm").on("submit", function(e) {
      e.preventDefault();

      // Validate form fields
      if (!formValidator.validateForm()) {
        Swal.fire({
          icon: "warning",
          title: "Validation Error",
          text: "Please fill in all required fields correctly.",
          confirmButtonColor: "#3085d6"
        });
        return;
      }

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

      $.ajax({
        url: "/admin/editReward",
        type: "POST",
        data: data,
        success: function(response) {
          Swal.fire({
            icon: "success",
            title: "Reward Updated!",
            text: "The reward was successfully updated.",
            showConfirmButton: false,
            timer: 1800
          }).then(() => {
            window.location.href = "/admin/rewards-manager";
          });
        },
        error: function(xhr) {
          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 () {

    const selectedCityId = "<%= reward.city_id %>";  // <-- ADD THIS

    fetch('/admin/getcities')
      .then(res => res.json())
      .then(cities => {
        initDropdowns(cities, selectedCityId);  // <-- FIXED
      });

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

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

        if (String(city.city_id) === String(selectedId)) {
          option.selected = true;  // <-- AUTO SELECT WORKS NOW
        }

        cityDropdown.appendChild(option);
      });

      // Lock when single city exists
      if (cities.data.length === 1) {
        const singleCity = cities.data[0];
        cityDropdown.value = singleCity.city_id;
        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 %>