<script setup>
import PageTitle from "@/components/global/PageTitle.vue";
import RestrictedPageWrapper from "@/components/page/wrappers/RestrictedPageWrapper.vue";
import { SessionUser } from "@/components/session/token/SessionUser.vue";
import { useRouter } from 'vue-router'
import { ref } from 'vue';
import { ConfigurationSelectOption } from "@/components/displays/superuser/configuration/ConfigurationSelectObject.vue";
import ConfigurationSubPageWrapper
  from "@/views/dashboards/superUserDashboard/configuration/ConfigurationSubPageWrapper.vue";
import ConfigurationCategory from "@/components/displays/superuser/configuration/ConfigurationCategory.vue";
import ConfigurationSwitch from "@/components/displays/superuser/configuration/ConfigurationSwitch.vue";
import ConfigurationSelect from "@/components/displays/superuser/configuration/ConfigurationSelect.vue";
import Swal from "sweetalert2";

// Get the department from the route
const router = useRouter()

const layouts = ref([]);
const payment_terms = ref([]);
const module_config = ref([]);

const getLayouts = async () => {
  await SessionUser.superUser.modules.economic.layouts.get().then((response) => {
    const tmp_layouts = response.data.data;
    for (let i = 0; i < tmp_layouts.length; i++) {
      layouts.value.push(
        ConfigurationSelectOption(
          tmp_layouts[i].name, tmp_layouts[i].layoutNumber,
        )
      );
    }
  }).catch((error) => {
    console.log(error);
  });
};

const getPaymentTerms = async () => {
  await SessionUser.superUser.modules.economic.paymentTerms.get().then((response) => {
    const tmp_payment_terms = response.data.data;
    for (let i = 0; i < tmp_payment_terms.length; i++) {
      payment_terms.value.push(
        ConfigurationSelectOption(
          tmp_payment_terms[i].name, tmp_payment_terms[i].paymentTermsNumber,
        )
      );
    }
    console.log(payment_terms.value);
  }).catch((error) => {
    console.log(error);
  });
};

const getModuleConfig = async () => {
  await SessionUser.superUser.modules.economic.config.get_all().then((response) => {
    let tmp_module_config = response.data.data;
    let tmp_module_config_array = [];
    for (const [key, value] of Object.entries(tmp_module_config)) {
      console.log(`${value.variable}: ${value.value}`);
      tmp_module_config_array.push({
        variable: value.variable,
        value: value.value,
      });
    }
    module_config.value = tmp_module_config_array;
    console.log(module_config.value);
  }).catch((error) => {
    console.log(error);
  });
};

const getModuleConfigValue = (variable) => {
  const config = module_config.value.find((config) => config.variable === variable);
  // Log to the console, what the value was found
  if (config) {
    console.log(`Found value for ${variable}: ${config.value}`);
  } else {
    console.log(`No value found for ${variable}`);
  }
  return config ? config.value : '';
};

const load = async () => {
  await getLayouts();
  await getModuleConfig();
};

const showPaymentTerms = async () => {
  await getPaymentTerms().then((result) => {
    Swal.fire({
      title: 'Payment terms',
      html: '<div id="payment-terms-list"></div>',
      showCloseButton: true,
      showCancelButton: false,
      showConfirmButton: false,
    });
    const paymentTermsList = document.getElementById('payment-terms-list');
    const paymentTermElement = document.createElement('table');
    paymentTermElement.classList.add('table', 'is-striped', 'is-hoverable', 'is-fullwidth');
    paymentTermElement.innerHTML = `
      <thead>
        <tr>
          <th>Label</th>
          <th>Value</th>
        </tr>
      </thead>
      <tbody></tbody>
    `;
    paymentTermElement.querySelector('tbody').innerHTML = '';
    payment_terms.value.forEach((paymentTerm) => {
      const paymentTermRow = document.createElement('tr');
      paymentTermRow.innerHTML = `
        <td>${paymentTerm.label}</td>
        <td>${paymentTerm.value}</td>
      `;
      paymentTermElement.querySelector('tbody').appendChild(paymentTermRow);
    });
    paymentTermsList.appendChild(paymentTermElement);
    Swal.getHtmlContainer().appendChild(paymentTermsList);
  }).catch((error) => {
    console.log(error);
  });
};

load();
</script>

<template>
  <RestrictedPageWrapper :hasPermission="SessionUser.canAccessSuperUser()">
    <ConfigurationSubPageWrapper>
      <template #title>
        <PageTitle title="E-conomic configuration" subtitle="The configuration of the E-conomic integration" />
      </template>
      <template v-if="module_config.length > 0" #content>
        <ConfigurationCategory
            class="mt-2"
            module="E-conomic"
            title="Invoice settings"
            description="The E-conomic configuration allows you to configure the integration with the E-conomic accounting system."
            icon="fas fa-cogs"
          >
          <ConfigurationSelect
            label="Invoice template"
            description="Select the invoice template to use for the E-conomic integration."
            :options="layouts"
            :value="getModuleConfigValue('invoiceLayoutNumber')"
            :on-select="SessionUser.superUser.modules.economic.config.layouts.invoiceLayoutNumber.set"
          />
          <!-- Buttons -->
          <button
            class="button is-link is-small mt-2"
            @click="showPaymentTerms"
          >
            <span class="icon">
              <i class="fas fa-list"></i>
            </span>
            <span>Show payment terms</span>
          </button>
        </ConfigurationCategory>
      </template>
    </ConfigurationSubPageWrapper>
  </RestrictedPageWrapper>
</template>

<style scoped>

</style>