@page
@model InvoiceModel
@{
    ViewData["Title"] = "消費者發票資訊填寫";
    Layout = "_SimpleLayout";
}

<div class="container mt-4">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="alert alert-secondary text-center mb-3" role="alert">
                <h5 class="mb-0">營業人：@Model.CompanyName（統編：@Model.CompanyTaxId）</h5>
            </div>
            @* @if (!string.IsNullOrEmpty(Model.DisplayTransDateTime) || !string.IsNullOrEmpty(Model.DisplayTransAmount)) *@
            @* { *@
            <div class="card mb-3 border-info">
                <div class="card-body bg-light">
                    <div class="row">
                        <div class="col-md-6">
                            <label class="form-label fw-bold">發票日期：</label>
                            <span class="ms-2">@Model.DisplayTransDateTime</span>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold">發票金額：</label>
                            <span class="ms-2">NT$ @Model.DisplayTransAmount</span>
                        </div>
                    </div>
                </div>
            </div>
            @* } *@

            <div class="card shadow-sm">
                <div class="card-header bg-primary text-white">
                    <h4 class="mb-0">消費者發票資訊填寫</h4>
                </div>
                <div class="card-body">
                    <div id="formErrorMessage" class="alert alert-danger alert-dismissible fade show @(string.IsNullOrEmpty(Model.ErrorMessage) ? "d-none" : string.Empty)" role="alert">
                        <span id="formErrorMessageText">@Model.ErrorMessage</span>
                        <button type="button" class="btn-close" aria-label="Close" data-error-close></button>
                    </div>

                    <div id="formSuccessMessage" class="alert alert-success alert-dismissible fade show @(string.IsNullOrEmpty(Model.SuccessMessage) ? "d-none" : string.Empty)" role="alert">
                        <span id="formSuccessMessageText">@Model.SuccessMessage</span>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>

                    <form method="post" asp-page-handler="ToEndPoint">
                        <div asp-validation-summary="All" class="text-danger mb-3"></div>

                        <!-- 隱藏欄位：系統傳入的資料 -->
                        <input type="hidden" asp-for="InvoiceData.Identifier" />
                        <input type="hidden" asp-for="InvoiceData.TransDateTime" />
                        <input type="hidden" asp-for="InvoiceData.TransAmount" />
                        <input type="hidden" asp-for="InvoiceData.DeviceID" />
                        <input type="hidden" asp-for="InvoiceData.LocationID" />
                        <input type="hidden" asp-for="InvoiceData.CarPlateNum" />
                        <input type="hidden" asp-for="InvoiceData.OrderID" />
                        <input type="hidden" asp-for="InvoiceData.TaxType" />

                        <div class="alert alert-info mb-4">
                            <strong>注意：</strong>以下四個選項至少需填寫一個
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label asp-for="InvoiceData.Email" class="form-label">消費者信箱(寄送發票開立通知用)</label>
                                <input asp-for="InvoiceData.Email" class="form-control" type="email" maxlength="64" placeholder="example@email.com" />
                                <span asp-validation-for="InvoiceData.Email" class="text-danger"></span>
                            </div>
                            <div class="col-md-6">
                                <label asp-for="InvoiceData.CarrierID" class="form-label">手機條碼</label>
                                <input asp-for="InvoiceData.CarrierID" class="form-control" maxlength="8" placeholder="/ABC1234" />
                                <small class="form-text text-muted">8碼，第1碼為/，例：/ABC1234</small>
                                <span asp-validation-for="InvoiceData.CarrierID" class="text-danger"></span>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label asp-for="InvoiceData.BuyerIdentifier" class="form-label">購買者統編</label>
                                <input asp-for="InvoiceData.BuyerIdentifier" class="form-control" maxlength="8" placeholder="12345678" />
                                <small class="form-text text-muted">8位數字</small>
                                <span asp-validation-for="InvoiceData.BuyerIdentifier" class="text-danger"></span>
                            </div>
                            <div class="col-md-6">
                                <label asp-for="InvoiceData.LoveCode" class="form-label">捐贈碼</label>
                                <input asp-for="InvoiceData.LoveCode" class="form-control" maxlength="7" placeholder="123456" />
                                <small class="form-text text-muted">輸入為捐贈發票</small>
                                <span asp-validation-for="InvoiceData.LoveCode" class="text-danger"></span>
                            </div>
                        </div>

                        <div id="submitButtonContainer" class="d-grid gap-2 mt-4 @(string.IsNullOrEmpty(Model.SuccessMessage) ? string.Empty : "d-none")">
                            <button type="submit" class="btn btn-primary btn-lg">送出</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<div id="formSubmittingOverlay" class="position-fixed top-0 start-0 w-100 h-100 bg-white bg-opacity-75 d-none" style="z-index: 1050;">
    <div class="d-flex justify-content-center align-items-center h-100">
        <div class="text-center">
            <div class="spinner-border text-primary mb-3" role="status" aria-hidden="true"></div>
            <p class="fw-semibold mb-0">資料送出中，請稍候...</p>
        </div>
    </div>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const errorAlert = document.getElementById('formErrorMessage');
            const errorText = document.getElementById('formErrorMessageText');
            const errorCloseBtn = errorAlert?.querySelector('[data-error-close]');
            const successAlert = document.getElementById('formSuccessMessage');
            const submitButtonContainer = document.getElementById('submitButtonContainer');

            const showError = (message) => {
                if (!errorAlert || !errorText) {
                    alert(message);
                    return;
                }
                errorText.textContent = message;
                errorAlert.classList.remove('d-none');
            };

            const hideError = () => {
                if (!errorAlert || !errorText) {
                    return;
                }
                errorText.textContent = '';
                errorAlert.classList.add('d-none');
            };

            errorCloseBtn?.addEventListener('click', hideError);

            const requiredGroup = [
                document.querySelector('input[name="InvoiceData.Email"]'),
                document.querySelector('input[name="InvoiceData.CarrierID"]'),
                document.querySelector('input[name="InvoiceData.BuyerIdentifier"]'),
                document.querySelector('input[name="InvoiceData.LoveCode"]')
            ];

            const form = document.querySelector('form[method="post"]');
            if (!form) {
                return;
            }

            const overlay = document.getElementById('formSubmittingOverlay');
            const submitButtons = form.querySelectorAll('button[type="submit"], input[type="submit"]');
            let isSubmitting = false;

            const hideSubmitButtonAfterSuccess = () => {
                if (successAlert && !successAlert.classList.contains('d-none')) {
                    submitButtonContainer?.classList.add('d-none');
                    submitButtons.forEach(btn => btn.disabled = true);
                }
            };

            hideSubmitButtonAfterSuccess();

            const lockForm = () => {
                if (overlay) {
                    overlay.classList.remove('d-none');
                }
                submitButtons?.forEach(btn => btn.disabled = true);
                isSubmitting = true;
            };

            form.addEventListener('submit', function(event) {
                if (isSubmitting) {
                    event.preventDefault();
                    return;
                }

                const hasValue = requiredGroup.some(field => field && field.value.trim() !== '');
                if (!hasValue) {
                    event.preventDefault();
                    showError('Email、手機條碼、購買者統編、捐贈碼至少需填寫一項。');
                    return;
                }

                hideError();
                lockForm();
            });
        });
    </script>
}
