<template>
    <theme-table :noneActions="true">
        <span slot="main-title">
            {{ $t('Profit & Loss Statement') }} {{ current_year }} / {{ branch_name }}
        </span>
        <template slot="more-button">
            <button class="btn btn-secondary" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasRight"
                aria-controls="offcanvasRight">{{ $t('Filter') }}</button>
            <div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasRight"
                aria-labelledby="offcanvasRightLabel">
                <div class="offcanvas-header">
                    <h5 class="offcanvas-title" id="offcanvasRightLabel">{{ $t('Filter') }}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
                </div>
                <div class="offcanvas-body">
                    <label class="form-label">{{ $t('Branch') }}</label>
                    <div class="mb-3 d-flex">
                        <Multiselect v-model="params.branch_id" :placeholder="$t('Branch')" label="name_en"
                            :searchable="true" :options="branchs" />
                    </div>
                    <label class="form-label">{{ $t('Year') }}</label>
                    <div class="mb-3 d-flex">
                        <date-picker type="year" v-model="params.year" valueType="format"
                            :format="formatYear"></date-picker>
                    </div>
                    <div class="list-group mb-3">
                        <button type="button" class="btn btn-success" @click="funGetData"><i class="fa fa-search"></i>
                            {{ $t('Search') }}</button>
                    </div>
                    <div class="list-group mb-3">
                        <button type="button" @click="printP" class="btn btn-primary"><i class="fa fa-print"></i> {{
                            $t('Print') }}</button>
                    </div>
                    <div class="list-group mb-3">
                        <button type="button" @click="exportExcell" class="btn btn-danger"><i
                                class="fa fa-file-export"></i> {{ $t('Export') }}</button>
                    </div>
                </div>
            </div>
        </template>

        <div slot="body">
            <div id="show-print">
                <div class="table-responsive tbscroll_nopaginat report_print">
                    <h5 class="mb-4 text-center d-none d-print-block">
                        PROFIT & LOSS STATEMENT BY MONTH FOR {{ current_year }} / {{ branch_name }}
                    </h5>
                    <!-- <table class="table table-hover">
                        <thead class="table-light"> -->
                    <table class="table table-bordered" id="excel-table">
                        <thead class="text-nowrap table-active fixed_table">
                            <tr>
                                <th>No</th>
                                <th>Type</th>
                                <th v-for="monthName in monthNames">
                                    {{ getFullMonthName(monthName) }}
                                </th>
                                <th>TOTAL</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>1</td>
                                <td class="text-nowrap">TOTAL INCOME</td>
                                <td v-for="(monthName, index) in monthNames" :key="index">
                                    {{ monthlyData[monthName].income | numberFomartValue }}
                                </td>
                                <td>{{ this.summary.totalIncome | numberFomartValue }}</td>
                            </tr>
                            <tr>
                                <td>2</td>
                                <td class="text-nowrap">TOTAL EXPENSE</td>
                                <td v-for="(monthName, index) in monthNames" :key="index">
                                    {{ monthlyData[monthName].expense | numberFomartValue }}
                                </td>
                                <td>{{ this.summary.totalExpense | numberFomartValue }}</td>
                            </tr>
                            <tr class="table-active">
                                <td colspan="2" class="text-center text-nowrap"><strong>NET PROFIT/LOSS</strong></td>
                                <td v-for="(monthName, index) in monthNames" :key="index">
                                    <strong>{{ monthlyData[monthName].profit | numberFomartValue }}</strong>
                                </td>
                                <td><strong>{{ this.summary.netProfit | numberFomartValue }}</strong></td>
                            </tr>
                            <tr>
                                <td colspan="2" class="text-center"><strong>Trend</strong></td>
                                <td v-for="(monthName, index) in monthNames" :key="index">
                                    <div class="progress" style="height: 10px;">
                                        <div :class="monthlyData[monthName].profit >= 0 ? 'progress-bar bg-success' : 'progress-bar bg-danger'"
                                            :style="{ width: Math.min(Math.abs(calculateMargin(monthlyData[monthName].income, monthlyData[monthName].profit)) * 2, 100) + '%' }">
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <div class="progress" style="height: 10px;">
                                        <div :class="this.summary.netProfit >= 0 ? 'progress-bar bg-success' : 'progress-bar bg-danger'"
                                            :style="{ width: Math.min(Math.abs(calculateMargin(this.summary.totalIncome, this.summary.netProfit)) * 2, 100) + '%' }">
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                        <!-- <thead class="table-light">
                            <tr>
                                <th>No</th>
                                <th>Month</th>
                                <th>Income</th>
                                <th>Expense</th>
                                <th>Profit/Loss</th>
                                <th>Margin</th>
                                <th>Trend</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="(monthName, index) in monthNames" :key="index">
                                <td>{{index+1}}</td>
                                <td>{{ getFullMonthName(monthName) }}</td>
                                <td>{{ monthlyData[monthName].income | numberFomartValue}}</td>
                                <td>{{ monthlyData[monthName].expense | numberFomartValue}}</td>
                                <td :class="monthlyData[monthName].profit >= 0 ? 'positive-profit' : 'negative-profit'">
                                    {{ monthlyData[monthName].profit | numberFomartValue}}
                                </td>
                                <td>{{ calculateMargin(monthlyData[monthName].income, monthlyData[monthName].profit) }}%</td>
                                <td>
                                    <div class="progress" style="height: 10px;">
                                        <div 
                                            :class="monthlyData[monthName].profit >= 0 ? 'progress-bar bg-success' : 'progress-bar bg-danger'" 
                                            :style="{ width: Math.min(Math.abs(calculateMargin(monthlyData[monthName].income, monthlyData[monthName].profit)) * 2, 100) + '%' }">
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        </tbody> -->
                    </table>
                    <apexchart type="area" class="px-0" height="400px" :options="chartOptions" :series="chartSeries"></apexchart>
                    <footer-report style="display: none;"></footer-report>
                </div>
            </div>
        </div>
    </theme-table>
