@model Aberwyn.Models.BudgetModel

@{
    Layout = "_Layout";
}

<!DOCTYPE html>
<html lang="en" ng-app="budgetApp">
<head>
    <meta charset="utf-8">
    <title>Budget Overview</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
    
    <link rel="stylesheet" type="text/css" href="~/css/budget.css">
</head>
<body ng-controller="BudgetController">

    <div class="budget-page">
        <h1>Budget Overview</h1>

        <div class="date-picker" ng-click="toggleDatePicker($event)">
            <button type="button" class="date-picker-toggle">
                {{ selectedMonthName() }} {{ selectedYear }}
            </button>
            <div class="date-picker-dropdown" ng-show="isDatePickerVisible">
                <select ng-model="selectedMonth" ng-options="month as monthName for (month, monthName) in monthOptions" ng-change="updateMonthYear()"></select>
                <select ng-model="selectedYear" ng-options="year for year in years" ng-change="updateMonthYear()"></select>
            </div>
        </div>

        <div class="budget-container">
            <div ng-repeat="category in categories" class="category-block">
                <div class="category-header">
                    {{ category }}
                    <span class="total">Total: {{ sumForCategory(category) }}</span>
                </div>

                <div class="items-wrapper">
                    <div ng-repeat="item in getItemsByCategory(category)" class="item">
                        <div class="item-name">
                            <input type="text" ng-model="item.name" ng-blur="updateItem(item)" placeholder="Name" />
                        </div>
                        <div class="item-amount">
                            <input type="number" ng-model="item.amount" ng-blur="updateItem(item)" placeholder="Amount" />
                        </div>
                    </div>
                </div>

                <div class="add-item" ng-click="addNewItem(category)">+</div>
            </div>
        </div>
    </div>

    <script>
        angular.module('budgetApp', [])
            .controller('BudgetController', function ($scope, $http) {
                const today = new Date();

                // Initialize months and years
                $scope.months = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'];
                $scope.years = [...Array(11).keys()].map(i => today.getFullYear() - 10 + i);
                $scope.selectedMonth = (today.getMonth() + 1).toString();
                $scope.selectedYear = today.getFullYear();
                $scope.categories = [];
                $scope.budgetItems = @Html.Raw(Json.Serialize(Model.BudgetItems)); // Initialize with server-side data

                $scope.loadCategories = function () {
                    $http.get('/api/budgetapi/categories').then(response => {
                        $scope.categories = response.data;
                    }).catch(error => console.error("Error fetching categories:", error));
                };

                // Automatically filter when month or year changes
                $scope.filterBudget = function () {
                    $http.get('/api/budgetapi/items', {
                        params: { month: $scope.selectedMonth, year: $scope.selectedYear }
                    }).then(response => {
                        $scope.budgetItems = response.data;
                    }).catch(error => console.error("Error fetching budget items:", error));
                };

                $scope.getItemsByCategory = function (category) {
                    return $scope.budgetItems.filter(item => item.category === category);
                };

                $scope.sumForCategory = function (category) {
                    return $scope.budgetItems
                        .filter(item => item.category === category)
                        .reduce((total, item) => total + item.amount, 0);
                };

                $scope.updateItem = function (item) {
                    $http.put('/api/budgetapi/items', item)
                        .then(response => console.log("Item updated:", response.data))
                        .catch(error => console.error("Error updating item:", error));
                };

                $scope.addNewItem = function (category) {
                    const newItem = {
                        name: '',
                        amount: 0,
                        category: category,
                        month: $scope.selectedMonth,
                        year: $scope.selectedYear
                    };
                    $scope.budgetItems.push(newItem);
                };

                // Dropdown toggle functions
                $scope.isMonthDropdownVisible = false;
                $scope.isYearDropdownVisible = false;

                $scope.toggleMonthDropdown = function () {
                    $scope.isMonthDropdownVisible = !$scope.isMonthDropdownVisible;
                    $scope.isYearDropdownVisible = false;
                };

                $scope.toggleYearDropdown = function () {
                    $scope.isYearDropdownVisible = !$scope.isYearDropdownVisible;
                    $scope.isMonthDropdownVisible = false;
                };

                $scope.selectMonth = function (month) {
                    $scope.selectedMonth = $scope.months.indexOf(month) + 1;
                    $scope.isMonthDropdownVisible = false;
                    $scope.filterBudget(); // Automatically filter after month selection
                };

                $scope.selectYear = function (year) {
                    $scope.selectedYear = year;
                    $scope.isYearDropdownVisible = false;
                    $scope.filterBudget(); // Automatically filter after year selection
                };

                $scope.selectedMonthName = function () {
                    return $scope.months[$scope.selectedMonth - 1];
                };

                // Initial load
                $scope.loadCategories();
                $scope.filterBudget();

            // Month and year options as before
            $scope.monthOptions = {
                1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June",
                7: "July", 8: "August", 9: "September", 10: "October", 11: "November", 12: "December"
            };

            // Toggle display of date picker
            $scope.toggleDatePicker = function ($event) {
                $event.stopPropagation(); // Prevents the click from closing the dropdown
                $scope.isDatePickerVisible = !$scope.isDatePickerVisible;
            };

            // Update selection and close dropdown
            $scope.updateMonthYear = function () {
                $scope.isDatePickerVisible = false; // Close after selection
                $scope.filterBudget(); // Trigger filtering immediately
            };

            // Close the date picker when clicking outside
            document.addEventListener('click', function () {
                $scope.$apply(() => $scope.isDatePickerVisible = false);
            }); 
            })
    </script>

</body>
</html>
