angular.module('mealMenuApp', ['ngSanitize'])
    .controller('MealMenuController', function ($scope, $http, $sce) {
        console.log("Controller initierad");

        $scope.viewMode = 'list';
        $scope.tooltip = {};
        $scope.meals = [];
        $scope.menu = {};
        const today = new Date();
        $scope.selectedWeek = getWeek(today);
        $scope.selectedYear = today.getFullYear();
        $scope.daysOfWeek = ["Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag", "Söndag"];

        $scope.loadMeals = function () {
            console.log("Hämtar måltider...");
            return $http.get('/api/mealMenuApi/getMeals')
                .then(res => {
                    console.log("Måltider hämtade:", res.data);
                    $scope.meals = res.data;
                    return res;
                })
                .catch(err => console.error("Fel vid hämtning av måltider:", err));
        };

        $scope.loadMenu = function () {
            console.log("Hämtar meny för vecka:", $scope.selectedWeek, $scope.selectedYear);
            $http.get('/api/mealMenuApi/menu', {
                params: { weekNumber: $scope.selectedWeek, year: $scope.selectedYear }
            }).then(res => {
                console.log("Menyposter hämtade:", res.data);
                $scope.menu = {};

                res.data.forEach(item => {
                    const dayIndex = item.DayOfWeek - 1;
                    if (dayIndex < 0 || dayIndex >= $scope.daysOfWeek.length) {
                        console.warn("Ogiltig dag:", item.DayOfWeek);
                        return;
                    }

                    const day = $scope.daysOfWeek[dayIndex];
                    $scope.menu[day] = {};

                    ['breakfast', 'lunch', 'dinner'].forEach(type => {
                        // Konvertera till PascalCase
                        const capitalType = type.charAt(0).toUpperCase() + type.slice(1);
                        const idKey = capitalType + 'MealId';
                        const nameKey = capitalType + 'MealName';

                        if (item[idKey]) {
                            const m = $scope.meals.find(x => x.Id === item[idKey]);
                            console.log(`Match för ${type} (${day}):`, m);

                            $scope.menu[day][type + 'MealId'] = item[idKey];
                            $scope.menu[day][type + 'MealName'] = m?.Name || item[nameKey] || 'Okänd rätt';

                            if (m?.ImageUrl) {
                                $scope.menu[day].imageUrl = m.ImageUrl;
                            }
                        }
                    });
                });

                console.log("Byggd meny:", $scope.menu);
            }).catch(err => console.error("Fel vid hämtning av veckomeny:", err));
        };

        $scope.openMeal = function (mealId) {
            if (!mealId) return;
            window.open('/Meal/View/' + mealId, '_blank');
        };

        $scope.getDayImage = function (day) {
            const item = $scope.menu[day];
            return (item && item.imageUrl) || '/images/default-meal.jpg';
        };

        $scope.getMealIdByDay = function (day) {
            const item = $scope.menu[day] || {};
            return item.dinnerMealId || item.lunchMealId || item.breakfastMealId || null;
        };

        $scope.goToPreviousWeek = function () {
            if ($scope.selectedWeek === 1) {
                $scope.selectedYear--;
                $scope.selectedWeek = 52;
            } else {
                $scope.selectedWeek--;
            }
            $scope.loadMenu();
        };

        $scope.goToNextWeek = function () {
            if ($scope.selectedWeek === 52) {
                $scope.selectedYear++;
                $scope.selectedWeek = 1;
            } else {
                $scope.selectedWeek++;
            }
            $scope.loadMenu();
        };

        function getWeek(d) {
            d = new Date(d.getFullYear(), d.getMonth(), d.getDate());
            const dayNum = d.getDay() || 7;
            d.setDate(d.getDate() + 4 - dayNum);
            const yearStart = new Date(d.getFullYear(), 0, 1);
            return Math.ceil((((d - yearStart) / 86400000) + 1) / 7);
        }

        console.log("Initierar måltidsladdning...");
        $scope.loadMeals().then(() => {
            console.log("Laddar meny efter måltider...");
            $scope.loadMenu();
        });
    });
