<script setup>
import { ref, defineProps } from "vue";
import { SessionUser } from "@/components/session/token/SessionUser.vue";
import ConfigurationCategory from "@/components/displays/superuser/configuration/ConfigurationCategory.vue";
import Swal from "sweetalert2";

const props = defineProps({
  user: {
    type: Object,
    required: true,
  },
})

const washSubscriptionInvoice_template = {
    "id": 6250,
    "customer_id": 12345679,
    "cashier_id": 1857,
    "reference": "Vaskeabonnementer",
    "notes": "",
    "department_id": 10,
    "reg_1": "",
    "reg_2": "",
    "reg_3": "",
    "completed_at": null,
    "created_at": "2025-04-01 00:00:01",
    "deleted_at": null,
    "total_net_amount": 694,
    "invoice_collection_id": 1634,
    "booking_id": 0,
    "closed_at": "2025-04-24 12:45:10"
};


const washSubscriptionVehicles = ref(null);

const load = () => {
  if (!props.user.customer_number.value) {
    console.log('No customer number found');
    return;
  }
  // Load the vehicles
  loadVehicles();
  props.user.functions.getUserData();
}

const loadVehicles = () => {
  // Load the wash subscription invoices
  SessionUser.request(
      "/vehicles",
      "GET",
      {
        filters: 'customer_id:' + props.user.customer_number.value + ',wash_subscription:1',
      }
  ).then((response) => {
    washSubscriptionVehicles.value = response.data.data;
  }).catch((error) => {
    console.error(error);
  });
}

const hasActiveSubscriptions = () => {
  // If the user has no vehicles, return false
  if (!washSubscriptionVehicles.value) {
    return false;
  }
  // If the user has no active subscriptions, return false
  if (washSubscriptionVehicles.value.length === 0) {
    return false;
  }
  // If the user has active subscriptions, return true
  for (let i = 0; i < washSubscriptionVehicles.value.length; i++) {
    if (washSubscriptionVehicles.value[i].wash_subscription) {
      return true;
    }
  }
  return false;
}

const userHasSubscriptionInvoiceThisMonth = () => {
  // If the user has no invoices, return false
  if (!props.user.wash_subscription_transactions.value) {
    return false;
  }
  // If the user has no invoices, return false
  if (props.user.wash_subscription_transactions.value.length === 0) {
    return false;
  }
  // If the user has invoices, check if they are from this month
  for (let i = 0; i < props.user.wash_subscription_transactions.value.length; i++) {
    const invoice = props.user.wash_subscription_transactions.value[i];
    if (invoice.created_at.substring(0, 7) === new Date().toISOString().substring(0, 7)) {
      return true;
    }
  }
  return false;
}

const showAddSubscriptionInvoiceFormOtherMonth = () => {
  // Require the customer number to be set, and be above 0
  if (!props.user.customer_number.value || props.user.customer_number.value <= 0) {
    Swal.fire({
      icon: 'error',
      title: SessionUser.objects.global.language.error,
      text: SessionUser.objects.global.language.customer_number + ' ' + SessionUser.objects.global.language.invalid.toLowerCase(),
      showConfirmButton: true,
    })
    return;
  }
  const lastTwelveMonths = [];
  const currentDate = new Date();
  const currentMonth = currentDate.getMonth();
  const currentYear = currentDate.getFullYear();
  // Get the last twelve months (not including the current month)
  for (let i = 0; i < 12; i++) {
    const month = new Date(currentYear, currentMonth - (i), 2);
    lastTwelveMonths.push({
      month: month.toLocaleString('default', { month: 'long' }),
      year: month.getFullYear(),
      value: month.toISOString().substring(0, 7),
    });
  }
  // Show the SweetAlert2 modal
  Swal.fire({
    title: SessionUser.objects.global.language.add + ' ' + SessionUser.objects.collectedOrderInvoices.meta.labels.single,
    html: '<p>' + SessionUser.objects.global.language.select + ' ' + SessionUser.objects.global.language.month.toLowerCase() + '</p>',
    input: 'select',
    inputOptions: lastTwelveMonths.reduce((options, month) => {
      options[month.value] = month.month + ' ' + month.year;
      return options;
    }, {}),
    inputPlaceholder: SessionUser.objects.global.language.select + ' ' + SessionUser.objects.global.language.month.toLowerCase(),
    showCancelButton: true,
    confirmButtonText: SessionUser.objects.global.language.add,
  }).then((result) => {
    if (result.isConfirmed) {
      const selected = result.value;
      console.log(selected);
      const monthNumber = selected.substring(5, 7);
      const yearNumber = selected.substring(0, 4);
      // Redirect to the invoice creation page
      console.log(
          'Month: ' + monthNumber + ', Year: ' + yearNumber
      );
      createVehicleSubscriptionInvoice(monthNumber, yearNumber);
    }
  });
}

const createVehicleSubscriptionInvoice = (month, year) => {
  SessionUser.request(
      "/collected-invoices/vehicle-subscriptions/custom",
      "POST",
      {
        customer_number: props.user.customer_number.value,
        month: month,
        year: year,
      }
  ).then((response) => {
    console.log(response);
    // Reload the data
    load();
    // Redirect to the invoice creation page
    SessionUser.functions.redirectTo.superUser('/invoices/' + response.data.data.id, true);
  }).catch((error) => {
    console.error(error);
  });
}

load();
</script>

