@model Francesco.Recipes.World.Models.BackendModels.Recipe.Recipe

@{
	ViewData["Title"] = "Add Instructions";
}

<h1>Add Instructions to @Model.Name</h1>

<div class="instructions-list">
	<h3>Existing Instructions</h3>
	<ul>
		@foreach (var instruction in Model.Instructions.OrderBy(i => i.Number))
		{
			<li>@instruction.Number. @instruction.Description</li>
		}
	</ul>
</div>

<div class="add-instruction-form">
	<h3>Add New Instruction</h3>
	<form id="instruction-form" method="post" asp-action="AddInstruction" asp-controller="Recipe">
		<input type="hidden" name="recipeId" value="@Model.Id" />
		<div class="form-group">
			<label for="description">Description</label>
			<input type="text" class="form-control" id="description" name="description" required />
		</div>
		<button type="button" class="btn btn-primary" onclick="addInstructionToRecipe()">Add Instruction</button>
	</form>

</div>

@section Scripts {
	<script>
	async function addInstructionToRecipe() {
    event.preventDefault();

    var form = document.getElementById('instruction-form');
    var recipeId = form.querySelector('input[name="recipeId"]').value;
    var description = form.querySelector('input[name="description"]').value;
    var token = form.querySelector('input[name="__RequestVerificationToken"]').value;

			var response = await fetch('/' + recipeId + '/AddInstruction', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'RequestVerificationToken': token
        },
        body: `recipeId=${encodeURIComponent(recipeId)}&description=${encodeURIComponent(description)}`
    });

    if (response.ok) {
        location.reload();
    } else {
        alert('Failed to add instruction.');
    }
}

	</script>

}

