<%- header %>
<main class="dashboard-main">
  <%- navbar %>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/choices.js/public/assets/styles/choices.min.css">

<style>
  .error-text {
    color: red;
    font-size: 13px;
    margin-top: 4px;
    display: none;
  }
  .is-invalid {
    border-color: red !important;
  }
</style>

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

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

  <div class="bg-white shadow-md rounded-lg mt-4" style="padding: 20px;">
    <form id="promoForm">

      <div class="row">
        <!-- LEFT -->
        <div class="col-md-6">
          <h6><i class="bi bi-info-circle"></i> General Info</h6>
          <hr>

          <div class="mb-3" style="padding-top: 15px;">
            <label>Location</label>
            <select id="city_id" name="city_id" class="form-select">
              <option value="">Select City</option>
            </select>
            <div id="city_id_error" class="error-text">Location is required</div>
          </div>

          <div class="mb-3">
            <label>Promo Code</label>
            <input type="text" name="promo_code" class="form-control">
            <div id="promo_code_error" class="error-text">Promo code is required</div>
          </div>

          <div class="mb-3">
            <label>Promo Value (%)</label>
            <input type="number" name="promo_value" class="form-control">
            <div id="promo_value_error" class="error-text">Promo value is required</div>
          </div>

          <div class="row">
            <div class="col-md-6 mb-3">
              <label>Min Eligibility Amount</label>
              <input type="number" name="min_eligibility_amt" class="form-control">
              <div id="min_eligibility_amt_error" class="error-text">Required</div>
            </div>
            <div class="col-md-6 mb-3">
              <label>Max Discount Amount</label>
              <input type="number" name="max_discount" class="form-control">
              <div id="max_discount_error" class="error-text">Required</div>
            </div>
          </div>

          <!-- Native Date Inputs -->
          <div class="row">
            <div class="col-md-6 mb-3">
              <label>Start Date</label>
              <input type="date" id="start_date" class="form-control">
              <div id="start_date_error" class="error-text">Start date is required</div>
            </div>

            <div class="col-md-6 mb-3">
              <label>End Date</label>
              <input type="date" id="end_date" class="form-control">
              <div id="end_date_error" class="error-text">End date is required</div>
            </div>
          </div>

          <div class="row">
            <div class="col-md-6 mb-3">
              <label>Max Usage Limit</label>
              <input type="number" name="max_usage" class="form-control">
              <div id="max_usage_error" class="error-text">Required</div>
            </div>
            <div class="col-md-6 mb-3">
              <label>Max Usage Per User</label>
              <input type="number" name="max_usage_per_user" class="form-control">
              <div id="max_usage_per_user_error" class="error-text">Required</div>
            </div>
          </div>

          <!-- ✅ STATUS FIELDS (RESTORED) -->
          <div class="d-flex gap-4 mt-2">
            <div class="form-check">
              <input
                class="form-check-input"
                type="checkbox"
                id="is_new_user"
                name="is_new_user"
                value="1"
                style="margin-top: 2px; margin-right: 5px;"
              >
              <label class="form-check-label" for="is_new_user" > 
                Is New User Only
              </label>
            </div>

            <div class="form-check">
              <input
              style="margin-top: 2px; margin-right: 5px;"
                class="form-check-input"
                type="checkbox"
                id="promo_status"
                name="promo_status"
                value="1"
               >
              <label class="form-check-label" for="promo_status" >
                Active Status
              </label>
            </div>
          </div>
        </div>

        <!-- RIGHT -->
        <div class="col-md-6">
          <h6><i class="bi bi-people"></i> Promo Applicability</h6>
          <hr>

          <div class="mb-3" style="padding-top: 15px;">
            <label>For All Users</label >
            <select id="for_all_users" class="form-select">
              <option value="yes">Yes</option>
              <option value="no">No</option>
            </select>
          </div>

          <div class="mb-3" id="select_users_container" style="display:none;">
            <label>Select Users</label>
            <select id="users" class="form-select" multiple></select>
            <div id="users_error" class="error-text">Please select at least one user</div>
          </div>
        </div>
      </div>

      <div class="text-end">
        <button class="btn btn-primary mt-3">Submit</button>
      </div>
    </form>
  </div>
