/* eslint-disable no-console */
/* eslint-disable no-undef */
$('#formSettings').submit(async e => {
  e.preventDefault();
  const data = $(e.target).serializeArray();
  const getToken = await fetch(`/session/key?s=jwt`);
  if (getToken.ok) {
    var token = await getToken.text();
    loading(10, true);
    let res = await fetch('/api/editable', {
      method: 'PUT',
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({data:{
        Active: (data.filter(i => i.name == 'editable')[0])?data.filter(i => i.name == 'editable')[0].value == 'on':false,
      }}),
    });
    if (res.ok) {
      loading(70, true);
      res = await fetch('/api/clear-monthly', {
        method: 'PUT',
        headers: {
          Authorization: `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({data:(data.filter(i => i.name == 'autoClear')[0])?{
          Active: data.filter(i => i.name == 'autoClear')[0].value == 'on',
          Every: data.filter(i => i.name == 'Every')[0].value||0,
        }:{
          Active: false,
          Every: 0,
        }}),
      });
      if (res.ok) {
        loading(100, true);
        showAlert('success', 'Berhasil menyimpan settings!');
        loading(0, false);
      } else {
        loading(0, false);
        showAlert('error', 'Terjadi kesalahan. Harap login kembali!');
      }
    } else {
      loading(0, false);
      showAlert('error', 'Terjadi kesalahan. Harap login kembali!');
    }
  } else {
    loading(0, false);
    showAlert('error', 'Terjadi kesalahan. Harap login kembali!');
  }
});
