<?php
$page_title = 'Become a Member';
$page_description = 'Join Buy Local Lowveld — choose your package and start supporting local.';

require_once __DIR__ . '/includes/csrf.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/auth.php';

// Already logged in? Send them to dashboard
if (auth_check()) {
    header('Location: member/welcome.php'); exit;
}

// Load plans from DB
$tiers = [];
if (db_is_ready()) {
    $db_plans = db_all(
        'SELECT * FROM subscription_plans WHERE active=1 ORDER BY sort_order, id'
    );
    foreach ($db_plans as $p) {
        $benefits = json_decode($p['benefits'] ?? '[]', true) ?: [];
        $tiers[] = [
            'slug'      => $p['slug'],
            'name'      => $p['name'],
            'price'     => $p['price_display'],
            'price_cents'=> (int)$p['price_cents'],
            'highlight' => !empty($p['badge']),
            'badge'     => $p['badge'],
            'features'  => $benefits,
        ];
    }
}
if (empty($tiers)) {
    $packages = require __DIR__ . '/data/packages.php';
    $tiers    = $packages['tiers'];
}

$categories = db_is_ready()
    ? db_all('SELECT slug, name FROM categories ORDER BY sort_order, name')
    : require __DIR__ . '/data/categories.php';

$error = $_GET['error'] ?? '';
require 'includes/header.php';
?>

<style>
/* ── Wizard shell ── */
.wizard-wrap { max-width: 860px; margin: 0 auto; padding: 2rem 1rem 4rem; }

/* ── Progress steps ── */
.wiz-progress {
    display: flex; align-items: center; gap: 0;
    margin-bottom: 2.5rem; counter-reset: step;
}
.wiz-step-label {
    display: flex; align-items: center; gap: .5rem;
    font-size: .82rem; color: var(--ink-muted); flex: 1;
    transition: color .3s;
}
.wiz-step-label::before {
    counter-increment: step;
    content: counter(step);
    display: inline-flex; align-items: center; justify-content: center;
    width: 28px; height: 28px; border-radius: 50%;
    background: var(--surface-alt); border: 2px solid var(--line);
    font-weight: 700; font-size: .82rem; flex-shrink: 0;
    transition: background .3s, border-color .3s, color .3s;
}
.wiz-step-label.done { color: var(--brand-primary); }
.wiz-step-label.done::before {
    background: var(--brand-primary); border-color: var(--brand-primary); color: white;
    content: '✓';
}
.wiz-step-label.active { color: var(--ink); font-weight: 600; }
.wiz-step-label.active::before {
    background: white; border-color: var(--brand-primary); color: var(--brand-primary);
}
.wiz-connector { flex: 0 0 2rem; height: 2px; background: var(--line); margin: 0 .25rem; }
.wiz-connector.done { background: var(--brand-primary); }

/* ── Slides ── */
.wiz-slides { position: relative; overflow: hidden; }
.wiz-slide {
    display: none;
    animation: slideIn .3s ease;
}
.wiz-slide.active { display: block; }
@keyframes slideIn {
    from { opacity: 0; transform: translateX(24px); }
    to   { opacity: 1; transform: translateX(0); }
}

/* ── Package cards ── */
.pkg-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 1rem; }
.pkg-card {
    border: 2px solid var(--line); border-radius: var(--radius); padding: 1.25rem;
    cursor: pointer; position: relative; transition: border-color .2s, transform .15s;
    background: white; text-align: center;
}
.pkg-card:hover { border-color: var(--brand-primary); transform: translateY(-2px); }
.pkg-card.selected {
    border-color: var(--brand-primary);
    box-shadow: 0 0 0 3px rgba(var(--brand-primary-rgb, 34,139,34), .15);
}
.pkg-card .pkg-badge {
    position: absolute; top: -1px; left: 50%; transform: translateX(-50%);
    background: var(--brand-primary); color: white;
    font-size: .68rem; font-weight: 700; text-transform: uppercase;
    letter-spacing: .05em; padding: .2em .8em; border-radius: 0 0 6px 6px;
    white-space: nowrap;
}
.pkg-card .pkg-name { font-size: 1.1rem; font-weight: 800; margin: .5rem 0 .25rem; }
.pkg-card .pkg-price { font-size: 1.3rem; font-weight: 900; color: var(--brand-primary); }
.pkg-card .pkg-features {
    list-style: none; padding: 0; margin: .85rem 0 0;
    text-align: left; font-size: .8rem; color: var(--ink-muted);
}
.pkg-card .pkg-features li { padding: .2rem 0; padding-left: 1.1em; position: relative; }
.pkg-card .pkg-features li::before { content: '✓'; position: absolute; left: 0; color: var(--brand-primary); }
.pkg-card input[type=radio] { display: none; }

