<script setup>
import axios from '@axios';
import { onBeforeMount, onMounted, onUnmounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
const store = useStore()
const router = useRouter()
const route = useRoute()
const cartEncoded = ref([
    {
        "product_id": 1,
        "qty": 2
    },
    {
        "product_id": 2,
        "qty": 3
    }
]);
const cartJson = ref()
const cart = route.query.cart
const plans = ref([]);
onBeforeMount(() => {
    // Example usage
    const encodedCart = encodeCartJson();
    console.log('Encoded:', encodedCart);

    decodeCartJson(encodedCart);
    console.log('Decoded:', cartJson.value);
});
onMounted(async () => {
    const fullRoute = {
        path: route.path,
        params: route.params,
        query: route.query,
        name: route.name,
        fullPath: route.fullPath,
    }

    console.log('Current route:', fullRoute.fullPath)
    localStorage.setItem('go_checkout', fullRoute.fullPath)
    let plansapi = await axios.post('/api/plans', {})
    console.log('Plans Data', plansapi.data)
    const finalArray = cartJson.value.map(cartItem => {
        const matchedProduct = plansapi.data.find(plan => plan.id === cartItem.product_id);
        if (matchedProduct) {
            return {
                ...matchedProduct,
                qty: cartItem.qty
            };
        }
        return null;
    }).filter(item => item !== null);
    const finalArrayJson = JSON.stringify(finalArray);

    // Save the JSON string to localStorage
    localStorage.setItem('cart_products', finalArrayJson);
    router.push('/pre-register');
    // plans.value = plansapi.data

});
onUnmounted(() => { });
const encodeCartJson = () => {
    const jsonStr = JSON.stringify(cartEncoded.value);
    const encodedStr = btoa(jsonStr);
    return encodedStr;
}

const decodeCartJson = (encodedStr) => {
    console.log(encodedStr)
    const jsonStr = atob(encodedStr);
    const decodedJson = JSON.parse(jsonStr);
    cartJson.value = decodedJson;
}



</script>

<template>
    <!-- Template content -->
</template>
