<template>
    <div class="row bg-white padding-10 m-b-10 rounded" v-if="data">
        <div class="col-3 fs-12">{{ data.created_at }}</div>
        <div class="col fs-12">
            <span v-html="data.description"></span>
            <!-- Allow Credit Note to be downloaded for company NOT opted in E-Invoice -->
            <!-- <a target=”_blank” v-if="[9].includes(data.type) && !data.einvoice" @click="downloadTransaction(data)"><i class="fa fa-download fs-11 m-l-5 text-secondary hover-primary"></i></a> -->
        </div>
        <div class="col-2 text-success text-center">
            {{ [5, 9].includes(parseFloat(data.type)) ? formatValue(data.amount) : '' }}
        </div>
        <div class="col-2 text-danger text-center">
            {{ [1, 11].includes(parseFloat(data.type)) ? '- ' + (formatValue(data.amount)) : '' }}
        </div>
        <div class="col-2 text-right">{{ formatValue(data.running_balance) }}</div>
    </div>
</template>

<script setup lang="ts">
import { useComponentHandler } from '@/composables/useComponentHandler';
import { useCrudStore } from '@/stores/crud';
import route from '@/general/functions/router';

interface Props {
    data: any;
    decimals: number;
}

const props = defineProps<Props>();

const { item } = useComponentHandler(props);
const crudStore = useCrudStore();

const formatValue = (value: any) => {
    const val = parseFloat(value);
    if (isNaN(val)) return '';

    if (props.decimals !== 2) {
        return (Math.round((val + Number.EPSILON) * 100000) / 100000).toLocaleString('en-US', { 
            minimumFractionDigits: 5, 
            maximumFractionDigits: 5 
        });
    }

    return (Math.round((val + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

const downloadTransaction = async (paramItem: any) => {
    const url = route('transaction.credit_note.download', paramItem.id);
    const vaporEnabled = window.LARAVEL_VAPOR_ENABLED;
    
    if (vaporEnabled) {
        try {
            const response: any = await crudStore.crudRequest({ endpoint: url, method: 'get' });
            if (response && response.ok) {
                const result = await response.json();
                if (result.src) {
                    window.open(result.src, '_blank');
                }
            }
        } catch (error) {
            console.error('Download error:', error);
        }
    } else {
        window.open(url, '_blank');
    }
};
</script>
