@model MedicalStateModel

@{
    ViewData["Title"] = "Medical State Details ";


    var a = 0;

}

<section id="toast-container" class="page-section" style="background-color: #f4f5f7;">
    <div class="container py-5 h-100">
        <div class="row d-flex justify-content-center align-items-center h-100">
            <div class="col col-10 col-lg-10 mb-4 mb-lg-0">
                <div class="card mb-3" style="border-radius: .5rem;">
                    <div class="row g-0">
                        <div class="col-10 gradient-custom text-center text-black"
                             style="border-top-left-radius: .5rem; border-bottom-left-radius: .5rem;">
                            <div class="icon-box">
                                <div class="icon " style="color: #5e54b3"><i class="fas fa-heartbeat  fa-8x "></i></div>
                            </div>
                            <h5>@Model.StateName</h5>
                            <p>AT: @(Model.PrescriptionTime )</p>
                            <a asp-action="Edit" asp-controller="MedicalState" asp-route-id="@Model.Id">
                                <i class="far fa-edit mb-5"></i>
                            </a>

                            <a asp-action="Index">

                                <i class="far fa-backward">

                                </i>
                                Go Back
                            </a>
                        </div>
                        <div class="col-10">
                            <div class="card-body p-4">
                                <h6> Information:</h6>
                                <hr class="mt-0 mb-4">
                                <div class="row pt-1">
                                    <div class="col-6 mb-3">
                                        <h6>Description</h6>
                                        <p class="text">@Model.StateDescription</p>
                                    </div>
                                    <div class="col-4 mb-3">
                                        <h6>Medicines Count:@Model.Medicines.Count()</h6>

                                        <a class="btn btn-primary m-1" asp-controller="MedicalState" asp-action="Edit" asp-route-id="@Model.Id">Edit</a>
                                        <a class="btn btn-danger m-1" asp-controller="MedicalState" asp-action="Delete" asp-route-id="@Model.Id">Delete</a>
                                        <button class="btn btn-danger" ondblclick='DeleteConfirm("Delete Confirm", "Are you sure you want to delete @Model.StateName From your medical Cases", "Reomve",@Model.Id)'>Delete Confirm</button>

                                    </div>
                                </div>
                                <h6>Medicines : </h6>
                                <hr class="mt-0 mb-4">
                                <div class="row pt-1">
                                    <table id="Ingredients_" class="table table-bordered">
                                        <thead>
                                            <tr>
                                                <td>#</td>
                                                <td>Name</td>
                                                <td>Description</td>
                                                <td>Price</td>
                                                <td>dosage</td>
                                                <td>Manfacture Name</td>
                                                <td>Manage</td>


                                            </tr>
                                        </thead>
                                        <tbody id="cc">
                                            @foreach (var ing in Model.Medicines)
                                            {
                                                <tr class=" mb-3">
                                                    <td>@(a+=1)</td>
                                                    <td>@ing.TradeName</td>
                                                    <td>@ing.Description</td>
                                                    <td>@ing.Price</td>
                                                    <td>@ing.Dosage</td>
                                                    <td>@ing.ManufactureName</td>
                                                    <td>
                                                        <button class="btn btn-danger" ondblclick='DeleteConfirm("Delete Confirm", "Are you sure you want to delete @ing.TradeName From this medical Case" , "ReomveMedicine" ,@ing.Id)'>Delete</button>
                                                        <button class="btn btn-primary" onclick="DetailMedicine( @ing.Id)">Details</button>

                                                    </td>
                                                </tr>
                                            }
                                        </tbody>
                                    </table>
                                </div>
                                <div class="row pt-1">
                                    <div class="col-6 mb-3">
                                        <h6>Go To list </h6>
                                        <a asp-action="Index">GO Back </a>

                                    </div>
                                </div>
                                <hr />
                                <div class="row pt-1">

                                    <button onclick="fetchMedicines()" class="btn btn-primary">Get All Medicine </button>

                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<section style="background-color: #f4f5f7;">
    <div class="container  h-100">
        <div class="row d-flex justify-content-center align-items-center h-100">
            <div class="col">
                <div class="row g-0">

                    <div class="row d-flex justify-content-center align-items-center h-100">

                        <div id="medicines-table">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>
