@model Aberwyn.Models.BudgetModel

@{
    Layout = "_Layout"; // Assuming you have a layout file named _Layout.cshtml
}

<!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/site.css">
</head>
<body ng-controller="BudgetController">

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

        <form ng-submit="filterBudget()">
            <label for="month">Month:</label>
            <select id="month" ng-model="selectedMonth">
                <option ng-repeat="month in months" value="{{ month }}">{{ month }}</option>
            </select>

            <label for="year">Year:</label>
            <select id="year" ng-model="selectedYear">
                <option ng-repeat="year in years" value="{{ year }}">{{ year }}</option>
            </select>

            <button type="submit">Filter</button>
        </form>

        <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> <!-- Total moved to the header -->
                </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> <!-- Button for adding items -->
            </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 budgetItems 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));
                };

                $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);
                };

                $scope.loadCategories();
                $scope.filterBudget();
            });
    </script>

</body>
</html>
