<?php
define('SHARED_PATH', __DIR__ . '/shared');
require_once SHARED_PATH . '/includes/site-config.php';
init_site('hub');
require_once SHARED_PATH . '/includes/config.php';
require_once SHARED_PATH . '/includes/auth.php';

if (Auth::isLoggedIn()) {
    // Als geen expliciete redirect → naar /portaal/ (niet homepage)
    // Cursus-inschrijven flow gebruikt ?redirect=/cursus/inschrijven?... — blijft werken
    $redirect = $_GET['redirect'] ?? '/portaal/';
    if ($redirect === '/' || $redirect === '') $redirect = '/portaal/';
    header('Location: ' . $redirect);
    exit;
}

$step     = $_POST['step'] ?? $_GET['step'] ?? 'email'; // email | code
$errors   = [];
$success  = '';
$redirect = $_GET['redirect'] ?? $_POST['redirect'] ?? '/';
$email    = $_POST['email'] ?? $_GET['email'] ?? '';

// POST handler
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $step = $_POST['step'] ?? 'email';

    if ($step === 'email') {
        // Stap 1: Stuur login code
        $email = strtolower(trim($_POST['email'] ?? ''));
        $result = Auth::sendLoginCode($email);
        if ($result['success']) {
            $step = 'code';
            $success = 'Er is een inlogcode verstuurd naar ' . htmlspecialchars($email);
        } else {
            $errors[] = $result['error'];
        }

    } elseif ($step === 'code') {
        // Stap 2: Verifieer code en log in
        $email = strtolower(trim($_POST['email'] ?? ''));
        $code  = trim($_POST['code'] ?? '');
        $result = Auth::verifyLoginCode($email, $code);

        if ($result['success']) {
            // Default na login: altijd /portaal/ (admin-panel bereikbaar via portaal-navigatie).
            // Expliciete redirect (bv ?redirect=/specifieke-pagina) wordt onderaan gerespecteerd.
            if ($redirect === '/' || $redirect === '') {
                header('Location: /portaal/');
                exit;
            }

            // Auto module-rol als redirect dat aangeeft
            $parsedRedirect = parse_url($redirect);
            parse_str($parsedRedirect['query'] ?? '', $qp);
            $autoModule = $qp['module'] ?? '';
            $autoRol    = $qp['rol'] ?? '';
            if ($autoModule && $autoRol && Auth::userId()) {
                $allowedAutoRols = [
                    'cursus' => ['cursist', 'docent', 'organisatie'],
                    'inventarisatie' => ['organisatie', 'monteur'],
                    'verzamelactie' => ['houder'],
                ];
                if (isset($allowedAutoRols[$autoModule]) && in_array($autoRol, $allowedAutoRols[$autoModule])) {
                    $autoStatus = ($autoModule === 'cursus' && $autoRol === 'cursist') ? 'actief' : 'pending';
                    Auth::addModuleRol(Auth::userId(), $autoModule, $autoRol, null, $autoStatus);
                }
            }

            header('Location: ' . $redirect);
            exit;
        }
        $errors[] = $result['error'];
    }
}

