angular.module('budgetApp', [])
    .controller('BudgetOverviewController', ['$scope', '$http', function ($scope, $http) {

        $scope.years = [];
        $scope.categoryDefColumns = [];
        $scope.categoryLabelColumns = [];
        $scope.itemDefColumns = [];
        $scope.itemLabelColumns = [];

        $scope.selectedCategoryDef = {};
        $scope.selectedCategoryLabel = {};
        $scope.selectedItemDef = {};
        $scope.selectedItemLabel = {};

        $scope.dropdownOpenCatDef = false;
        $scope.dropdownOpenCatLabel = false;
        $scope.dropdownOpenItemDef = false;
        $scope.dropdownOpenItemLabel = false;

        $scope.searchCategoryDef = '';
        $scope.searchCategoryLabel = '';
        $scope.searchItemDef = '';
        $scope.searchItemLabel = '';

        $scope.selectedMonths = {};
        $scope.dropdownOpenMonth = false;
        $scope.searchMonth = '';
        $scope.splitByYear = true; // standard: per år


        $scope.monthNames = ["Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"];
        $scope.categoryColors = { catDef: {}, catLabel: {} };
        $scope.columnOrder = { categoryDef: [], categoryLabel: [], itemDef: [], itemLabel: [] };

        $scope.openDropdown = function (type) {
            $scope.dropdownOpenCatDef = false;
            $scope.dropdownOpenCatLabel = false;
            $scope.dropdownOpenItemDef = false;
            $scope.dropdownOpenItemLabel = false;
            if (type === 'catDef') $scope.dropdownOpenCatDef = true;
            if (type === 'catLabel') $scope.dropdownOpenCatLabel = true;
            if (type === 'itemDef') $scope.dropdownOpenItemDef = true;
            if (type === 'itemLabel') $scope.dropdownOpenItemLabel = true;
        };

        document.addEventListener('click', function (event) {
            const el = document.querySelector('.budget-column-selector-wrapper');
            if (el && !el.contains(event.target)) {
                $scope.$apply(function () {
                    $scope.dropdownOpenCatDef = false;
                    $scope.dropdownOpenCatLabel = false;
                    $scope.dropdownOpenItemDef = false;
                    $scope.dropdownOpenItemLabel = false;
                    $scope.dropdownOpenMonth = false;

                });
            }
        });

        $http.get('/api/budget/metadata').then(function (metaRes) {
            // Fyll metadata-kolumner
            $scope.categoryDefColumns = (metaRes.data.CategoryDefinitions || []).map(c => c.Name);
            $scope.categoryLabelColumns = (metaRes.data.CategoryLabels || []).map(c => c.Name);
            $scope.itemDefColumns = (metaRes.data.ItemDefinitions || []).map(c => c.Name);
            $scope.itemLabelColumns = (metaRes.data.ItemLabels || []).map(c => c.Name);

            // Initiera val
            $scope.categoryDefColumns.forEach(c => $scope.selectedCategoryDef[c] = false);
            $scope.categoryLabelColumns.forEach(c => $scope.selectedCategoryLabel[c] = false);
            $scope.itemDefColumns.forEach(c => $scope.selectedItemDef[c] = false);
            $scope.itemLabelColumns.forEach(c => $scope.selectedItemLabel[c] = false);

            // Färginställningar
            (metaRes.data.CategoryDefinitions || []).forEach(c => $scope.categoryColors.catDef[c.Name] = c.Color || '#eee');
            (metaRes.data.CategoryLabels || []).forEach(c => $scope.categoryColors.catLabel[c.Name] = c.Color || '#eee');

            // Kolumnordning
            $scope.columnOrder.categoryDef = [...$scope.categoryDefColumns];
            $scope.columnOrder.categoryLabel = [...$scope.categoryLabelColumns];
            $scope.columnOrder.itemDef = [...$scope.itemDefColumns];
            $scope.columnOrder.itemLabel = [...$scope.itemLabelColumns];

            // Hämta rapportdata
            return $http.get('/api/budget/report/spreadsheet?includeItemDefinitions=true&includeItemLabels=true&includeCategoryDefinitions=true&includeCategoryLabels=true');
        }).then(function (res) {
            const sorted = res.data.sort((a, b) => (a.year || 0) - (b.year || 0) || (a.month || 0) - (b.month || 0));

            sorted.forEach(function (month) {
                ['itemDefinitions', 'itemLabels', 'categoryDefinitions', 'categoryLabels'].forEach(function (section) {
                    Object.keys(month[section] || {}).forEach(function (col) {
                        if (section === 'itemDefinitions' && !$scope.selectedItemDef.hasOwnProperty(col)) {
                            $scope.itemDefColumns.push(col);
                            $scope.selectedItemDef[col] = false;
                            $scope.columnOrder.itemDef.push(col);
                        }
                        if (section === 'itemLabels' && !$scope.selectedItemLabel.hasOwnProperty(col)) {
                            $scope.itemLabelColumns.push(col);
                            $scope.selectedItemLabel[col] = false;
                            $scope.columnOrder.itemLabel.push(col);
                        }
                        if (section === 'categoryDefinitions' && !$scope.selectedCategoryDef.hasOwnProperty(col)) {
                            $scope.categoryDefColumns.push(col);
                            $scope.selectedCategoryDef[col] = false;
                            $scope.columnOrder.categoryDef.push(col);
                        }
                        if (section === 'categoryLabels' && !$scope.selectedCategoryLabel.hasOwnProperty(col)) {
                            $scope.categoryLabelColumns.push(col);
                            $scope.selectedCategoryLabel[col] = false;
                            $scope.columnOrder.categoryLabel.push(col);
                        }
                    });
                });
            });

            // Bygg år och månader
            const yearsMap = {};
            sorted.forEach(function (m) {
                if (!yearsMap[m.year]) yearsMap[m.year] = [];
                yearsMap[m.year].push(m);
            });
            $scope.years = Object.keys(yearsMap).map(y => ({ year: parseInt(y), months: yearsMap[y] })).sort((a, b) => b.year - a.year);

            // ✅ Bygg månadsväljaren här
            $scope.allMonths = [];
            $scope.years.forEach(y => {
                y.months.forEach(m => {
                    $scope.allMonths.push({
                        id: `${m.year}-${(m.month < 10 ? '0' : '') + m.month}`,
                        year: m.year,
                        name: $scope.monthNames[m.month - 1]
                    });
                });
            });

        }).catch(function (err) {
            console.error('Fel vid API-anrop:', err);
        });


        $scope.getYearTotal = function (months, section, colName) {
            return months.reduce(function (sum, m) {
                if (section === 'income' || section === 'expense' || section === 'net') { return sum + (m[section] || 0); }
                return sum + ((m[section] && m[section][colName]) || 0);
            }, 0);
        };

        $scope.filterMonths = function (month) {
            const anySelected = Object.values($scope.selectedMonths).some(v => v);
            if (!anySelected) return true; // Visa alla om inget valt
            const monthId = month.year + '-' + (month.month < 10 ? '0' : '') + month.month;
            return !!$scope.selectedMonths[monthId];
        };
        $scope.$watch('splitByYear', function (newVal) {
            if (!newVal) {
                const allMonths = [];
                $scope.years.forEach(y => allMonths.push(...y.months));
                $scope.flatYears = [{ year: 'Allt', months: allMonths }];
            } else {
                $scope.flatYears = $scope.years;
            }
        });


    }]);
