<style>
.login_wrapper {
    right: 0;
    margin: 0 auto;
    margin-top: 5%;
    max-width: 350px;
    position: relative;
}

.login_content h1 {
    font: normal 25px Helvetica, Arial, sans-serif;
    letter-spacing: -.05em;
    line-height: 20px;
    margin: 10px 0 30px;
}

.login_form {
    z-index: 22;
}

.registration_form,
.password_form,
.login_form {
    position: absolute;
    top: 0;
    width: 100%;
}

.login_content:not(.btn) {
    margin: 0 auto;
    padding: 25px 0 0;
    position: relative;
    text-align: center;
    min-width: 280px;
    color: #fff;
}

.login_content form {
    margin: 20px 0;
    position: relative;
}
</style>
</head>

<body>

    <div class="login_wrapper">
        <div class="animate form login_form">
            <section class="login_content">
                <h1 style="line-height:28px"><?= THENAME ?></h1>

                <div class="mb-2">
                    <input type="email" class="form-control" placeholder="Registered email address" id="inputEmail"
                        required />
                </div>
                <div class="mb-2">
                    <input type="password" class="form-control" placeholder="Password" id="inputPassword" required />
                </div>
                <div class="mb-2">
                    <select class="form-control" id="inputType" required>
                        <option value="surveyor">Surveyor</option>
                        <?php if ($contractorModuleEnabled) { ?><option value="contractors">Contractor</option>
                        <?php } ?>
                        <option value="admins">Admin</option>
                    </select>
                </div>

                <div>
                    <button id="btnLogin" class="btn btn-primary mb-4" type="button" data-mdb-tooltip-init
                        data-mdb-placement="top" data-mdb-trigger="hover" title="Sign in" onclick="submitForm()">
                        <i class="fad fa-unlock"></i> Sign in
                    </button>
                    <br>
                    <a class="reset_pass text-light" href="javascript:void(0)" data-mdb-modal-init
                        data-mdb-target="#lostPasswordModal">
                        Lost your password?
                    </a>
                </div>

                <div class="separator">
                    <p class="change_link">
                        Interested in EnRep?
                        <a href="javascript:void(0)" class="to_register text-dark" data-mdb-modal-init
                            data-mdb-target="#demoRequestModal">
                            Request Demo
                        </a>
                    </p>

                    <div>
                        <h1 style="color:#fff">
                            <span style="color:#09a3c6; text-indent:20px">En</span>gineering<br>
                            <span style="color:#09a3c6; text-indent:20px">Rep</span>orting
                        </h1>
                        <p>&copy;<?= date('Y') ?></p>
                    </div>
                </div>
            </section>
        </div>
    </div>

    <!-- Lost Password Modal -->
    <div class="modal fade" id="lostPasswordModal" tabindex="-1" aria-labelledby="lostPasswordLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header"><a href="javascript:void(0)" class="sa">Password Reset</a></div>
                <div class="modal-body">
                    <div class="mb-2">
                        <input type="email" id="resetEmail" class="form-control" placeholder="Registered email address"
                            required>
                    </div>
                    <div class="mb-2">
                        <select id="resetType" class="form-control" required>
                            <option value="surveyor">Surveyor</option>
                            <?php if ($contractorModuleEnabled) { ?><option value="contractors">Contractor</option>
                            <?php } ?>
                            <option value="admins">Admin</option>
                        </select>
                    </div>
                    <div class="mb-2 text-center mt-3">
                        <button class="btn btn-primary" type="button" data-mdb-tooltip-init data-mdb-placement="top"
                            data-mdb-trigger="hover" title="Email a reset link" onclick="requestPasswordReset()">
                            <i class="fad fa-paper-plane"></i> Request Password Reset
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Demo Request Modal -->
    <div class="modal fade" id="demoRequestModal" tabindex="-1" aria-labelledby="demoRequestLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header"><a href="javascript:void(0)" class="sa">Request a Demo</a></div>
                <div class="modal-body">
                    <div class="mb-2"><input type="text" id="demoName" class="form-control" placeholder="Full Name"
                            required></div>
                    <div class="mb-2"><input type="email" id="demoEmail" class="form-control" placeholder="Email"
                            required></div>
                    <div class="mb-2"><input type="tel" id="demoContactNumber" class="form-control"
                            placeholder="Contact Number" required></div>
                    <div class="mb-2">
                        <select id="demoBusinessSize" class="form-control" required>
                            <option value="">Select Business Size</option>
                            <option value="Sole">Sole</option>
                            <option value="1-3">1-3 Employees</option>
                            <option value="3-5">3-5 Employees</option>
                            <option value="5-10">5-10 Employees</option>
                            <option value="10+">10+ Employees</option>
                        </select>
                    </div>
                    <div class="mb-2">
                        <input type="text" id="demoSoftware" class="form-control"
                            placeholder="Existing Reporting Software (if any)">
                    </div>
                    <div class="mb-2">
                        <button class="btn btn-primary" type="button" data-mdb-tooltip-init data-mdb-placement="top"
                            data-mdb-trigger="hover" title="Send demo request" onclick="submitDemoRequest()">
                            <i class="fad fa-paper-plane"></i> Request Demo
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 2FA Modal -->
    <div class="modal fade" id="twoFAModal" tabindex="-1" aria-labelledby="twoFALabel" aria-hidden="true">
        <div class="modal-dialog modal-md">
            <div class="modal-content" id="twoFAContainer">
                <div class="modal-header">
                    <h5 class="modal-title" id="twoFALabel">Two-Factor Authentication</h5>
                    <button type="button" class="btn-close" data-mdb-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Enter the 6-digit code sent to your email.</p>
                    <div class="mb-3">
                        <input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="6" class="form-control"
                            id="twoFACode" placeholder="123456" />
                    </div>
                    <div class="d-flex gap-2">
                        <button id="btnVerify2FA" class="btn btn-primary" data-mdb-tooltip-init data-mdb-placement="top"
                            data-mdb-trigger="hover" title="Verify code" onclick="verify2FA()">
                            <i class="fad fa-check-circle"></i> Verify
                        </button>
                        <button id="btnResend2FA" class="btn btn-outline-secondary" data-mdb-tooltip-init
                            data-mdb-placement="top" data-mdb-trigger="hover" title="Resend code" onclick="resend2FA()">
                            <i class="fad fa-sync"></i> Resend
                        </button>
                    </div>
                    <div id="twoFAStatus" class="mt-3 small"></div>
                </div>
            </div>
        </div>
    </div>

    <script>
    function maskEmail(email) {
        if (!email) return '';
        const [local, domain] = String(email).split('@');
        if (!domain) return email;
        const first = local.charAt(0) || '';
        return `${first}${'*'.repeat(Math.max(1, local.length - 1))}@${domain}`;
    }
    /* Helpers */
    function getModal(el) {
        return mdb.Modal.getInstance(el) || new mdb.Modal(el);
    }

    function disableBtn(btn, yes) {
        btn.disabled = !!yes;
        if (yes) btn.setAttribute('data-working', '1');
        else btn.removeAttribute('data-working');
    }

    function showMsg(kind, msg) {
        if (typeof showResponse === 'function') {
            showResponse(kind, msg);
            return;
        }
        // Fallback
        console.log(kind.toUpperCase() + ': ' + msg);
    }

    /* Initial notice */
    <?php if ($blocked) { ?>
    showMsg('danger', 'Your access has been suspended, please contact your system administrator');
    <?php } ?>

    /* Demo request */
    async function submitDemoRequest() {
        const demoName = document.getElementById('demoName').value.trim();
        const demoEmail = document.getElementById('demoEmail').value.trim();
        const demoContactNumber = document.getElementById('demoContactNumber').value.trim();
        const demoBusinessSize = document.getElementById('demoBusinessSize').value.trim();
        const demoSoftware = document.getElementById('demoSoftware').value.trim();

        if (!demoName || !demoEmail || !demoContactNumber || !demoBusinessSize) {
            showMsg('danger', 'Please fill in all required fields.');
            return;
        }

        const btn = event?.currentTarget;
        if (btn) disableBtn(btn, true);

        try {
            const res = await fetch(ROOT_URL + '/framework/demo_request.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({
                    name: demoName,
                    email: demoEmail,
                    contact: demoContactNumber,
                    size: demoBusinessSize,
                    software: demoSoftware,
                    tenant: TENANT_URL
                })
            });
            const txt = await res.text();
            if (txt.trim() === 'success') {
                showMsg('success', 'Demo request has been sent successfully.');
                getModal(document.getElementById('demoRequestModal')).hide();
            } else {
                showMsg('danger', 'Error processing request. Please try again later.');
            }
        } catch (e) {
            console.error(e);
            showMsg('danger', 'Failed to send demo request. Please try again later.');
        } finally {
            if (btn) disableBtn(btn, false);
        }
    }

    /* Password reset */
    async function requestPasswordReset() {
        const resetEmail = document.getElementById('resetEmail').value.trim();
        const resetType = document.getElementById('resetType').value;

        if (!resetEmail || !resetType) {
            showMsg('danger', 'Please enter both your email and select user type');
            return;
        }

        const btn = event?.currentTarget;
        if (btn) disableBtn(btn, true);

        try {
            const res = await fetch(ROOT_URL + '/framework/password_reset_request.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({
                    email: resetEmail,
                    type: resetType,
                    tenant: TENANT_URL
                })
            });
            const txt = await res.text();
            if (txt.trim() === 'success') {
                showMsg('success', 'Password reset link has been sent to your email.');
                getModal(document.getElementById('lostPasswordModal')).hide();
            } else {
                showMsg('danger', 'Error processing request. Please ensure the email is registered.');
            }
        } catch (e) {
            console.error(e);
            showMsg('danger', 'Failed to send reset link. Please try again later.');
        } finally {
            if (btn) disableBtn(btn, false);
        }
    }

    /* Login + 2FA */
    async function submitForm() {
        const email = document.getElementById('inputEmail').value.trim();
        const pass = document.getElementById('inputPassword').value;
        const type = document.getElementById('inputType').value;
        const btn = document.getElementById('btnLogin');

        if (!email || !pass || !type) {
            showMsg('warning', 'Please complete all fields.');
            return;
        }

        disableBtn(btn, true);

        try {
            const res = await fetch('config.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({
                    u: email,
                    p: pass,
                    t: type,
                    src: 'ext',
                    op: 'login'
                })
            });
            const data = (await res.text()).trim();

            // Standard outcomes
            if (data === '0') {
                showResponse('warning', 'The details entered have not been recognised, please try again');
                btn.blur();
                return;
            }
            if (data === '1') {
                window.location.href = 'index.php';
                return;
            }
            if (data === '3') {
                showResponse('danger', 'Your access has been suspended, please contact your system administrator');
                btn.blur();
                return;
            }
            if (data.startsWith('4|')) {
                const parts = data.split('|');
                const remainingHours = parts[1] ?? '0';
                const remainingMinutes = parts[2] ?? '0';
                showResponse('warning',
                    `Your account is in a lockout period due to a recent reinstatement. Please try again in ${remainingHours} hours and ${remainingMinutes} minutes.`
                );
                btn.blur();
                return;
            }

            // 2FA trigger
            // Accepts variants like: "2FA", "2FA_REQUIRED", or "2FA|email@example.com"
            if (data.toUpperCase().startsWith('2FA')) {
                const el = document.getElementById('twoFAModal');
                getModal(el).show();
                document.getElementById('twoFACode').focus();
                const info = (data.split('|')[1] || '').trim();
                const masked = info ? maskEmail(info) : '';
                const status = document.getElementById('twoFAStatus');
                status.textContent = masked ? `Code sent to ${masked}` : 'Code sent to your email.';
                return;
            }

            // Unknown response
            showResponse('danger', 'Unexpected response during login.');
        } catch (e) {
            console.error(e);
            showResponse('danger', 'An error occurred while processing your login. Please try again later.');
        } finally {
            disableBtn(btn, false);
        }
    }

    async function verify2FA() {
        const codeEl = document.getElementById('twoFACode');
        const code = codeEl.value.trim();
        const btn = document.getElementById('btnVerify2FA');
        const status = document.getElementById('twoFAStatus');

        if (!/^\d{6}$/.test(code)) {
            status.textContent = 'Enter a valid 6-digit code.';
            return;
        }

        disableBtn(btn, true);
        status.textContent = 'Verifying…';

        try {
            const res = await fetch('/framework/verify_2fa_local.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({
                    code
                })
            });
            const json = await res.json();
            if (json.status === 'ok') {
                status.textContent = 'Verified. Finishing sign-in…';
                // Server sets trust cookie and session. Reload to continue to app.
                window.location.reload();
                return;
            }
            if (json.error === 'expired') {
                status.textContent = 'Code expired. Resend a new code.';
                return;
            }
            if (json.error === 'used') {
                status.textContent = 'Code already used. Resend a new code.';
                return;
            }
            if (json.error === 'invalid') {
                status.textContent = 'Invalid code. Check and try again.';
                return;
            }
            status.textContent = 'Verification failed.';
        } catch (e) {
            console.error(e);
            status.textContent = 'Error verifying code.';
        } finally {
            disableBtn(btn, false);
        }
    }

    async function resend2FA() {
        const btn = document.getElementById('btnResend2FA');
        const status = document.getElementById('twoFAStatus');
        disableBtn(btn, true);
        status.textContent = 'Sending code…';

        try {
            const res = await fetch(ROOT_URL + '/framework/resend_2fa.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({
                    a: 'resend',
                    tenant: TENANT_URL
                })
            });
            const json = await res.json().catch(() => ({}));
            if (json.status === 'ok') {
                status.textContent = 'New code sent.';
            } else if (json.status === 'error' && json.message) {
                status.textContent = json.message;
            } else {
                // Older resend may return plain 'ok'
                const txt = await res.text();
                if (txt.trim().toLowerCase() === 'ok' || txt.trim().toLowerCase() === 'success') {
                    status.textContent = 'New code sent.';
                } else {
                    status.textContent = 'Could not send a new code.';
                }
            }
        } catch (e) {
            console.error(e);
            status.textContent = 'Error sending code.';
        } finally {
            disableBtn(btn, false);
        }
    }
    </script>