<script>
  // @ts-nocheck

  import { browser } from "$app/environment";
  import { getAuthInfo, makeAuthHeaderForAxios } from "$lib/auth/Auth.js";
  import { makePost } from "$lib/tools/requests/requests.js";
  import { sayError } from "$lib/tools/toaster/Toaster.js";

  export let data;
  let { reqID } = data;
  let { token } = data;

  let reqInfo = [];
  let value_bankName;
  let value_cardNumber;
  let value_phone;
  let value_status;

  let canChange = false;

  $: reqInfo, bindValues();
  $: value_cardNumber, value_phone, value_status, checkFields();

  function bindValues() {
    value_bankName = reqInfo[0]?.bankname;
    value_cardNumber = reqInfo[0]?.cardnumber;
    value_phone = reqInfo[0]?.phone;
    value_status = reqInfo[0]?.status === "t";
  }

  function checkFields() {

    if(value_cardNumber?.length !== 16)
    {
        canChange = false;
        return;
    }
    if(value_phone?.length !== 11)
    {
        canChange = false;
        return;
    }

    canChange = true;

  }

  async function getReqInfo() {
    const result = await makePost(
      "getRequisite",
      {
        token: token,
      },
      makeAuthHeaderForAxios(getAuthInfo()?.a)
    );
    if (result.status === 401) {
      sayError("Данные авторизации устарели");
      window.location.href = "/";
      return;
    }
    if (result.error) {
      sayError("Не удалось получить реквизиты пользователя");
      return;
    }
    console.log(result.data);
    reqInfo = result.data.filter((s) => s.id === reqID);
  }

  async function changeRequisite() {
    //changeRequisite
    canChange = false;
    const result = await makePost(
      "changeRequisite",
      {
        ...reqInfo[0],
        bankname: value_bankName,
        cardnumber: value_cardNumber,
        phone: value_phone,
        status: value_status ? "true":"false"
      },
      makeAuthHeaderForAxios(getAuthInfo()?.a)
    );
    if (result.status === 401) {
      sayError("Данные авторизации устарели");
      window.location.href = "/";
    //   canChange = true;
      return;
    }
    if (result.error) {
      sayError("Не удалось изменить реквизит пользователя");
      canChange = true;
      return;
    }
    document.getElementById("ref")?.click();
    // canChange = true;
  }

  if (browser) {
    getReqInfo();
  }
</script>

<div class="w-full flex flex-col gap-8">
  <div class="flex gap-4">
    <div class="bg-accent rounded-[4px] w-[10px] h-full"></div>
    <h1 class="text-2xl font-semibold">Изменение реквизита (ID: {reqID})</h1>
  </div>
  <div class="w-full flex flex-col p-4 gap-2 rounded-box bg-base-300">
    {#each reqInfo as req}
      <select
        bind:value={value_bankName}
        class="select select-bordered w-full text-base"
      >
        <option disabled selected value="-1">Банк</option>
        <option value="sber">Сбер</option>
        <!-- <option value="2">Модератор</option>
        <option value="4">Администратор</option> -->
      </select>
      <label class="input input-bordered flex items-center gap-2">
        Номер карты
        <input
          type="text"
          class="grow text-info"
          bind:value={value_cardNumber}
        />
      </label>
      <label class="input input-bordered flex items-center gap-2">
        Телефон
        <input type="text" class="grow text-info" bind:value={value_phone} />
      </label>
      <div class="flex p-4 items-center gap-2">
        <p>Активный:</p>
        <input
          bind:checked={value_status}
          type="checkbox"
          class="toggle toggle-primary"
        />
      </div>
      <button on:click={()=>{changeRequisite()}} class="btn btn-primary" disabled={!canChange}>Сохранить</button>
      <a href={"/user/profile/"+token} class="hidden" id="ref"></a>
    {/each}
  </div>
</div>