$pageTitle = 'Inloggen — Reanimatie.nl';
?>
<!DOCTYPE html>
<html lang="nl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($pageTitle) ?></title>
    <meta name="robots" content="noindex, nofollow">
    <meta name="description" content="Inloggen bij Reanimatie.nl. Ontvang een eenmalige inlogcode per e-mail.">
    <link rel="canonical" href="https://www.reanimatie.nl/login">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <link rel="stylesheet" href="/css/style.css">
    <link rel="stylesheet" href="/css/modules.css">
    <style>
        .code-inputs { display: flex; gap: 8px; justify-content: center; margin: 20px 0; }
        .code-inputs input {
            width: 48px; height: 56px; text-align: center; font-size: 1.5rem; font-weight: 700;
            border: 2px solid var(--border); border-radius: var(--radius-md); background: var(--bg-secondary);
            transition: var(--transition);
        }
        .code-inputs input:focus { border-color: var(--accent); outline: none; background: #fff; }
    </style>
</head>
<body>

<header class="topbar" id="topbar">
    <div class="container topbar__inner">
        <a href="/" class="topbar__logo">
            <img src="/assets/images/logo-hart.svg" alt="Reanimatie.nl" class="logo-icon-svg">
            <span class="logo-text">Reanimatie<span class="logo-accent">.nl</span></span>
        </a>
    </div>
</header>

<div class="auth-page">
    <div class="auth-card">
        <div class="auth-logo">
            <a href="/">
                <img src="/assets/images/logo-hart.svg" alt="Reanimatie.nl" style="width:48px;height:48px;">
                Reanimatie<span style="color:var(--accent)">.nl</span>
            </a>
        </div>

        <?php if (!empty($errors)): ?>
            <div class="alert alert-error">
                <i class="fa-solid fa-circle-exclamation"></i>
                <?= htmlspecialchars($errors[0]) ?>
            </div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="alert alert-success">
                <i class="fa-solid fa-check-circle"></i>
                <?= $success ?>
            </div>
        <?php endif; ?>

        <?php if ($step === 'code'): ?>
        <!-- STAP 2: Code invoeren -->
        <h2 style="text-align:center;font-size:1.15rem;font-weight:700;margin-bottom:4px;">Inlogcode invoeren</h2>
        <p style="text-align:center;font-size:0.85rem;color:var(--text-secondary);margin-bottom:20px;">
            Voer de 6-cijferige code in die we naar<br><strong><?= htmlspecialchars($email) ?></strong> hebben gestuurd.
        </p>

        <form method="POST" action="/login.php?redirect=<?= urlencode($redirect) ?>" id="codeForm">
            <input type="hidden" name="step" value="code">
            <input type="hidden" name="email" value="<?= htmlspecialchars($email) ?>">
            <input type="hidden" name="redirect" value="<?= htmlspecialchars($redirect) ?>">
            <input type="hidden" name="code" id="codeValue">

            <div class="code-inputs">
                <input type="text" maxlength="1" inputmode="numeric" pattern="[0-9]" data-code-pos="0" autofocus>
                <input type="text" maxlength="1" inputmode="numeric" pattern="[0-9]" data-code-pos="1">
                <input type="text" maxlength="1" inputmode="numeric" pattern="[0-9]" data-code-pos="2">
                <input type="text" maxlength="1" inputmode="numeric" pattern="[0-9]" data-code-pos="3">
                <input type="text" maxlength="1" inputmode="numeric" pattern="[0-9]" data-code-pos="4">
                <input type="text" maxlength="1" inputmode="numeric" pattern="[0-9]" data-code-pos="5">
            </div>

            <button type="submit" class="btn btn-primary w-full" style="padding:12px;">
                <i class="fa-solid fa-right-to-bracket"></i> Inloggen
            </button>
        </form>

        <p style="text-align:center;font-size:0.85rem;margin-top:16px;">
            <a href="/login.php?redirect=<?= urlencode($redirect) ?>" style="color:var(--primary);">
                <i class="fa-solid fa-arrow-left"></i> Ander e-mailadres
            </a>
        </p>

        <script>
        (function() {
            const inputs = document.querySelectorAll('.code-inputs input');
            const form = document.getElementById('codeForm');
            const codeValue = document.getElementById('codeValue');

            inputs.forEach((inp, i) => {
                inp.addEventListener('input', function() {
                    this.value = this.value.replace(/\D/g, '').slice(0, 1);
                    if (this.value && i < 5) inputs[i + 1].focus();
                    updateCode();
                });
                inp.addEventListener('keydown', function(e) {
                    if (e.key === 'Backspace' && !this.value && i > 0) {
                        inputs[i - 1].focus();
                        inputs[i - 1].value = '';
                        updateCode();
                    }
                });
                inp.addEventListener('paste', function(e) {
                    e.preventDefault();
                    const paste = (e.clipboardData.getData('text') || '').replace(/\D/g, '').slice(0, 6);
                    paste.split('').forEach((ch, j) => { if (inputs[j]) inputs[j].value = ch; });
                    if (paste.length > 0) inputs[Math.min(paste.length, 5)].focus();
                    updateCode();
                    if (paste.length === 6) form.submit();
                });
            });

            function updateCode() {
                codeValue.value = Array.from(inputs).map(i => i.value).join('');
            }

            form.addEventListener('submit', function() { updateCode(); });
        })();
        </script>

        <?php else: ?>
        <!-- STAP 1: E-mail invoeren -->
        <h2 style="text-align:center;font-size:1.15rem;font-weight:700;margin-bottom:4px;">Inloggen / Registreren</h2>
        <p style="text-align:center;font-size:0.85rem;color:var(--text-secondary);margin-bottom:20px;">
            Voer uw e-mailadres in. U ontvangt een inlogcode per e-mail.
        </p>

        <form method="POST" action="/login.php?redirect=<?= urlencode($redirect) ?>">
            <input type="hidden" name="step" value="email">
            <input type="hidden" name="redirect" value="<?= htmlspecialchars($redirect) ?>">

            <div class="form-group">
                <label class="form-label">E-mailadres</label>
                <input type="email" name="email" class="form-control" placeholder="uw@email.nl"
                       value="<?= htmlspecialchars($email) ?>" required autofocus>
            </div>

            <button type="submit" class="btn btn-primary w-full" style="padding:12px;">
                <i class="fa-solid fa-paper-plane"></i> Inlogcode versturen
            </button>

            <p style="text-align:center;font-size:0.8rem;color:var(--text-muted);margin-top:16px;">
                <i class="fa-solid fa-shield-halved"></i> Geen wachtwoord nodig — u logt in met een eenmalige code per e-mail.
            </p>
        </form>
        <?php endif; ?>
    </div>
</div>
</body>
</html>