/* ── Form styling ── */
.form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 0 1.25rem; }
.form-group { margin-bottom: 1rem; }
.form-group label { display: block; font-weight: 600; font-size: .88rem; margin-bottom: .35rem; }
.form-group input, .form-group select, .form-group textarea {
    width: 100%; padding: .65rem .85rem;
    border: 1px solid var(--line); border-radius: var(--radius);
    font-size: .95rem; background: white;
    transition: border-color .2s, box-shadow .2s;
}
.form-group input:focus, .form-group select:focus {
    outline: none; border-color: var(--brand-primary);
    box-shadow: 0 0 0 3px rgba(34,139,34,.1);
}
.form-group .hint { font-size: .78rem; color: var(--ink-muted); margin-top: .25rem; }
.field-error { border-color: #c0392b !important; }
.field-msg { font-size: .78rem; color: #c0392b; margin-top: .25rem; display: none; }
.field-msg.show { display: block; }

/* ── Password strength ── */
.pw-bar { height: 4px; border-radius: 2px; margin-top: .4rem; background: var(--line); }
.pw-fill { height: 100%; border-radius: 2px; transition: width .3s, background .3s; width: 0; }
.pw-label { font-size: .75rem; margin-top: .25rem; color: var(--ink-muted); }

/* ── Step 3 ── */
.payment-summary {
    max-width: 420px; margin: 0 auto; text-align: center;
    border: 2px solid var(--brand-primary); border-radius: var(--radius);
    padding: 2rem; background: white;
}
.payment-summary .sum-tier { font-size: 1.1rem; font-weight: 800; }
.payment-summary .sum-price { font-size: 2.2rem; font-weight: 900; color: var(--brand-primary); margin: .5rem 0; }
.payment-summary .sum-note { font-size: .82rem; color: var(--ink-muted); }

/* ── Nav buttons ── */
.wiz-nav { display: flex; gap: .75rem; margin-top: 1.75rem; align-items: center; }
.wiz-nav .back-btn { background: none; border: none; color: var(--ink-muted);
                     cursor: pointer; font-size: .9rem; padding: .5rem 0; }
.wiz-nav .back-btn:hover { color: var(--ink); }

@media (max-width: 600px) {
    .form-row { grid-template-columns: 1fr; }
    .pkg-grid { grid-template-columns: 1fr 1fr; }
}
</style>

<div class="wizard-wrap">

    <?php if ($error === 'exists'): ?>
        <div class="alert alert-error" style="margin-bottom:1.5rem;">
            That email is already registered with us.
            <a href="login.php">Log in</a> or
            <a href="forgot.php">reset your password</a>.
        </div>
    <?php elseif ($error === 'zoho_exists'): ?>
        <div class="alert alert-error" style="margin-bottom:1.5rem;">
            We already have a customer record with this email address. If you've signed up with us before,
            please <a href="login.php">log in</a> or
            <a href="forgot.php">reset your password</a>.
            If this isn't you, get in touch via <a href="contact.php">our contact page</a> and we'll sort it out.
        </div>
    <?php elseif ($error === 'invalid_email'): ?>
        <div class="alert alert-error" style="margin-bottom:1.5rem;">
            That email address didn't pass validation. Please check the spelling and try again with a real
            email you can receive mail at — invoices and receipts will be sent there.
        </div>
    <?php elseif ($error === 'missing'): ?>
        <div class="alert alert-error" style="margin-bottom:1.5rem;">
            Please fill in all required fields.
        </div>
    <?php endif; ?>

    <!-- Progress indicator -->
    <div class="wiz-progress" id="wiz-progress">
        <span class="wiz-step-label active" data-label="1">Choose package</span>
        <span class="wiz-connector" data-connector="1"></span>
        <span class="wiz-step-label" data-label="2">Your details</span>
        <span class="wiz-connector" data-connector="2"></span>
        <span class="wiz-step-label" data-label="3">Payment</span>
    </div>

    <div class="wiz-slides">

        <!-- ═══════════════════════════════════════════
             SLIDE 1 — Choose package
        ════════════════════════════════════════════ -->
        <div class="wiz-slide active" id="slide-1">
            <h2 style="margin:0 0 .5rem;">Choose your package</h2>
            <p class="muted" style="margin:0 0 1.5rem;">
                Pick a tier. Start where it fits — you can upgrade any time.
            </p>

            <div class="pkg-grid" id="pkg-grid">
                <?php foreach ($tiers as $t): ?>
                    <label class="pkg-card <?= !empty($t['highlight'])?'selected':'' ?>" id="pkg-<?= htmlspecialchars($t['slug']) ?>">
                        <input type="radio" name="tier_pick" value="<?= htmlspecialchars($t['name']) ?>"
                               <?= !empty($t['highlight'])?'checked':'' ?>>
                        <?php if (!empty($t['badge'])): ?>
                            <span class="pkg-badge"><?= htmlspecialchars($t['badge']) ?></span>
                        <?php endif; ?>
                        <div class="pkg-name"><?= htmlspecialchars($t['name']) ?></div>
                        <div class="pkg-price"><?= htmlspecialchars($t['price']) ?></div>
                        <?php if (!empty($t['features'])): ?>
                            <ul class="pkg-features">
                                <?php foreach (array_slice($t['features'], 0, 4) as $f): ?>
                                    <li><?= htmlspecialchars($f) ?></li>
                                <?php endforeach; ?>
                            </ul>
                        <?php endif; ?>
                    </label>
                <?php endforeach; ?>
            </div>

            <div class="wiz-nav">
                <button class="btn" onclick="goStep(2)">
                    Continue to your details →
                </button>
            </div>
        </div>

        <!-- ═══════════════════════════════════════════
             SLIDE 2 — Member information
        ════════════════════════════════════════════ -->
        <div class="wiz-slide" id="slide-2">
            <h2 style="margin:0 0 .5rem;">Your details</h2>
            <p class="muted" style="margin:0 0 1.5rem;">
                This is your account information. You'll complete your business profile after payment.
            </p>

            <form id="signup-form" action="signup-submit.php" method="post" novalidate>
                <?= csrf_field() ?>
                <input type="hidden" id="tier-hidden" name="tier" value="">
                <input type="hidden" name="consent" value="1">

                <div class="form-row">
                    <div class="form-group">
                        <label for="first_name">First name *</label>
                        <input type="text" id="first_name" name="first_name"
                               placeholder="Jane" autocomplete="given-name">
                        <div class="field-msg" id="err-first_name">Required</div>
                    </div>
                    <div class="form-group">
                        <label for="last_name">Last name *</label>
                        <input type="text" id="last_name" name="last_name"
                               placeholder="Smith" autocomplete="family-name">
                        <div class="field-msg" id="err-last_name">Required</div>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="email">Email *</label>
                        <input type="email" id="email" name="email"
                               placeholder="you@company.co.za" autocomplete="email">
                        <div class="field-msg" id="err-email">Enter a valid email address</div>
                    </div>
                    <div class="form-group">
                        <label for="phone">Phone</label>
                        <input type="tel" id="phone" name="phone"
                               placeholder="013 000 0000" autocomplete="tel">
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="business">Business name *</label>
                        <input type="text" id="business" name="business"
                               placeholder="My Business (Pty) Ltd" autocomplete="organization">
                        <div class="field-msg" id="err-business">Required</div>
                    </div>
                    <div class="form-group">
                        <label for="industry">Industry / category *</label>
                        <select id="industry" name="industry">
                            <option value="">— choose —</option>
                            <?php foreach ($categories as $c): ?>
                                <option value="<?= htmlspecialchars($c['slug']) ?>">
                                    <?= htmlspecialchars($c['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <div class="field-msg" id="err-industry">Please select a category</div>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="password">Choose a password *</label>
                        <input type="password" id="password" name="password"
                               placeholder="At least 8 characters" autocomplete="new-password">
                        <div class="pw-bar"><div class="pw-fill" id="pw-fill"></div></div>
                        <div class="pw-label" id="pw-label"></div>
                        <div class="field-msg" id="err-password">Minimum 8 characters</div>
                    </div>
                    <div class="form-group">
                        <label for="password2">Confirm password *</label>
                        <input type="password" id="password2" name="password_confirm"
                               placeholder="Repeat your password" autocomplete="new-password">
                        <div class="field-msg" id="err-password2">Passwords don't match</div>
                    </div>
                </div>

                <div class="wiz-nav">
                    <button type="button" class="back-btn" onclick="goStep(1)">← Back</button>
                    <button type="button" class="btn" onclick="validateStep2()">
                        Continue to payment →
                    </button>
                </div>

            </form><!-- form tag closes here; step 3 button submits it -->
        </div>

        <!-- ═══════════════════════════════════════════
             SLIDE 3 — Payment summary + redirect
        ════════════════════════════════════════════ -->
        <div class="wiz-slide" id="slide-3">
            <div class="payment-summary">
                <p class="muted" style="font-size:.85rem;margin:0 0 .5rem;">Selected package</p>
                <div class="sum-tier" id="sum-tier">—</div>
                <div class="sum-price" id="sum-price">—</div>
                <div class="sum-note">billed monthly · cancel any time</div>

                <div style="margin:1.5rem 0;padding:1rem;background:var(--surface-alt);border-radius:var(--radius);font-size:.85rem;text-align:left;">
                    <strong>What happens next:</strong>
                    <ol style="margin:.5rem 0 0;padding-left:1.25rem;line-height:1.8;">
                        <li>Redirected to PayFast to pay securely</li>
                        <li>Subscription activated instantly on payment</li>
                        <li>Complete your company profile and go live</li>
                    </ol>
                </div>

                <button type="button" class="btn" style="width:100%;" id="pay-btn"
                        onclick="submitSignup()">
                    Pay &amp; activate membership →
                </button>
                <button type="button" class="back-btn" onclick="goStep(2)" style="margin-top:.75rem;width:100%;text-align:center;">
                    ← Back to details
                </button>
            </div>
        </div>

    </div><!-- /wiz-slides -->
</div><!-- /wizard-wrap -->

<script>
// ── Package selection ──────────────────────────────────────────
const tierPrices = <?= json_encode(array_column($tiers, 'price', 'name')) ?>;
const tierNames  = <?= json_encode(array_column($tiers, 'name', 'name')) ?>;

document.querySelectorAll('.pkg-card').forEach(card => {
    card.addEventListener('click', function () {
        document.querySelectorAll('.pkg-card').forEach(c => c.classList.remove('selected'));
        this.classList.add('selected');
        this.querySelector('input[type=radio]').checked = true;
    });
});

function selectedTier() {
    const checked = document.querySelector('.pkg-grid input[type=radio]:checked');
    return checked ? checked.value : null;
}

// ── Step navigation ────────────────────────────────────────────
function goStep(n) {
    if (n === 2 && !selectedTier()) {
        alert('Please select a package first.');
        return;
    }

    document.querySelectorAll('.wiz-slide').forEach(s => s.classList.remove('active'));
    document.getElementById('slide-' + n).classList.add('active');

    // Update progress labels
    document.querySelectorAll('.wiz-step-label').forEach((el, i) => {
        const stepNum = i + 1;
        el.classList.remove('active', 'done');
        if (stepNum < n)      el.classList.add('done');
        else if (stepNum === n) el.classList.add('active');
    });
    document.querySelectorAll('.wiz-connector').forEach((el, i) => {
        el.classList.toggle('done', i + 1 < n);
    });

    // Populate step 3 summary
    if (n === 3) {
        const tier = selectedTier();
        document.getElementById('sum-tier').textContent  = tier || '—';
        document.getElementById('sum-price').textContent = tierPrices[tier] || '—';
    }

    window.scrollTo({ top: 0, behavior: 'smooth' });
}

// ── Password strength ──────────────────────────────────────────
document.getElementById('password').addEventListener('input', function () {
    const v = this.value;
    let score = 0;
    if (v.length >= 8)  score++;
    if (v.length >= 12) score++;
    if (/[A-Z]/.test(v)) score++;
    if (/[0-9]/.test(v)) score++;
    if (/[^a-zA-Z0-9]/.test(v)) score++;

    const fill  = document.getElementById('pw-fill');
    const label = document.getElementById('pw-label');
    const colours = ['#e74c3c','#e67e22','#f1c40f','#27ae60','#1a7b3c'];
    const labels  = ['Too short','Weak','Fair','Strong','Very strong'];
    const idx = Math.min(score, 4);
    fill.style.width   = (score * 20) + '%';
    fill.style.background = colours[idx];
    label.textContent  = v.length ? labels[idx] : '';
});

// ── Step 2 validation ──────────────────────────────────────────
function showErr(id, show) {
    const el = document.getElementById('err-' + id);
    const input = document.getElementById(id);
    if (el) el.classList.toggle('show', show);
    if (input) input.classList.toggle('field-error', show);
    return show;
}

function validateStep2() {
    let ok = true;
    const first    = document.getElementById('first_name').value.trim();
    const last     = document.getElementById('last_name').value.trim();
    const email    = document.getElementById('email').value.trim();
    const business = document.getElementById('business').value.trim();
    const industry = document.getElementById('industry').value;
    const pw       = document.getElementById('password').value;
    const pw2      = document.getElementById('password2').value;

    if (showErr('first_name', !first)) ok = false;
    if (showErr('last_name', !last))   ok = false;

    const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
    if (showErr('email', !emailOk)) ok = false;

    if (showErr('business', !business)) ok = false;
    if (showErr('industry', !industry)) ok = false;
    if (showErr('password', pw.length < 8)) ok = false;
    if (showErr('password2', pw !== pw2))   ok = false;

    if (!ok) return;

    // Set hidden tier field so the form submission carries it
    document.getElementById('tier-hidden').value = selectedTier();

    // POST the form to signup-validate.php — this creates the Zoho
    // contact and the local member, or returns an error to show inline.
    const continueBtn = document.querySelector('#slide-2 .btn');
    const originalLabel = continueBtn ? continueBtn.textContent : '';
    if (continueBtn) {
        continueBtn.disabled = true;
        continueBtn.textContent = 'Checking…';
    }
    clearServerError();

    const formEl = document.getElementById('signup-form');
    const formData = new FormData(formEl);

    fetch('signup-validate.php', {
        method: 'POST',
        body: formData,
        credentials: 'same-origin',
    })
    .then(r => r.json().catch(() => ({ok:false, error:'parse_error', message:'Server returned an unexpected response. Please try again.'})))
    .then(data => {
        if (data.ok) {
            goStep(3);
        } else {
            // Highlight a specific field if the server told us which one
            if (data.field) {
                showErr(data.field, true);
            }
            showServerError(data.message || 'Something went wrong. Please check your details and try again.');
        }
    })
    .catch(err => {
        showServerError('Couldn\'t reach the server. Please check your connection and try again.');
    })
    .finally(() => {
        if (continueBtn) {
            continueBtn.disabled = false;
            continueBtn.textContent = originalLabel;
        }
    });
}

function showServerError(msg) {
    let box = document.getElementById('server-error');
    if (!box) {
        box = document.createElement('div');
        box.id = 'server-error';
        box.className = 'alert alert-error';
        box.style.cssText = 'margin-bottom:1rem;';
        const slide2 = document.getElementById('slide-2');
        if (slide2) slide2.insertBefore(box, slide2.firstChild);
    }
    box.textContent = msg;
    box.scrollIntoView({behavior:'smooth', block:'center'});
}

function clearServerError() {
    const box = document.getElementById('server-error');
    if (box) box.remove();
}

// ── Submit ─────────────────────────────────────────────────────
function submitSignup() {
    document.getElementById('tier-hidden').value = selectedTier();
    const btn = document.getElementById('pay-btn');
    btn.disabled    = true;
    btn.textContent = 'Creating account…';
    document.getElementById('signup-form').submit();
}
</script>

<?php require 'includes/footer.php'; ?>