@using Newtonsoft.Json
@model PizzaAdminViewModel
@{
    ViewData["Title"] = "Pizza Admin";
    var availablePizzas = Model.AvailablePizzas as List<Meal> ?? new List<Meal>();
    var restaurantOpen = ViewBag.RestaurantIsOpen as bool? ?? false;
}

<link rel="stylesheet" href="~/css/pizza-admin.css" />

<div class="admin-grid">
    <!-- Vänster: Beställningar (allt i partial) -->
    <div class="main-orders">
        @await Html.PartialAsync("_PizzaAdminPartial", Model)
    </div>

    <!-- Höger: Restaurangstatus + Tillgängliga pizzor -->
    <div class="available-pizzas">
        <h2>Restaurangstatus</h2>
        <form id="restaurantStatusForm">
            <label class="form-check form-switch">
                <input class="form-check-input" type="checkbox" id="isOpenSwitch" name="isOpen" @(restaurantOpen ? "checked" : "") />
                <span class="ms-2" id="statusLabel">@(restaurantOpen ? "Restaurangen är öppen" : "Restaurangen är stängd")</span>
            </label>
        </form>

        <h3 class="mt-4">Tillgängliga pizzor</h3>
        <form method="post" asp-action="UpdatePizzaAvailability">
            <ul class="list-group mb-4">
                @foreach (var pizza in Model.AvailablePizzas)
                {
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        @pizza.Name
                        <label class="form-check form-switch m-0">
                            <input class="form-check-input" type="checkbox" name="availableIds" value="@pizza.Id" @(pizza.IsAvailable ? "checked" : "") />
                        </label>
                    </li>
                }
            </ul>
            <button type="submit" class="btn btn-outline-primary">Spara tillgänglighet</button>
        </form>
    </div>
</div>

@section Scripts {
<script>
    const switchInput = document.getElementById("isOpenSwitch");
    const label = document.getElementById("statusLabel");

    switchInput.addEventListener("change", function () {
        const isOpen = this.checked;

        fetch("/FoodMenu/ToggleRestaurant", {
            method: "POST",
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
            body: `isOpen=${isOpen}`
        }).then(() => {
            label.textContent = isOpen ? "Restaurangen är öppen" : "Restaurangen är stängd";
        });
    });

    setInterval(() => {
        fetch("/FoodMenu/PizzaAdminPartial")
            .then(r => r.text())
            .then(html => {
                const dom = new DOMParser().parseFromString(html, 'text/html');
                const newContent = dom.getElementById("ordersContainer").innerHTML;
                document.getElementById("ordersContainer").innerHTML = newContent;
            });
    }, 8000);
</script>
}