</div>
</main>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdn.jsdelivr.net/npm/choices.js/public/assets/scripts/choices.min.js"></script>

<script>
document.addEventListener("DOMContentLoaded", () => {

  const citySelect = document.getElementById("city_id");
  /* Load Cities */
  fetch("/admin/getcities")
    .then(r => r.json())
    .then(res => {
      if (!res?.data || !res.data.length) return;

      // Clear default option
      citySelect.innerHTML = `<option value="">Select City</option>`;

      res.data.forEach(c => {
        citySelect.insertAdjacentHTML(
          "beforeend",
          `<option value="${c.city_id}">${c.city_name}</option>`
        );
      });

      // ✅ If only ONE city → auto-select & disable
      if (res.data.length === 1) {
        citySelect.value = res.data[0].city_id;
        citySelect.setAttribute("disabled", "disabled");

        // 🔑 IMPORTANT: keep value submitted
        citySelect.insertAdjacentHTML(
          "afterend",
          `<input type="hidden" name="city_id" value="${res.data[0].city_id}">`
        );
      }
    });

  /* Init Users */
  const usersSelect = new Choices("#users", {
    removeItemButton: true,
    shouldSort: false
  });

  fetch("/admin/all/passengers/options?is_delete=0")
    .then(r => r.json())
    .then(res => {
      if (!res.data) return;
      usersSelect.setChoices(
        res.data.map(u => ({
          value: u.user_id,
          label: `${u.u_name} (ID: ${u.user_id})`
        })),
        "value",
        "label",
        true
      );
    });

  for_all_users.onchange = () => {
    select_users_container.style.display =
      for_all_users.value === "no" ? "block" : "none";
  };

  document.querySelectorAll("input, select").forEach(el => {
    el.addEventListener("input", clearError);
    el.addEventListener("change", clearError);
  });

  function clearError(e) {
    const el = e.target;
    el.classList.remove("is-invalid");
    const err =
      document.getElementById(el.name + "_error") ||
      document.getElementById(el.id + "_error");
    if (err) err.style.display = "none";
  }

  function req(name) {
    const el = document.querySelector(`[name="${name}"]`) || document.getElementById(name);
    if (!el.value) {
      el.classList.add("is-invalid");
      document.getElementById(name + "_error").style.display = "block";
      return false;
    }
    return true;
  }

  promoForm.onsubmit = e => {
    e.preventDefault();

    let ok =
      req("city_id") &
      req("promo_code") &
      req("promo_value") &
      req("min_eligibility_amt") &
      req("max_discount") &
      req("max_usage") &
      req("max_usage_per_user") &
      req("start_date") &
      req("end_date");

    if (for_all_users.value === "no" && !usersSelect.getValue(true).length) {
      users_error.style.display = "block";
      ok = false;
    }

    if (!ok) return;

    console.log(promo_status.checked)

    const data = {
      city_id: city_id.value,
      promo_code: promoForm.promo_code.value,
      promo_value: promoForm.promo_value.value,
      min_eligibility_amt: promoForm.min_eligibility_amt.value,
      max_discount: promoForm.max_discount.value,
      promo_start_date: start_date.value,
      promo_end_date: end_date.value,
      max_usage: promoForm.max_usage.value,
      max_usage_per_user: promoForm.max_usage_per_user.value,
      is_new_user: is_new_user.checked ? 1 : 0,
      status: promo_status.checked ? 1 : 0,
      for_all_users: for_all_users.value,
      users: JSON.stringify(usersSelect.getValue(true))
    };

    fetch("/admin/add-promo-api", {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: new URLSearchParams(data)
    })
    .then(async res => {
      const json = await res.json();
      if (!res.ok) throw json;

      return Swal.fire({
        icon: "success",
        title: "Success",
        text: "Promo added successfully",
        confirmButtonText: "OK"
      });
    })
    .then(() => window.location.href = "/admin/promo-manager")
    .catch(err => {
      Swal.fire("Error", err?.message || err?.error || "Something went wrong", "error");
    });
  };
});
</script>

<%- footer %>
