<!-- Add articles view -->
<script setup lang="ts">
import { computed, inject, onMounted, ref } from 'vue';
import ContainerSmall from '../components/layout/ContainerSmall.vue';
import Slider from '../components/form/Slider.vue';
import useBgImage from '../composables/useBgImage';
import Button from '../components/base/Button.vue';
import { AppConfigType } from '../types';
import usePopupWindow from '../composables/usePopupWindow';
import { useRouter } from 'vue-router';
import useSetPageTitle from '../composables/useSetPageTitle';
import { useGettext } from 'vue3-gettext';
import Axios from '~src/shared/axios';
import {useNotificationStore} from '../stores/useNotificationStore';

// Translations
const { $gettext } = useGettext();

// Set page title
useSetPageTitle($gettext('Add articles'));

// Get plugin config
const config: AppConfigType = inject('pluginConfig');

// Show notification
const { addNotification } = useNotificationStore();

// Router
const router = useRouter();

// Buy URL
const buyUrl = ref('');

// Set backgroud image on body
useBgImage(config.plugin_url);

// Calculate the price
const selectedArticles = ref(1);
const articlePrice = 1;

const subtotalPrice = computed(() => {
    return articlePrice * selectedArticles.value;
});

const taxPrice = computed(() => {
    return (subtotalPrice.value * 1.23).toFixed(2);
});

// Open payment popup window
const openPaymentPopup = () => {
    usePopupWindow(buyUrl.value, 900, 600, () => {
        // Go to main page
        router.push('/');
    });
};

// Get the buy URL from the API
onMounted(async () => {
	try {
        // Call the WordPress Rest API to get the buy URL
        const response = await Axios.get(`${config.rest.endpoints.boostsite}/generate_stripe_url`);

        // Check if the response is successful
        if (response.status !== 200 || !response.data.success) {
            throw new Error(`REST API error: ${response.status} - ${response.statusText}`);
        }

		if (response.data.data?.url) {
			buyUrl.value = response.data.data.url;
		}
    } catch (error) {
        console.error('Error generating while getting the url:', error);

        addNotification({
            message: $gettext('There was an unexpected error!'),
            type: 'danger',
        });
    }
});
</script>

<template>
	<ContainerSmall>
		<!-- Logo -->
		<img
			width="139px"
			class="max-md:mx-auto mb-10"
			:src="`${config.plugin_url}/public/images/boostsite-logo.png`"
		/>

		<!-- Number of additional articles -->
		<p class="font-bold mb-2Q">{{ $gettext('Additional articles') }}</p>
		<Slider class="mb-10" v-model="selectedArticles" />

		<!-- Subtotal and tax -->
		<div class="py-5 border-y border-y-neutral-900">
			<div class="flex justify-between items-center pb-2.5">
				<p class="font-bold">{{ $gettext('Subtotal') }}</p>

				<p>${{ subtotalPrice }}</p>
			</div>

			<div class="flex justify-between items-center">
				<p class="font-bold">{{ $gettext('Tax') }}</p>

				<p>${{ taxPrice }}</p>
			</div>
		</div>

		<!-- Total -->
		<div class="flex justify-between items-center py-8 md:py-11">
			<p class="font-bold">{{ $gettext('Total due today') }}</p>

			<p class="font-bold text-xl md:text-2xl leading-xl">${{ taxPrice }}</p>
		</div>

		<!-- Go to payment -->
		<Button
			class="w-full mb-10"
			:text="$gettext('Proceed to payment')"
			size="large"
			@click.prevent="openPaymentPopup"
			:loading="buyUrl === ''"
			:disabled="buyUrl === ''"
		/>
	</ContainerSmall>
</template>


<style scoped></style>
