@model List<Aberwyn.Controllers.AdminUserViewModel>
<link rel="stylesheet" href="~/css/admin.css" />

<h2 class="mb-3">Adminpanel</h2>

<div class="card mb-4">
    <div class="card-header">Roller och användare</div>
    <div class="card-body">
        <div class="row">
            <div>
                <h4>Skapa ny roll</h4>
                <form method="post" asp-action="CreateRole">
                    <div class="form-group">
                        <input type="text" name="roleName" class="form-control" placeholder="Namn på ny roll" required />
                    </div>
                    <button type="submit" class="btn btn-success mt-2">Skapa roll</button>
                </form>
            </div>

            <div>
                <h4>Skapa ny användare</h4>
                @if (TempData["Message"] != null)
                {
                    <div class="alert alert-success">@TempData["Message"]</div>
                }

                <form method="post" asp-action="CreateUser">
                    <div class="form-group">
                        <label for="email">E-post:</label>
                        <input type="email" name="email" class="form-control" required />
                    </div>
                    <div class="form-group">
                        <label for="password">Lösenord:</label>
                        <input type="password" name="password" class="form-control" required />
                    </div>
                    <button type="submit" class="btn btn-success mt-2">Skapa användare</button>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="card mb-4">
    <div class="card-header">Befintliga roller och användare</div>
    <div class="card-body">
        <h5>Alla roller</h5>
        <ul>
            @foreach (var role in ViewBag.AllRoles as List<string>)
            {
                <li>@role</li>
            }
        </ul>

        <table class="table">
            <thead>
                <tr>
                    <th>E-post</th>
                    <th>Roller</th>
                    <th>Lägg till roll</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var user in Model)
                {
                    <tr>
                        <td>@user.Email</td>
                        <td>
                            @foreach (var role in user.Roles)
                            {
                                <span>@role</span>
                                <form method="post" asp-action="RemoveFromRole" style="display:inline;">
                                    <input type="hidden" name="userId" value="@user.UserId" />
                                    <input type="hidden" name="role" value="@role" />
                                    <button type="submit" class="btn btn-sm btn-danger">Ta bort</button>
                                </form>
                            }
                        </td>
                        <td>
                            <form method="post" asp-action="AddToRole" class="form-inline">
                                <input type="hidden" name="userId" value="@user.UserId" />
                                <input type="text" name="role" class="form-control" placeholder="Rollnamn" />
                                <button type="submit" class="btn btn-sm btn-primary">Lägg till</button>
                            </form>
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
</div>

<div class="card mb-4">
    <div class="card-header">Övriga funktioner</div>
    <div class="card-body">
        <button class="btn btn-secondary mb-3" onclick="generateThumbnails()">🖼 Generera thumbnails</button>

        <h4>Testa Pushnotis</h4>
        <form onsubmit="sendPush(event)">
            <div class="form-group">
                <label for="title">Titel:</label>
                <input type="text" id="title" name="title" class="form-control" required />
            </div>
            <div class="form-group">
                <label for="body">Meddelande:</label>
                <input type="text" id="body" name="body" class="form-control" required />
            </div>
            <button type="submit" class="btn btn-warning mt-2">Skicka testnotis</button>
        </form>
        <hr />
        <h4>Skicka Pizza-notis</h4>
        <button class="btn btn-danger mt-2" onclick="sendPizzaPush()">🍕 Skicka pizzanotis</button>
        <div id="pizzaPushResult" class="mt-2"></div>
            </div>
        </div>

<div class="card mb-5">
    <div class="card-header">Importera från annan databas</div>
    <div class="card-body">
        <form id="customDbForm">
            <div class="form-group">
                <label>Server:</label>
                <input type="text" name="dbHost" class="form-control" required />
            </div>
            <div class="form-group">
                <label>Port:</label>
                <input type="number" name="dbPort" class="form-control" value="3306" required />
            </div>
            <div class="form-group">
                <label>Databas:</label>
                <input type="text" name="dbName" class="form-control" required />
            </div>
            <div class="form-group">
                <label>Användarnamn:</label>
                <input type="text" name="dbUser" class="form-control" required />
            </div>
            <div class="form-group">
                <label>Lösenord:</label>
                <input type="password" name="dbPassword" class="form-control" required />
            </div>
        </form>

        <button class="btn btn-info mt-3" onclick="testDbConnection()">🔌 Testa anslutning</button>
        <div id="testResult" class="mt-2"></div>
        <button class="btn btn-primary mt-3" onclick="submitTo('ImportMealsFromCustom')">🍽 Importera måltider</button>
        <button class="btn btn-primary mt-3" onclick="submitTo('ImportMenusFromCustom')">🗓 Importera menyer</button>
        <button class="btn btn-primary mt-3" onclick="submitTo('ImportBudgetFromCustom')">💰 Importera budget</button>
    </div>
</div>



<script>
    async function sendPizzaPush() {
  const resultDiv = document.getElementById("pizzaPushResult");
  resultDiv.innerText = "⏳ Skickar notis...";

  try {
    const response = await fetch("/api/push/notify-pizza", {
      method: "POST"
    });

    const text = await response.text();
    if (response.ok) {
      resultDiv.className = "text-success mt-2";
      resultDiv.innerText = "✅ " + text;
    } else {
      resultDiv.className = "text-danger mt-2";
      resultDiv.innerText = "❌ Fel: " + text;
    }
  } catch (err) {
    resultDiv.className = "text-danger mt-2";
    resultDiv.innerText = "❌ Ett tekniskt fel uppstod.";
    console.error(err);
  }
}

function generateThumbnails() {
    if (!confirm("Generera thumbnails för alla måltider som saknar?")) return;

    fetch("/admin/GenerateThumbnails", {
        method: "POST"
    })
    .then(res => res.text())
    .then(msg => {
        alert("✅ " + msg);
    })
    .catch(err => {
        console.error("Fel vid generering av thumbnails:", err);
        alert("❌ Ett fel uppstod vid generering av thumbnails.");
    });
}

function collectFormData() {
    const form = document.getElementById("customDbForm");
    return new FormData(form); // 🔁 Byt ut till ren FormData istället för URLSearchParams
}

function submitTo(action) {
    const data = collectFormData();

    fetch(`/admin/${action}`, {
        method: "POST",
        body: data
    })
    .then(async res => {
        const text = await res.text();
        if (res.ok) {
            alert(`✅ ${action} lyckades`);
        } else {
            alert(`❌ Fel vid ${action}:\n${text}`);
        }
    });
}

function testDbConnection() {
    const data = collectFormData();

    fetch(`/admin/TestDbConnection`, {
        method: "POST",
        body: data
    })
    .then(res => res.json())
    .then(data => {
        const div = document.getElementById("testResult");
        div.innerText = data.message;
        div.className = data.success ? "text-success mt-2" : "text-danger mt-2";
    })
    .catch(err => {
        document.getElementById("testResult").innerText = "❌ Ett tekniskt fel uppstod.";
        console.error(err);
    });
}

  async function sendPush(event) {
    event.preventDefault(); // 🚫 stoppa formuläret från att göra vanlig POST

    const title = document.getElementById("title").value;
    const body = document.getElementById("body").value;

    const response = await fetch("/api/push/notify-all", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ title, body })
    });

    if (response.ok) {
      alert("✅ Pushnotis skickad!");
    } else {
      alert("❌ Något gick fel.");
    }
  }
</script>
