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

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

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

        <input type="hidden" name="promo_id" value="<%= promo.promo_id %>">

        <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 pt-3">
              <label>Location</label>
              <select id="city_id" name="city_id" class="form-select"></select>
            </div>

            <div class="mb-3">
              <label>Promo Code</label>
              <input type="text" name="promo_code" class="form-control"
                     value="<%= promo.promo_code %>">
            </div>

            <div class="mb-3">
              <label>Promo Value (%)</label>
              <input type="number" name="promo_value" class="form-control"
                     value="<%= promo.promo_value %>">
            </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"
                       value="<%= promo.min_eligibility_amt %>">
              </div>
              <div class="col-md-6 mb-3">
                <label>Max Discount Amount</label>
                <input type="number" name="max_discount" class="form-control"
                       value="<%= promo.max_discount %>">
              </div>
            </div>

            <div class="row">
              <div class="col-md-6 mb-3">
                <label>Start Date</label>
                <input type="date" id="start_date" name="promo_start_date"
                       class="form-control"
                       value="<%= promo.promo_start_date ? String(promo.promo_start_date).slice(0,10) : '' %>">
              </div>

              <div class="col-md-6 mb-3">
                <label>End Date</label>
                <input type="date" id="end_date" name="promo_end_date"
                       class="form-control"
                       value="<%= promo.promo_end_date ? String(promo.promo_end_date).slice(0,10) : '' %>">
              </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"
                       value="<%= promo.promo_max_limit %>">
              </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"
                       value="<%= promo.user_usage_limit %>">
              </div>
            </div>

            <div class="d-flex gap-4">
              <div class="form-check">
                <input class="form-check-input" type="checkbox"
                       name="is_new_user" value="1"
                                       style="margin-top: 2px; margin-right: 5px;"

                       <%= promo.is_new_user ? "checked" : "" %>>
                <label class="form-check-label">Is New User Only</label>
              </div>

              <div class="form-check">
                <input class="form-check-input" type="checkbox"
                       name="status" value="1"
                                       style="margin-top: 2px; margin-right: 5px;"

                       <%= promo.promo_status ? "checked" : "" %>>
                <label class="form-check-label">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 pt-3">
              <label>For All Users</label>
              <select id="for_all_users" name="for_all_users" class="form-select">
                <option value="yes" <%= promo.is_exclusive == 0 ? "selected" : "" %>>Yes</option>
                <option value="no" <%= promo.is_exclusive == 1 ? "selected" : "" %>>No</option>
              </select>
            </div>

            <div class="mb-3"
                 id="select_users_container"
                 style="display:<%= promo.is_exclusive == 1 ? 'block' : 'none' %>">
              <label>Select Users</label>
              <select id="users" name="users" class="form-select" multiple></select>
            </div>
          </div>
        </div>

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

<!-- SCRIPTS -->
<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", () => {

  /* ================= INIT ================= */
  const citySelect = new Choices("#city_id", { searchEnabled:true, shouldSort:false });
  const usersSelect = new Choices("#users", { removeItemButton:true, shouldSort:false });

  /* ================= LOAD CITIES ================= */
  fetch("/admin/getcities")
    .then(r => r.json())
    .then(res => {
      if (!res.data?.length) return;

      const cities = res.data.map(c => ({
        value: String(c.city_id),
        label: c.city_name
      }));

      citySelect.setChoices(cities, "value", "label", true);

      if (cities.length === 1) {
        citySelect.setChoiceByValue(cities[0].value);
        citySelect.disable();
        return;
      }

      const promoCityId = "<%= promo.city_id || '' %>";
      if (promoCityId) citySelect.setChoiceByValue(String(promoCityId));
    });

  /* ================= LOAD USERS ================= */
  const selectedUserIds = <%- JSON.stringify(selectedUserIds || []) %>;

  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: String(u.user_id),
          label: `${u.u_name} (ID: ${u.user_id})`,
          selected: selectedUserIds.includes(u.user_id)
        })),
        "value", "label", true
      );
    });

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

  /* ================= UPDATE PROMO (RESTORED) ================= */
  promoForm.onsubmit = e => {
    e.preventDefault();

    const start = new Date(start_date.value);
    const end = new Date(end_date.value);

    if (end < start) {
      Swal.fire("Invalid Dates", "End date must be after start date", "error");
      return;
    }

    const data = new URLSearchParams(new FormData(promoForm));

    fetch("/admin/update-promo", {
      method: "POST",
      body: data
    })
    .then(async res => {
      const json = await res.json();
      if (!res.ok) throw json;
      return Swal.fire("Updated", "Promo updated successfully", "success");
    })
    .then(() => window.location.href = "/admin/promo-manager")
    .catch(err => {
      Swal.fire("Error", err?.message || "Something went wrong", "error");
    });
  };

});
</script>

<%- footer %>
