text: import { useState } from "react";
  import axios from "axios";
  import { useSelector } from "react-redux";
  
  const ArusKasHelper = () => {
    const currentUser = useSelector((state) => state.currentUser);
    const baseUrl = process.env.REACT_APP_LARAVEL_URL;
    const fields = [
      {
        key: "no_pembayaran",
        label: "No",
        _style: { textAlign: "center", width: "10%" },
      },
      {
        key: "cabang",
        label: "Cabang",
        _style: { textAlign: "center" },
      },
      {
        key: "transaksi",
        label: "Sandi Transaksi",
        _style: { textAlign: "center" },
      },
      {
        key: "nominal",
        label: "Nominal",
        _style: { textAlign: "center" },
      },
      {
        key: "shift",
        label: "Shift",
        _style: { textAlign: "center" },
      },
      {
        key: "show_details",
        label: "",
        _style: { width: "1%" },
        sorter: false,
        filter: false,
      },
    ];
  
    const kodeCabang = (item) => {
      switch (item) {
        case "Banjarbaru":
          return "S.BJB.";
        case "Landasan Ulin":
          return "S.LNU.";
        case "Banjarmasin":
          return "S.BJM.";
        default:
          return "";
      }
    };
  
    const [success, setSuccess] = useState(false);
    const [info, setInfo] = useState(false);
    const [warning, setWarning] = useState(false);
    const [color, setColor] = useState("success");
    const [modalTitle, setModalTitle] = useState("Tambah Data");
    const [buttonSubmitName, setButtonSubmitName] = useState("Submit");
    const [dataCabang, setDataCabang] = useState([]);
    const [loadDataCabang, setLoadDataCabang] = useState(true);
    const [dataCabangCetakList, setDataCabangCetakList] = useState([]);
    const [arusKas, setArusKas] = useState([]);
    const [arusKasCadangan, setArusKasCadangan] = useState([]);
    const [arusKasGroupBySandiTransaksi, setArusKasGroupBySandiTransaksi] =
      useState([]);
    const [
      arusKasGroupBySandiTransaksiCadangan,
      setArusKasGroupBySandiTransaksiCadangan,
    ] = useState([]);
    const [isLoading, setIsLoading] = useState(true);
    const [currentArusKas, setCurrentArusKas] = useState({});
    const [loadCurrentArusKas, setLoadCurrentArusKas] = useState(true);
    const [details, setDetails] = useState([]);
    const [dataRekening, setDataRekening] = useState({});
    const [loadDataRekening, setLoadDataRekening] = useState(true);
    const [sandiTransaksiOptions, setSandiTransaksiOptions] = useState([]);
    const [currentSandiTransaksi, setCurrentSandiTransaksi] = useState({
      sandi_transaksi: "",
    });
    const [adminOptions, setAdminOptions] = useState([]);
    const [currentAdmin, setCurrentAdmin] = useState({
      name: "",
    });
    const [input, setInput] = useState({
      kas: "",
      norekening: "",
      nominal: "",
      id_sandi: "",
      id_admin: "",
      keterangan: "",
    });
    const [filter, setFilter] = useState({
      shift: "",
      sandi_transaksi: "",
      jenis_transaksi: "",
      cabang: "",
      dari: "",
      sampai: "",
      cari: "",
    });
    const [laporan, setLaporan] = useState({
      list_sandi: [],
      pemasukan_tunai: 0,
      pengeluaran_tunai: 0,
      pemasukan_non_tunai: 0,
      pengeluaran_non_tunai: 0,
    });
  
    const arrangeArusKas = (data) => {
      // buat grup untuk sandi transaksi
      const sandi_transaksi = [
        ...new Map(
          data.map((item) => [item["id_sandi"], item.transaksi.sandi_transaksi])
        ).values(),
      ];
  
      // hitung pemasukan dan pengeluaran
      let pemasukan_tunai = 0;
      let pemasukan_non_tunai = 0;
      let pengeluaran_tunai = 0;
      let pengeluaran_non_tunai = 0;
  
      data.map((item) => {
        if (item.rekening) {
          if (item.transaksi.jenis_transaksi) {
            pemasukan_non_tunai += item.nominal;
          } else {
            pengeluaran_non_tunai += item.nominal;
          }
        } else {
          if (item.transaksi.jenis_transaksi) {
            pemasukan_tunai += item.nominal;
          } else {
            pengeluaran_tunai += item.nominal;
          }
        }
      });
  
      setLaporan({
        pemasukan_tunai: pemasukan_tunai,
        pemasukan_non_tunai: pemasukan_non_tunai,
        pengeluaran_tunai: pengeluaran_tunai,
        pengeluaran_non_tunai: pengeluaran_non_tunai,
        list_sandi: sandi_transaksi,
      });
    };
  
    const toggleDetails = (index) => {
      const position = details.indexOf(index);
      let newDetails = details.slice();
      if (position !== -1) {
        newDetails.splice(position, 1);
      } else {
        newDetails = [...details, index];
      }
      setDetails(newDetails);
    };
  
    const closeModalHandler = (action) => {
      if (action === "Submit" || action === "Update") {
        setSuccess(false);
      } else if (action === "view") {
        setInfo(false);
      }
  
      setModalTitle("Tambah Data");
      setButtonSubmitName("Submit");
      setInput({
        kas: "",
        norekening: "",
        nominal: "",
        id_sandi: "",
        keterangan: "",
      });
  
      setCurrentSandiTransaksi({
        sandi_transaksi: "",
      });
  
      setCurrentAdmin({
        name: "",
      });
    };
  
    const getDataArusKas = async () => {
      await axios
        .get(`${baseUrl}/detail-pembayaran`, {
          headers: {
            Accept: "Application/json",
            Authorization: `Bearer ${localStorage.getItem("sis-token")}`,
          },
        })
        .then((response) => {
          const result = response.data.data;
          setArusKas(result);
          setArusKasCadangan(result);
        })
        .catch((error) => {
          console.log(error);
        });
  
      setIsLoading(false);
    };
  
    const getArusKasGroupBySandiTransaksi = async () => {
      await axios
        .get(`${baseUrl}/detail-pembayaran/group-by/sandi-transaksi`, {
          headers: {
            Accept: "Application/json",
            Authorization: `Bearer ${localStorage.getItem("sis-token")}`,
          },
        })
        .then((response) => {
          const result = response.data.data;
          setArusKasGroupBySandiTransaksi(result);
          setArusKasGroupBySandiTransaksiCadangan(result);
        })
        .catch((error) => {
          console.log(error);
        });
  
      setIsLoading(false);
    };
  
    const getDataArusKasById = (values, actionModal) => {
      setCurrentArusKas(values);
  
      if (actionModal === "update") {
        const keterangan = values.keterangan
          .split(values.transaksi.sandi_transaksi)[1]
          .trim();
  
        setInput({
          kas: values.kas,
          norekening: values.norekening,
          nominal: values.nominal,
          id_sandi: values.id_sandi,
          keterangan: keterangan,
        });
  
        setCurrentSandiTransaksi({
          sandi_transaksi: values.transaksi.sandi_transaksi,
        });
  
        setCurrentAdmin({
          name: values.admin.name,
        });
      }
  
      setLoadCurrentArusKas(false);
  
      if (actionModal === "view") {
        setInfo(true);
      } else if (actionModal === "update") {
        setModalTitle("Updata Data");
        setButtonSubmitName("Update");
        setSuccess(true);
      }
    };
  
    const getDataRekening = async () => {
      await axios
        .get(`${baseUrl}/rekening`, {
          headers: {
            Accept: "Application/json",
            Authorization: `Bearer ${localStorage.getItem("sis-token")}`,
          },
        })
        .then((response) => {
          setDataRekening(response.data.data);
        })
        .catch((error) => {
          console.log(error);
        });
  
      setLoadDataRekening(false);
    };
  
    const getDataSandiTransaksi = async () => {
      await axios
        .get(`${baseUrl}/sandi-transaksi`, {
          headers: {
            Accept: "Application/json",
            Authorization: `Bearer ${localStorage.getItem("sis-token")}`,
          },
        })
        .then((response) => {
          let data = [];
          response.data.data.map((item) => data.push(item));
          setSandiTransaksiOptions(data);
        })
        .catch((error) => {
          console.log(error);
        });
    };
  
    const getDataCabang = async () => {
      await axios
        .get(`${baseUrl}/cabang`, {
          headers: {
            Accept: "Application/json",
            Authorization: `Bearer ${localStorage.getItem("sis-token")}`,
          },
        })
        .then((response) => {
          const result = response.data.data;
          setDataCabang(result);
  
          const data = result.filter((item) => {
            return item.nama_cabang.toLowerCase().match("twincom");
          });
          setDataCabangCetakList(data);
        })
        .catch((error) => {
          console.log(error);
        });
  
      setLoadDataCabang(false);
    };
  
    const filterData = (
      shift,
      sandi_transaksi,
      jenis_transaksi,
      cabang,
      dari,
      sampai,
      cari
    ) => {
      let arusKas = arusKasCadangan;
      let arusKasGroup = arusKasGroupBySandiTransaksiCadangan;
  
      if (shift) {
        arusKas = arusKas.filter((item) => {
          return item.shift.toString() === shift;
        });
  
        arusKasGroup = arusKasGroup.filter((item) => {
          return item.shift.toString() === shift;
        });
      }
  
      if (sandi_transaksi) {
        arusKas = arusKas.filter((item) => {
          return item.id_sandi.toString() === sandi_transaksi;
        });
  
        arusKasGroup = arusKasGroup.filter((item) => {
          return item.id_sandi.toString() === sandi_transaksi;
        });
      }
  
      if (jenis_transaksi) {
        arusKas = arusKas.filter((item) => {
          return item.transaksi.jenis_transaksi.toString() === jenis_transaksi;
        });
  
        arusKasGroup = arusKasGroup.filter((item) => {
          return item.transaksi.jenis_transaksi.toString() === jenis_transaksi;
        });
      }
  
      if (cabang) {  
        arusKas = arusKas.filter((item) => {
          return item.id_cabang.toString() === cabang;
        });
  
        arusKasGroup = arusKasGroup.filter((item) => {
          return item.id_cabang.toString() === cabang;
        });
      }
  
      if (dari && !sampai) {
        arusKas = arusKas.filter((item) => {
          const d = new Date(dari);
          const s = new Date();
          const data = new Date(item.created_at);
  
          return data.getTime() >= d.getTime() && data.getTime() <= s.getTime();
        });
  
        arusKasGroup = arusKasGroup.filter((item) => {
          const d = new Date(dari);
          const s = new Date();
          const data = new Date(item.created_at);
  
          return data.getTime() >= d.getTime() && data.getTime() <= s.getTime();
        });
      } else if (dari && sampai) {
        arusKas = arusKas.filter((item) => {
          const d = new Date(dari);
          const s = new Date(`${sampai} 23:59:59`);
          const data = new Date(item.created_at);
  
          return data.getTime() >= d.getTime() && data.getTime() <= s.getTime();
        });
  
        arusKasGroup = arusKasGroup.filter((item) => {
          const d = new Date(dari);
          const s = new Date(`${sampai} 23:59:59`);
          const data = new Date(item.created_at);
  
          return data.getTime() >= d.getTime() && data.getTime() <= s.getTime();
        });
      }
  
      if (cari) {
        arusKas = arusKas.filter((item) => {
          return item.no_bukti.toString().match(cari);
        });
  
        arusKasGroup = arusKasGroup.filter((item) => {
          return item.no_bukti.toString().match(cari);
        });
      }
  
      setArusKasGroupBySandiTransaksi(arusKasGroup);
      setArusKas(arusKas);
      arrangeArusKas(arusKas);
    };
  
    return {
      currentUser,
      fields,
      kodeCabang,
      success,
      setSuccess,
      info,
      warning,
      setWarning,
      color,
      modalTitle,
      buttonSubmitName,
      arusKas,
      setArusKas,
      arusKasGroupBySandiTransaksi,
      setArusKasGroupBySandiTransaksi,
      isLoading,
      setIsLoading,
      currentArusKas,
      loadCurrentArusKas,
      details,
      dataCabang,
      setDataCabang,
      loadDataCabang,
      setLoadDataCabang,
      dataCabangCetakList,
      setDataCabangCetakList,
      dataRekening,
      setDataRekening,
      loadDataRekening,
      setLoadDataRekening,
      sandiTransaksiOptions,
      setSandiTransaksiOptions,
      currentSandiTransaksi,
      setCurrentSandiTransaksi,
      adminOptions,
      setAdminOptions,
      currentAdmin,
      setCurrentAdmin,
      input,
      setInput,
      filter,
      setFilter,
      laporan,
      filterData,
      toggleDetails,
      closeModalHandler,
      getDataArusKas,
      getDataArusKasById,
      getDataRekening,
      getDataSandiTransaksi,
      getDataCabang,
      arrangeArusKas,
      getArusKasGroupBySandiTransaksi,
    };
  };
  
  export default ArusKasHelper;
  