$(document).ready(function() {
  // Detect pagination click
  $("#pagination").on("click", "a", function(e) {
    e.preventDefault();

    const pageno = $(this).attr("data-ci-pagination-page");
    const url = $(this).attr("href");
    const filters = {
      country_code: getURLParameter(url, "country_code"),
      city_id: getURLParameter(url, "city_id"),
      geo_area_id: getURLParameter(url, "geo_area_id")
    };

    loadPagination(pageno, filters);
  });

  // Init Page
  loadPagination(0, {
    country_code: $("#country_card").val(),
    city_id: $("#city_filter").val(),
    geo_area_id: $("#geo_area_filter").val()
  });

  function loadPagination(pagno, filters = []) {
    $.ajax({
      url: "/Geofence_area_anchor/loadRecord",
      type: "get",
      dataType: "json",
      data: {
        rowno: pagno,
        filters: filters
      },
      success: function(response) {
        $("#pagination").html(response.pagination);
        createTable(response.result);
      },
      complete: function() {}
    });
  }

  function createTable(result) {
    const list = $("#geofence-area-anchor-list tbody");
    list.empty();

    for (index in result) {
      const id = result[index].id;
      const geofence_area = result[index].name;
      const address = result[index].address;
      const title = result[index].title;
      const address_id = result[index].address_id;
      const geofence_area_id = result[index].geofence_area_id;
      const city_id = result[index].city_id;

      let tr = `<tr>
          <td hidden>${geofence_area_id}</td>
          <td hidden>${address_id}</td>
          <td>${id}</td>
          <td>${geofence_area}</td>
          <td>${address}</td>
          <td>${title}</td>
          <td hidden>${city_id}</td>
          <td class="input-group-btn">
            <button type='button' class='btn btn-info btn-sm btn-update'>Update</button>
            <button type='button' class='btn btn-secondary btn-sm btn-cancel hidden'>Cancel</button>
            <button type='button' class='btn btn-danger btn-sm btn-delete'>Delete</button>
          </td>
        </tr>`;

      list.append(tr);
    }
  }

  // Detect on click the update button on form
  $("#btn-update").click(function() {
    $("#geofence-area-anchor-form").submit();
  });

  // Detect on click the add button on form
  $("#btn-add").click(function() {
    $("#geofence-area-anchor-form").attr(
      "action",
      origin + "/Geofence_area_anchor/create"
    );
  });

  let address = $("#address").select2({
    placeholder: "Search By Address",
    maximumSelectionSize: 1,
    minimumInputLength: 3,
    ajax: {
      url: "/geofence_area_anchor/getLocationByAddress",
      type: "GET",
      dataType: "json",
      delay: 250,
      data: function(params) {
        const query = {
          address: params.term,
          page: params.page || 1
        };
        return query;
      },
      processResults: function(res, params) {
        const { data, total } = res;
        params.page = params.page || 1;
        return {
          results: data.map(item => ({
            id: item.id,
            text: item.address
          })),
          pagination: {
            more: params.page * 20 < +total
          }
        };
      }
    }
  });

  $("#geofence-area-anchor-form").on("submit", function(e) {
    if (address && address.val()) {
      const selectedId = address.select2("data")[0].id;
      const selectedText = address.select2("data")[0].text;
      $(this).append(
        `<input type="hidden" id="address_id" name="address_id" value="${selectedId.trim()}" />`
      );
      $(this).append(
        `<input type="hidden" id="address" name="address" value="${selectedText.trim()}" />`
      );
    }

    return true;
  });

  function loadGeoAreaByCity(city_id, callback, data) {
    $.ajax({
      url: `/Geofence_area_anchor/loadGeoAreaByCity/${city_id}`,
      type: "get",
      dataType: "json",
      success: function(response) {
        callback(response, data);
      }
    });
  }

  function render_geo_area_filter(response, data = null) {
    let select = $("#geofence_area_filter_card");
    select.empty();
    select.append('<option value="">Select</option>');

    const geo_area_selected = $("#geo_area_filter").val();

    $.each(response, function(key, value) {
      select.append(
        `<option value="${value.id}"
        ${geo_area_selected === value.id ? "selected" : ""}
        >${value.geo_area_name}</option>`
      );
    });
  }

  function render_geo_area(response, data = null) {

    let select = $("#geofence_area_card");
    select.empty();
    select.append('<option value="">Select</option>');

    $.each(response, function(key, value) {
      select.append(
        `<option value="${value.id}"
        ${ data ? ( data.geo_area_id === value.id ? "selected" : "") : "" }
        >${value.geo_area_name}</option>`
      );
    });
  }

  function loadCityByCountry(country_id) {
    $.ajax({
      url: `/Geofence_area_anchor/loadCityByCountry/${country_id}`,
      type: "get",
      dataType: "json",
      success: function(response) {
        let select = $("#city_card");
        select.empty();
        select.append('<option value="">Select</option>');

        $.each(response.contries, function(key, value) {
          select.append(
            `<option value="${value.id}"
            >${value.city}</option>`
          );
        });
      }
    });
  }

  $("#country_card").on("change", function(event) {
    event.preventDefault();

    const country_code = $(this)
      .children("option:selected")
      .val();
    const city_id = '';

    // keep value to reshow after validate failed
    $("#country_filter").val(country_code);

    // load city filter
    loadCityByCountry(country_code);
    // load geo area filter
    loadGeoAreaByCity(city_id, render_geo_area_filter);
    // load list
    loadPagination(0, {
      country_code: country_code,
      city_id: city_id,
      geo_area_id: '',
    });
  });

  $("#city_card").on("change", function() {
    const city_id = $(this)
      .children("option:selected")
      .val();
    const country_code = $("#country_card")
      .children("option:selected")
      .val();

    // keep value to reshow after validate failed
    $("#city_filter").val(city_id);

    // load geo area filter
    loadGeoAreaByCity(city_id, render_geo_area_filter);
    // load list
    loadPagination(0, {
      country_code: country_code,
      city_id: city_id,
      geo_area_id: ''
    });
  });

  $("#geofence_area_filter_card").on("change", function() {
    const geo_area_id = $(this)
      .children("option:selected")
      .val();
    const city_id = $("#city_card")
      .children("option:selected")
      .val();
    const country_code = $("#country_card")
      .children("option:selected")
      .val();

    // keep value to reshow after validate failed
    $("#geo_area_filter").val(geo_area_id);
    // load list
    loadPagination(0, {
      geo_area_id: country_code,
      city_id: city_id,
      geo_area_id: geo_area_id
    });
  });

  $("#geofence_area_city_card").on("change", function(event, data) {
    event.preventDefault();

    let city_id = $(this)
      .children("option:selected")
      .val();

    loadGeoAreaByCity(city_id, render_geo_area, data);
  });
});

