var app = angular.module('reportApp', []);

app.controller('ReportController', function ($scope, $http) {
    $scope.definitions = [];
    $scope.results = [];
    $scope.years = [];
    $scope.months = [
        { value: 1, label: 'Januari' },
        { value: 2, label: 'Februari' },
        { value: 3, label: 'Mars' },
        { value: 4, label: 'April' },
        { value: 5, label: 'Maj' },
        { value: 6, label: 'Juni' },
        { value: 7, label: 'Juli' },
        { value: 8, label: 'Augusti' },
        { value: 9, label: 'September' },
        { value: 10, label: 'Oktober' },
        { value: 11, label: 'November' },
        { value: 12, label: 'December' }
    ];

    $scope.init = function () {
        const now = new Date();
        $scope.endYear = now.getFullYear();
        $scope.endMonth = now.getMonth() + 1;
        $scope.startYear = $scope.endYear - 1;
        $scope.startMonth = $scope.endMonth;

        const baseYear = 2022;
        const thisYear = new Date().getFullYear();
        for (let y = baseYear; y <= thisYear + 1; y++) {
            $scope.years.push(y);
        }

        $http.get('/api/budget/definitions/items')
            .then(res => {
                $scope.definitions = res.data.map(d => {
                    d.Selected = true;
                    return d;
                });
            });
    };

    $scope.monthName = function (month) {
        const match = $scope.months.find(m => m.value === month);
        return match ? match.label : month;
    };

    $scope.loadReport = function () {
        const selectedDefs = $scope.definitions.filter(d => d.Selected);
        if (selectedDefs.length === 0) {
            alert("Välj minst en post att visa.");
            return;
        }

        const payload = {
            startYear: $scope.startYear,
            startMonth: $scope.startMonth,
            endYear: $scope.endYear,
            endMonth: $scope.endMonth,
            definitionIds: selectedDefs.map(d => d.Id)
        };


        $http.post('/api/report/report', payload)
            .then(res => {
                $scope.results = res.data;
                $scope.activeDefinitions = selectedDefs;
            })
            .catch(err => {
                console.error("Fel vid hämtning av rapport:", err);
                alert("Kunde inte ladda rapporten.");
            });
    };

    $scope.getAmount = function (row, defId) {
        const match = row.Definitions.find(d => d.DefinitionId === defId);
        return match ? match.TotalAmount : 0;
    };

    $scope.getRowTotal = function (row) {
        return row.Definitions.reduce((sum, d) => sum + d.TotalAmount, 0);
    };
});