<template>
  <div>
    <ConfigurationCategory
      v-show="hasActiveSubscriptions()"
      :module="SessionUser.objects.vehicles.meta.title"
      :title="SessionUser.objects.global.language.subscriptions"
      :subtitle="SessionUser.objects.global.language.active"
      icon="fas fa-car"
      >
      <template #default>
        <div class="columns is-multiline">
          <template v-for="(vehicle, index) in washSubscriptionVehicles" :key="index">
            <div class="column is-4-desktop">
              <div class="card">
                <div class="card-header">
                  <div class="card-header-icon">
                    <span class="icon">
                      <i class="fas fa-car"></i>
                    </span>
                  </div>
                  <div class="card-header-title">
                    <span class="is-size-6 title">{{ vehicle.reg }}</span>
                  </div>
                  <div class="card-header-icon">
                    <span
                        class="tag is-light is-size-7"
                        :class="vehicle.wash_subscription ? 'is-success' : 'is-grey'"
                    >
                      {{ vehicle.wash_subscription ? SessionUser.objects.global.language.active : SessionUser.objects.global.language.inactive }}
                    </span>
                  </div>
                </div>
                <div class="card-content">
                  <p><strong>{{SessionUser.objects.vehicles.columns.type.label}}:</strong> {{ SessionUser.objects.products.functions.getProductName(vehicle.type) }}</p>
                  <p><strong>Addons:</strong></p>
                  <ul>
                    <li v-for="(addon, index) in vehicle.addons.list" :key="index">
                      {{ addon.product.name }}
                    </li>
                  </ul>
                </div>
              </div>
            </div>
          </template>
        </div>
      </template>
    </ConfigurationCategory>
    <!-- Invoices -->
    <ConfigurationCategory
      v-show="(user.wash_subscription_transactions.value !== null && user.wash_subscription_transactions.value.length > 0) || (hasActiveSubscriptions())"
      :module="SessionUser.objects.collectedOrderInvoices.meta.title"
      :title="SessionUser.objects.vehicles.meta.title"
      :subtitle="SessionUser.objects.global.language.subscriptions"
      icon="fas fa-file-invoice-dollar"
      >
      <template #default>
        <div class="columns is-multiline">
          <template v-for="(invoice, index) in user.wash_subscription_transactions.value" :key="index">
            <div class="column is-4-desktop">
              <div class="card">
                <div class="card-header">
                  <div class="card-header-icon">
                    <span class="icon">
                      <i class="fas fa-file-invoice-dollar"></i>
                    </span>
                  </div>
                  <div class="card-header-title">
                    <span class="is-size-6 title">{{ SessionUser.functions.date.getDateMonthName(invoice.created_at).toUpperCase() }} - {{ SessionUser.functions.date.getDateYear(invoice.created_at) }}</span>
                  </div>
                  <div class="card-header-icon">
                    <span
                        class="tag is-light is-size-7"
                        :class="invoice.closed_at ? 'is-success' : 'is-grey'"
                    >
                      {{ invoice.closed_at
                        ? (invoice.closed_at)
                        : SessionUser.objects.global.language.inactive
                      }}
                    </span>
                  </div>
                </div>
                <div class="card-content">
                  <h2 class="has-text-centered title is-size-2">{{ SessionUser.functions.currency.toLocal(invoice.total_net_amount) }}</h2>
                  <div class="buttons is-centered">
                    <!-- Show invoice collection -->
                    <button
                      class="button is-light is-fullwidth"
                      @click="SessionUser.functions.redirectTo.superUser('/invoices/' + invoice.invoice_collection_id, true)"
                    >
                      {{SessionUser.objects.global.language.show}} {{ SessionUser.objects.collectedOrderInvoices.meta.labels.single }}
                    </button>
                    <!-- Show transaction -->
                    <button
                      class="button is-light is-fullwidth"
                      @click="SessionUser.functions.redirectTo.department(10, 'modules/pos/orders/' + invoice.id, true)"
                    >
                      {{SessionUser.objects.global.language.show}} {{ SessionUser.objects.orders.meta.labels.single }}
                    </button>
                  </div>
                </div>
                <!-- Card footer -->
                <div class="card-footer">
                  <div class="card-footer-item">
                    <span class="icon">
                      <i class="fas fa-calendar-alt"></i>
                    </span>
                    <span>{{ SessionUser.functions.date.getDateMonthName(invoice.created_at) }} {{ SessionUser.functions.date.getDateYear(invoice.created_at) }}</span>
                  </div>
                  <div class="card-footer-item">
                    <span class="icon">
                      <i class="fas fa-user"></i>
                    </span>
                    <span>{{ invoice.customer_id }}</span>
                  </div>
                </div>
              </div>
            </div>
          </template>
          <!-- Add invoice button -->
          <div class="column is-12">
            <div class="buttons">
              <!-- If the user has invoices this month, show the message -->
              <button
                v-if="userHasSubscriptionInvoiceThisMonth()"
                class="button is-light is-fullwidth"
                disabled
              >
                {{SessionUser.objects.global.language.invoice_already_created}} {{ SessionUser.objects.global.language.time.this_month.toLowerCase() }}
              </button>
              <!-- Allow the user to create a new invoice for another month -->
              <button
                class="button is-light is-fullwidth"
                @click="showAddSubscriptionInvoiceFormOtherMonth"
              >
                {{SessionUser.objects.global.language.add}} {{ SessionUser.objects.collectedOrderInvoices.meta.labels.single.toLowerCase() }} {{ SessionUser.objects.global.language.other_period.toLowerCase() }}
              </button>
            </div>
          </div>
        </div>
      </template>
    </ConfigurationCategory>
  </div>
</template>

<style scoped>

</style>