<div class="modal fade" id="item" tabindex="-1" aria-labelledby="label-" role="dialog"
     aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header border-bottom-0">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">
                        <i class="fas fa-times"></i>
                    </span>
                </button>
            </div>
            <div class="modal-body text-start p-3">
                <h5 class="modal-title text-uppercase mb-5" id="exampleModalLabel">title</h5>

                <p class=" mb-5"> message</p>

                <hr class="mt-2 mb-4"
                    style="height: 0; background-color: transparent; opacity: .75; border-top: 2px dashed #9e9e9e;">
                <div class="modal-footer d-flex justify-content-center border-top-0 py-4">

                    <button class="btn btn-info"  data-dismiss="modal" aria-label="Close">Close</button>
                </div>
            </div>
        </div>
    </div>
    </div>
    @section Scripts {
        <script>
        async function fetchMedicines() {
            try {
                debugger
                let response = await fetch('/MedicalState/GetMedicines'); // Adjust the endpoint as needed
                if (response.ok) {
                    let medicines = await response.json();
                    populateTable(medicines, 'medicines-table');
                } else {
                    console.error('Error:', response.statusText);
                }
            } catch (error) {
                console.error('Fetch error:', error);
            }
        }
        async function updateMedicines() {
               let id =@Model.Id

            try {
                debugger
                let response = await fetch(`/MedicalState/GetMedicalStateMedicine/?id=${id}`); // Adjust the endpoint as needed
                if (response.ok) {
                    let medicines = await response.json();
                    populateTable(medicines, 'Ingredients_');
                } else {
                    console.error('Error:', response.statusText);
                }
            } catch (error) {
                console.error('Fetch error:', error);
            }
        }
        function populateTable(medicines,tableName) {


            let tableBody = document.querySelector('#' + tableName);
            tableBody.innerHTML = `
            <table class="table">
               <thead>
          <tr class="mb-3">
            <td>ID</td>
            <td>tradeName</td>
            <td>description</td>
            <td>price</td>
            <td>dosage</td>
            <td>Manufacture Name </td>
            <td>
            Manage
            </td>
              </tr>

            </thead ><tbody id="b"> </tbody></table>`;

            tableBody = document.querySelector('#b');

            medicines.forEach(medicine => {
                let row = document.createElement('tr');
                row.classList = "mb-3"

                row.innerHTML = `
                    <td>${medicine.id}</td>
                    <td>${medicine.tradeName}</td>
                    <td>${medicine.description}</td>
                    <td>${medicine.price}</td>
                    <td>${medicine.dosage}</td>

                    <td>${medicine.manufactureName}</td>
                    `;
                row.innerHTML +=
                    (tableName == "Ingredients_") ?

                        `
                <td>

                    <button class="btn btn-danger" ondblclick="ReomveMedicine(${medicine.id})">Delete</button>
                    <button class="btn btn-primary" onclick="DetailMedicine( ${medicine.id})">Details</button>

                    </td>
                ` :
                        `<td>
                        <button class="btn btn-primary" onclick="addMedicine( ${medicine.id})">Add</button>
                        <button class="btn btn-primary" onclick="DetailMedicine( ${medicine.id})">Details</button>

                    </td>
                `

                tableBody.appendChild(row);
            });
        }
        async function addMedicine(med) {
            let id =@Model.Id;
            try {
               showToast('Loading ... ', 'Adding medicine');

                let response = await fetch(`/MedicalState/AddMedicine`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ MedicalStateId: id, MedicineId: med }) // Adjust the body as needed
                });

                if (response.ok) {
                    let result = await response.json();
                    updateMedicines();
                    showToast('Medicine added successfully', 'Success');
                } else {
                    console.error('Error:', response.statusText);
                    showToast('Failed to add medicine', 'Error');
                }
            } catch (error) {
                console.error('Fetch error:', error);
                showToast('Failed to add medicine', 'Error');
            }
        }
        async function DetailMedicine(med) {
            let id =@Model.Id
            try {
                debugger
                let response = await fetch(`/MedicalState/GetDetails/${med}`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                 });

                if (response.ok) {
                    let result = await response.json();
                    console.log(result)
                    showModal('Medicine Details',result );
                } else {
                    console.error('Error:', response.statusText);
                    showToast('Failed to add medicine', 'Error');
                }
            } catch (error) {
                console.error('Fetch error:', error);
                showToast('Failed to add medicine', 'Error');
            }
        }
        async function ReomveMedicine(med) {
            let id =@Model.Id
            debugger
            try {
        //        showToast('Loading ... ', 'Removing medicine');

                let response = await fetch(`/MedicalState/RemoveMedicine`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ MedicalStateId: id, MedicineId: med }) // Adjust the body as needed
                });

                if (response.ok) {
                    let result = await response.json();

                    updateMedicines();

                    showToast('Medicine Reomved successfully', 'Success');
                } else {
                    console.error('Error:', response.statusText);
                    showToast('Failed to remove medicine', 'Error');
                }
            } catch (error) {
                console.error('Fetch error:', error);
                showToast('Failed to remove medicine', 'Error');
            }
        }
        async function Reomve(med) {
            debugger
            try {
        //        showToast('Loading ... ', 'Removing medicine');

                let response = await fetch(`/MedicalState/Delete/${med}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });

                if (response.ok) {
                   // let result = await response.json();

                    document.location.href="/MedicalState/"
                    showToast('Medicine Reomved successfully', 'Success');
                } else {
                    console.error('Error:', response.statusText);
                    showToast('Failed to remove medicine', 'Error');
                }
            } catch (error) {
                console.error('Fetch error:', error);
                showToast('Failed to remove medicine', 'Error');
            }
        }
        async function DeleteConfirm(title, message, action,param) {
            debugger
            const modalBody = document.querySelector('#mod');
            modalBody.innerHTML = `
                   <div class="modal fade" id="item" tabindex="-1" aria-labelledby="label-" role="dialog"
             aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header border-bottom-0">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">
                                <i class="fas fa-times"></i>
                            </span>
                        </button>
                    </div>
                    <div class="modal-body text-start p-3">
                        <h5 class="modal-title text-uppercase mb-5" id="exampleModalLabel">${title}</h5>

                        <p class=" mb-5"> ${message}</p>

                        <hr class="mt-2 mb-4"
                            style="height: 0; background-color: transparent; opacity: .75; border-top: 2px dashed #9e9e9e;">
                    <div class="modal-footer d-flex justify-content-center border-top-0 py-4">

                        <button class="btn btn-danger" onclick="${action}(${param})">Delete</button>

                        <button class="btn btn-info" class="close" data-dismiss="modal" aria-label="Close">Close</button>
                    </div>
                </div>
            </div>
        </div>  `;
            // Show the modal
            const medicineModal = new bootstrap.Modal(document.getElementById('item'));
            medicineModal.show();

        }
            function showToast(message, title) {
                const Modal = new bootstrap.Modal(document.getElementById('item'));
            //    Modal.close();
            if (Modal) Modal.hide();  
       //     Modal.toggle();
            //Modal.dispose();
            const modalBody = document.querySelector('#item');
            modalBody.innerHTML = `
                   <div class="modal fade" id="item" tabindex="-1" aria-labelledby="label-" role="dialog"
             aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header border-bottom-0">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">
                                <i class="fas fa-times"></i>
                            </span>
                        </button>
                    </div>
                    <div class="modal-body text-start p-3">
                        <h5 class="modal-title text-uppercase mb-5" id="exampleModalLabel">${title}</h5>

                        <p class=" mb-5"> ${message}</p>

                        <hr class="mt-2 mb-4"
                            style="height: 0; background-color: transparent; opacity: .75; border-top: 2px dashed #9e9e9e;">
                    <div class="modal-footer d-flex justify-content-center border-top-0 py-4">

                        <button class="btn btn-info" class="close" data-dismiss="modal" aria-label="Close">Close</button>
                    </div>
                </div>
            </div>
        </div>  `;
            // Show the modal
            const medicineModal = new bootstrap.Modal(document.getElementById('item'));
            medicineModal.show();


        }
        function showModal(message, result) {
            debugger
            const Modal = new bootstrap.Modal(document.getElementById('item'));
            //    Modal.close();
            try { Modal.hide(); } catch { }

            let m = result["manufactureName"]
            console.log(m)
            var s = result.medicineIngredients
            console.log(s)
            var r = ""
            var t = 0;
            for (i in s) {
                console.log(i)
                r+=`
                            <div class="d-flex justify-content-between">
                                <p class="fw-bold mb-0">${t++}</p>

                                <p class="fw-bold mb-0">${s[i].ingredient.name}</p>

                                <p class="text-muted mb-0">${s[i].ratio}</p>
                            </div>
            `}
            const modalBody = document.querySelector('#item');
            modalBody.innerHTML = `
                   <div class="modal fade" id="item" tabindex="-1" aria-labelledby="label-" role="dialog"
             aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header border-bottom-0">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">
                                <i class="fas fa-times"></i>
                            </span>
                        </button>
                    </div>
                    <div class="modal-body text-start p-3">
                        <h5 class="modal-title text-uppercase mb-5" id="exampleModalLabel">${result.tradeName}</h5>
                        <p class=" mb-5"> Manufacuture : ${m}</p>

                        <p class=" mb-5"> Side Effect : ${result.sideEffect}</p>

                        <p class="mb-0">Ingredients Summary</p>

                        <hr class="mt-2 mb-4"
                            style="height: 0; background-color: transparent; opacity: .75; border-top: 2px dashed #9e9e9e;">
                        <div class="d-flex justify-content-between">
                            <p class="fw-bold mb-0">#</p>

                            <p class="fw-bold mb-0">Ingredient Name</p>

                            <p class="text-muted mb-0">Ratio</p>
                        </div>
                            ${r}
                        <hr class="mt-2 mb-4"
                            style="height: 0; background-color: transparent; opacity: .75; border-top: 2px dashed #9e9e9e;">
                        <div class="d-flex justify-content-between">
                            <p class="fw-bold">Price</p>

                            <p class="fw-bold">$${result.price}</p>
                        </div>

                    </div>
                    <div class="modal-footer d-flex justify-content-center border-top-0 py-4">

                        <button class="btn btn-info" class="close" data-dismiss="modal" aria-label="Close">Close</button>
                    </div>
                </div>
            </div>
        </div>  `;
            // Show the modal
            const medicineModal = new bootstrap.Modal(document.getElementById('item'));
            medicineModal.show();

        }
        </script>

    }