// Detect on click the update button
$(document).on("click", ".btn-update", function(e) {
  const row = $(this).closest("tr"); // Finds the closest row <tr>
  const tds = row.find("td"); // Finds all children <td> elements

  $(".btn-cancel").addClass("hidden");
  $(".btn-update").removeClass("hidden");
  $("#btn-add").addClass("hidden");
  $("#btn-update").removeClass("hidden");

  $(this)
    .siblings(".btn-cancel")
    .removeClass("hidden");
  $(this).addClass("hidden");

  $('[name="geofence_area_city_card"]')
    .val(tds[6].innerText)
    .trigger("change", { geo_area_id: tds[0].innerText });

  $('[name="address"]').append(
    `<option value="${tds[1].innerText}" selected>${tds[4].innerText}</option>`
  );

  $('[name="title"]').val(tds[5].innerText);
  $('[name="old_geofence_area_id"]').val(tds[0].innerText);
  $('[name="old_address_id"]').val(tds[1].innerText);

  $("#geofence-area-anchor-form").attr(
    "action",
    origin + "/Geofence_area_anchor/update/" + tds[2].innerText
  );
});

// Detect on click the cancel button
$(document).on("click", ".btn-cancel", function(e) {
  $("#geofence-area-anchor-form")[0].reset();
  $('[name="address"]')
    .empty()
    .trigger("change");
  $('[name="geofence_area_card"] option').prop("selected", false);

  $(this)
    .siblings(".btn-update")
    .removeClass("hidden");
  $(this).addClass("hidden");
  $("#btn-add").removeClass("hidden");
  $("#btn-update").addClass("hidden");

  $("#geofence-area-anchor-form").attr(
    "action",
    origin + "/Geofence_area_anchor/create"
  );
});

// Detect on click the delete button
$(document).on("click", ".btn-delete", function(e) {
  if (!confirm("Are you sure want to delete?")) {
    return;
  }

  const row = $(this).closest("tr"); // Finds the closest row <tr>
  const tds = row.find("td"); // Finds all children <td> elements

  $("#geofence-area-anchor-form").attr(
    "action",
    origin + "/Geofence_area_anchor/destroy/" + tds[2].innerText
  );
  $("#geofence-area-anchor-form").submit();
});