</template>

<script>
import HeaderReport from "../../../components/report/header.vue";
import FooterReport from "../../../components/report/footer.vue";
import ThemeTable from "../../../components/ThemeTable.vue";
import { exportTableToExcel } from "../../../exportExcel.js";
import moment from "moment";
export default {
    components: {
        HeaderReport,
        FooterReport,
        ThemeTable
    }, 
    data() {
        return {
            monthlyData: {},
            branchs: {},
            current_year: '',
            branch_name: '',
            formatYear: "YYYY",
            moment: moment,
            summary: {
                totalIncome: 0,
                totalExpense: 0,
                netProfit: 0,
                profitMargin: 0
            },
            params: {
                branch_id: '',
                year: new Date().getFullYear(),
            },
            chart: null,
            monthNames: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
        }
    },
    mounted() {
        this.initMonthlyData();
        this.funGetData();
        this.getBranch();
    },


    computed: {

        chartSeries() {
            const incomeData = this.monthNames.map(month => {
                return this.monthlyData[month]?.income || 0;
            });

            const expenseData = this.monthNames.map(month => {
                return this.monthlyData[month]?.expense || 0;
            });

            const profitData = this.monthNames.map(month => {
                return this.monthlyData[month]?.profit || 0;
            });
            return [
                {
                    name: 'Total Income',
                    type: 'area',
                    data: incomeData
                },
                {
                    name: 'Total Expense',
                    type: 'area',
                    data: expenseData
                },
                {
                    name: 'Net Profit/Loss',
                    type: 'area',
                    data: profitData
                }
            ];
        },
        chartOptions() {
            return {
                chart: {
                    type: 'area',
                    toolbar: { show: false },
                    zoom: { enabled: false },
                    stacked: false,
                },
                colors: ['#adb5bd', '#52b788', '#0096c7'],
                dataLabels: { enabled: false },
                stroke: {
                    width: 2,
                    curve: 'smooth'
                },

                xaxis: {
                    categories: this.monthNames,
                    labels: { style: { colors: '#6B7280' } },
                    axisBorder: { show: false },
                    axisTicks: { show: false },
                },
                yaxis: {
                    labels: {
                        style: { colors: '#6B7280' },
                        formatter: (value) => this.formatAxisLabel(value)
                    }
                },
                grid: { borderColor: '#e5e7eb' },
                tooltip: {
                    shared: true,
                    intersect: false,
                    y: {
                        formatter: (val) => Vue.filter('numberFomartValue')(val)
                    }
                },
                legend: {
                    show: true,
                    position: 'top',
                    horizontalAlign: 'right',
                    offsetY: 0
                }
            };
        }
    },
    methods: {

        formatAxisLabel(value) {
            if (value === 0) return '0';
            const sign = value < 0 ? '-' : '';
            const absValue = Math.abs(value);

            if (absValue >= 1e6) return sign + (absValue / 1e6).toFixed(1) + 'M';
            if (absValue >= 1e3) return sign + (absValue / 1e3).toFixed(1) + 'K';
            return sign + absValue.toFixed(0);
        },


        getBranch() {
            axios.get("admin-api/com-branch").then((res) => {
                this.branchs = res.data;
            }).catch((error) => {
                console.log(error);
            });
        },
        initMonthlyData() {
            this.monthlyData = {};
            this.monthNames.forEach(month => {
                this.monthlyData[month] = {
                    income: 0,
                    expense: 0,
                    profit: 0
                };
            });
        },
        funGetData() {
            axios.get('/accounting/profit-and-loss-statement-by-month', {
                params: this.params,
            }).then(response => {
                this.monthlyData = response.data.monthlyData;
                this.current_year = response.data.year;
                this.branch_name = response.data.branch_name;
                this.calculateSummary();
                this.renderChart();
            }).catch(error => {
                if (error.message == "Request failed with status code 403") {
                    this.$router.push({ name: "permissionTest" });
                } else {
                    console.log(error.message);
                }
            });
        },
        calculateSummary() {
            this.summary.totalIncome = 0;
            this.summary.totalExpense = 0;
            this.summary.netProfit = 0;

            for (const month in this.monthlyData) {
                this.summary.totalIncome += this.monthlyData[month].income;
                this.summary.totalExpense += this.monthlyData[month].expense;
                this.summary.netProfit += this.monthlyData[month].profit;
            }
            this.summary.profitMargin = this.summary.totalIncome > 0 ? ((this.summary.netProfit / this.summary.totalIncome) * 100).toFixed(2) : 0;
        },
        renderChart() {
            if (this.chart) {
                this.chart.destroy();
            }

            const incomeData = this.monthNames.map(month => this.monthlyData[month].income / 1000);
            const expenseData = this.monthNames.map(month => this.monthlyData[month].expense / 1000);
            const profitData = this.monthNames.map(month => this.monthlyData[month].profit / 1000);

            const ctx = this.$refs.monthlyChart.getContext('2d');
            this.chart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: this.monthNames,
                    datasets: [
                        {
                            label: 'Income',
                            data: incomeData,
                            backgroundColor: 'rgba(54, 162, 235, 0.5)',
                            borderColor: 'rgba(54, 162, 235, 1)',
                            borderWidth: 1
                        },
                        {
                            label: 'Expense',
                            data: expenseData,
                            backgroundColor: 'rgba(255, 99, 132, 0.5)',
                            borderColor: 'rgba(255, 99, 132, 1)',
                            borderWidth: 1
                        },
                        {
                            label: 'Profit',
                            data: profitData,
                            backgroundColor: 'rgba(75, 192, 192, 0.5)',
                            borderColor: 'rgba(75, 192, 192, 1)',
                            borderWidth: 1,
                            type: 'line',
                            tension: 0.1
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: 'Amount (in thousands)'
                            }
                        }
                    },
                    plugins: {
                        title: {
                            display: true,
                            text: 'Monthly Income, Expenses, and Profit'
                        }
                    }
                }
            });
        },
        calculateMargin(income, profit) {
            return income > 0 ? ((profit / income) * 100).toFixed(2) : 0;
        },
        getFullMonthName(monthAbbr) {
            const months = {
                'Jan': 'January',
                'Feb': 'February',
                'Mar': 'March',
                'Apr': 'April',
                'May': 'May',
                'Jun': 'June',
                'Jul': 'July',
                'Aug': 'August',
                'Sep': 'September',
                'Oct': 'October',
                'Nov': 'November',
                'Dec': 'December'
            };
            return months[monthAbbr] || monthAbbr;
        },
        printP() {
            this.$htmlToPaper('show-print');
        },
        async exportExcell() {
            this.$isLoading(true)
            try {
                await exportTableToExcel({
                    tableId: "excel-table",
                    filename: "ExportProfitAndLossStatementByMonth",
                    reportTitle: "PROFIT & LOSS STATEMENT BY MONTH FOR 2025",
                    subDate:this.params.date,
                })
            } catch (e) {
                this.$toast.warning(e.message);
            } finally {
                this.$isLoading(false)
            }
        }
    }
};
</script>