/**
 * MUTASI JS (FIX datepicker + default minggu ini)
 * - Kirim tanggal ke server selalu: YYYY-MM-DD
 * - Pertama kali load: tampilkan timeline minggu ini (Senin s/d hari ini)
 * - Klik Today: pasti tampil data hari ini
 */

(function () {
  // simpan range aktif agar setelah simpan mutasi, reload tetap pakai range yang sama
  var MUTASI_RANGE = {
    start: "",
    end: ""
  };

  function _toYMD(m) {
    return m && m.format ? m.format("YYYY-MM-DD") : "";
  }

  function _toDMY(m) {
    return m && m.format ? m.format("DD/MM/YYYY") : "";
  }

  // fallback kalau ajaxQueue tidak tersedia
  function _ajaxPost(opts) {
    if (typeof $.ajaxQueue === "function") return $.ajaxQueue(opts);
    return $.ajax(opts);
  }

  // =========================
  // AJAX LOAD TIMELINE
  // =========================
  window.search_Mutasi = function (page, dari, sampai) {
    page = page || 0;

    // kalau kosong, default minggu ini
    if (!dari || !sampai) {
      var s = moment().startOf("isoWeek"); // Senin
      var e = moment();                    // hari ini
      dari = _toYMD(s);
      sampai = _toYMD(e);
    }

    MUTASI_RANGE.start = dari;
    MUTASI_RANGE.end = sampai;

    _ajaxPost({
      type: "POST",
      url: base_url + "kas/cariMutasi/" + page,
      data: { page: page, dari: dari, sampai: sampai },
      dataType: "html",
      beforeSend: function () { $("body").loading(); },
      success: function (html) {
        if (html === "NONE") {
          $("#dataMutasi").hide();
        } else {
          $("#dataMutasi").show().html(html);
        }
        $("body").loading("stop");
      },
      error: function (xhr) {
        var t = xhr.responseText;
        sweet("Server!!!", t, "error", "danger");
        $("body").loading("stop");
      }
    });
  };

  // =========================
  // LOAD TUJUAN & REKENING
  // =========================
  window.load_tujuan = function (id) {
    $.ajax({
      url: base_url + "kas/tujuan_kas",
      type: "POST",
      data: { id: id },
      dataType: "json",
      beforeSend: function () {
        $("#tujuan").append("<option value='loading'>loading</option>");
        $("#tujuan").empty();
      },
      success: function (res) {
        $("#tujuan option[value='loading']").remove();
        $("#tujuan").append("<option value=''>Pilih</option>");
        for (var i = 0; i < res.length; i++) {
          $("#tujuan").append("<option value='" + res[i].id + "'>" + res[i].name + "</option>");
        }
      }
    });
  };

  window.load_rekening = function (id) {
    $.ajax({
      url: base_url + "kas/rekening",
      type: "POST",
      data: { id: id },
      dataType: "json",
      beforeSend: function () {
        $("#rekening_dari").append("<option value='loading'>loading</option>");
        $("#rekening_dari").empty();
      },
      success: function (res) {
        $("#rekening_dari option[value='loading']").remove();
        $("#rekening_dari").append("<option value=''>Pilih</option>");
        for (var i = 0; i < res.length; i++) {
          $("#rekening_dari").append("<option value='" + res[i].id + "'>" + res[i].name + "</option>");
        }
      }
    });
  };

  // =========================
  // INIT DATE RANGE PICKER
  // =========================
  function initDateRange() {
    if (!$("#reportrange").length || typeof $("#reportrange").daterangepicker !== "function") {
      // kalau daterangepicker belum ada, tetap load default minggu ini
      var s0 = moment().startOf("isoWeek");
      var e0 = moment();
      MUTASI_RANGE.start = _toYMD(s0);
      MUTASI_RANGE.end = _toYMD(e0);
      search_Mutasi(0, MUTASI_RANGE.start, MUTASI_RANGE.end);
      return;
    }

    var start = moment().startOf("isoWeek"); // Senin minggu ini
    var end = moment();                      // hari ini

    function applyRange(s, e) {
      // set label tampilan
      $("#reportrange span").html(_toDMY(s) + " - " + _toDMY(e));

      // set hidden input kalau memang ada (kompatibilitas)
      if ($("#startdate").length) $("#startdate").val(_toYMD(s));
      if ($("#enddate").length) $("#enddate").val(_toYMD(e));

      // load timeline (kirim YYYY-MM-DD)
      search_Mutasi(0, _toYMD(s), _toYMD(e));
    }

    $("#reportrange").daterangepicker(
      {
        startDate: start,
        endDate: end,
        opens: "left",
        autoUpdateInput: false,
        ranges: {
          "Today": [moment(), moment()],
          "This Week": [moment().startOf("Years"), moment()],
          "Last 7 Days": [moment().subtract(6, "days"), moment()],
          "This Month": [moment().startOf("month"), moment().endOf("month")],
          "Last Month": [
            moment().subtract(1, "month").startOf("month"),
            moment().subtract(1, "month").endOf("month")
          ],
          "This Years": [moment().startOf("Years"), moment().endOf("Years")]
        },
        locale: {
          format: "DD/MM/YYYY",
          applyLabel: "Terapkan",
          cancelLabel: "Batal",
          fromLabel: "Dari",
          toLabel: "Sampai",
          customRangeLabel: "Custom",
          weekLabel: "M",
          daysOfWeek: ["Min", "Sen", "Sel", "Rab", "Kam", "Jum", "Sab"],
          monthNames: [
            "Januari","Februari","Maret","April","Mei","Juni",
            "Juli","Agustus","September","Oktober","November","Desember"
          ],
          firstDay: 1
        }
      },
      function (s, e) {
        applyRange(s, e);
      }
    );

    // pertama kali load (minggu ini)
    applyRange(start, end);

    // jaga-jaga: kalau user klik apply, tetap pakai picker object (bukan input hidden)
    $("#reportrange").on("apply.daterangepicker", function (ev, picker) {
      applyRange(picker.startDate, picker.endDate);
    });
  }

  // =========================
  // EVENT EXISTING (mutasi form)
  // =========================
  $(document).ready(function () {
    initDateRange();

    // select text input on click
    $(".input").click(function () { this.select(); });

    // open modal
    $(document).on("click", ".add_mutasi", function (e) {
      e.preventDefault();
      var id = $(this).attr("data-id");
      $("#ModalMutasi").modal({ backdrop: "static", keyboard: false });
      $("#tujuan").attr("disabled", true);
      $("#saldo").val(formatMoney(0, 0, "Rp."));
      if (id != 0) $("#type").val("edit");
      else $("#type").val("add");
    });

    // cek saldo
    $(document).on("click", ".cek_saldo", function (e) {
      e.preventDefault();
      var idkas = $("#dari_kas").val();
      var rekening = $("#rekening_dari").val();
      $.ajax({
        url: base_url + "kas/cek_saldo",
        type: "POST",
        data: { rekening: rekening, idkas: idkas },
        dataType: "json",
        beforeSend: function () { $("body").loading(); },
        success: function (r) {
          if (r.status == 200 && r.saldo != null) $("#saldo").val(formatMoney(r.saldo, 0, "Rp."));
          else $("#saldo").val(formatMoney(0, 0, "Rp."));
          $("body").loading("stop");
        }
      });
    });

    // load jenis kas mutasi
    $("#dari_kas").filter(function () {
      $.ajax({
        url: base_url + "kas/jenis_kas_mutasi",
        type: "POST",
        dataType: "json",
        beforeSend: function () {
          $("#dari_kas").append("<option value='loading'>loading</option>");
          $("#dari_kas").empty();
          $("#dari_kas").attr("disabled", false);
          $("#tujuan").attr("disabled", true);
        },
        success: function (res) {
          $("#dari_kas option[value='loading']").remove();
          $("#dari_kas").append("<option value=''>Pilih</option>");
          for (var i = 0; i < res.length; i++) {
            $("#dari_kas").append("<option value='" + res[i].id + "'>" + res[i].name + "</option>");
          }
        }
      });
    });

    // dari_kas change
    $("#dari_kas").change(function () {
      var v = $("#dari_kas").val();
      $(".rekening").css("display", "none");

      if (v == 0 || v === "") {
        $("#tujuan").empty().append("<option value=''>Pilih</option>");
        $("#tujuan").attr("disabled", true);
        return;
      }

      if (parseInt(v, 10) === 110) {
        $("#tujuan").attr("disabled", true);
        $(".rekening_dari").css("display", "block");
        load_rekening(v);
      } else {
        $(".rekening_dari").css("display", "none");
        $("#tujuan").attr("disabled", false);
        load_tujuan(v);
      }
    });

    // tujuan change
    $("#tujuan").change(function () {
      var tujuan = $("#tujuan").val();
      var rekening_dari = $("#rekening_dari").val();

      if (parseInt(tujuan, 10) === 110) $(".rekening").css("display", "block");
      else $(".rekening").css("display", "none");

      $.ajax({
        url: base_url + "kas/rekening",
        type: "POST",
        data: { id: tujuan, dari: rekening_dari },
        dataType: "json",
        beforeSend: function () {
          $("#rekening").append("<option value='loading'>loading</option>");
          $("#rekening").empty();
        },
        success: function (res) {
          $("#rekening option[value='loading']").remove();
          $("#rekening").append("<option value=''>Pilih</option>");
          for (var i = 0; i < res.length; i++) {
            $("#rekening").append("<option value='" + res[i].id + "'>" + res[i].name + "</option>");
          }
        }
      });
    });

    // save btn
    $(document).on("click", ".save_mutasi", function () {
      $("#myForm").submit();
    });

    // submit form
    $("#myForm").submit(function (e) {
      e.preventDefault();

      var tujuan = $("#tujuan").val();
      var jml = angka($("#jumlah").val());
      var saldo = angka($("#saldo").val());

      if (tujuan === "") {
        $("#tujuan").addClass("is-invalid").focus();
        return;
      }

      if (parseInt(saldo, 10) === 0) {
        sweet_time(2000, "Status!!!", "saldo tidak mencukupi");
        return;
      }

      if (jml === "" || jml <= 0) {
        $("#jumlah").addClass("is-invalid").focus();
        return;
      }

      $.ajax({
        url: base_url + "kas/simpan_mutasi",
        type: "POST",
        // [EDIT] kirim form + file (bukti mutasi) menggunakan FormData
        data: new FormData(this),
        dataType: "json",
        processData: false, // [ADD] wajib untuk FormData
        contentType: false, // [ADD] wajib untuk FormData
        beforeSend: function () { $("body").loading(); },
        success: function (r) {
          sweet_time(2000, "Status!!!", r.msg);

          // reload timeline pakai range yang sedang aktif
          search_Mutasi(0, MUTASI_RANGE.start, MUTASI_RANGE.end);

          $("#ModalMutasi").modal("hide");
          $("body").loading("stop");
        }
      });
    });

    // rekening_dari change (bank source)
    $("#rekening_dari").change(function () {
      var id = $("#rekening_dari").val();
      $("#tujuan").attr("disabled", false);
      load_tujuan(id); // tetap ikuti flow lama kamu
    });

    // validasi jumlah > saldo
    var jumlah = document.getElementById("jumlah");
    if (jumlah) {
      jumlah.addEventListener("keyup", function () {
        jumlah.value = formatRupiah(this.value, "Rp. ");
        var jml_bayar = angka(this.value);
        var saldo = angka($("#saldo").val());
        if (parseInt(jml_bayar, 10) > parseInt(saldo, 10)) {
          sweet_time(2000, "Status!!!", "saldo tidak mencukupi");
          $("#jumlah").val(formatMoney(0, 0, "Rp."));
        }
      });
    }
  });
})();
