<?php
require_once __DIR__ . '/../app/includes/auth.php';
header('X-Frame-Options: SAMEORIGIN');
header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: strict-origin-when-cross-origin');
header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

if (current_user()) {
    redirect('/dashboard.php');
}

$email = $_SESSION['verification_email'] ?? null;
if (!$email) {
    flash('error', 'No pending verification found. Please register again.');
    redirect('/register.php');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $otp = trim((string)post('otp'));

    if (!$otp) {
        flash('error', 'Please enter the verification code.');
    } else {
        $stmt = db()->prepare('SELECT * FROM email_verifications WHERE email = ?');
        $stmt->execute([$email]);
        $record = $stmt->fetch();

        if (!$record) {
            flash('error', 'Verification record not found.');
        } elseif (strtotime($record['expires_at']) < time()) {
            flash('error', 'This verification code has expired. Please register again.');
            db()->prepare('DELETE FROM email_verifications WHERE email = ?')->execute([$email]);
            unset($_SESSION['verification_email']);
        } elseif ($record['otp'] !== $otp) {
            flash('error', 'Invalid verification code.');
        } else {
            // Success! Create the user.
            $payload = json_decode($record['payload'], true);
            
            db()->beginTransaction();
            try {
                $stmt = db()->prepare('INSERT INTO users (name, email, mobile_number, company_name, password_hash, role, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
                $stmt->execute([
                    $payload['name'], 
                    $email, 
                    $payload['mobile_number'] ?? null, 
                    $payload['company_name'] ?? null, 
                    $payload['password_hash'], 
                    'visitor', 
                    'active', 
                    now()
                ]);
                $userId = db()->lastInsertId();

                $stmt = db()->prepare('INSERT INTO customers (customer_name, phone, email, customer_type, created_by, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)');
                $stmt->execute([
                    $payload['company_name'] ?: $payload['name'], 
                    $payload['mobile_number'] ?? null, 
                    $email, 
                    'visitor', 
                    $userId,
                    now(), 
                    now()
                ]);
                
                db()->prepare('DELETE FROM email_verifications WHERE email = ?')->execute([$email]);
                
                db()->commit();
                unset($_SESSION['verification_email']);

                $user = ['id' => $userId, 'name' => $payload['name'], 'email' => $email, 'role' => 'visitor'];
                login_user($user);
                log_activity('register.verified', 'New visitor verified and registered: ' . $email);
                
                flash('success', 'Your account has been successfully created and verified.');
                redirect('/dashboard.php');
            } catch (Exception $e) {
                db()->rollBack();
                flash('error', 'An error occurred while creating your account. Please try again.');
            }
        }
    }
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Verify Email - <?= APP_NAME ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
    <link href="<?= APP_BASE ?>/assets/css/app.css?v=<?= time() ?>" rel="stylesheet">
</head>
<body class="login-page">
    <div class="login-card">
        <div class="login-logo">F</div>
        <h1>Verify Email</h1>
        <p>Enter the 6-digit code sent to <strong><?= e($email) ?></strong>.</p>
        <?php if ($msg = flash('error')): ?><div class="alert alert-danger"><?= e($msg) ?></div><?php endif; ?>
        <?php if ($msg = flash('success')): ?><div class="alert alert-success"><?= $msg ?></div><?php endif; ?>
        <form method="post" novalidate>
            <?= csrf_field() ?>
            <label class="form-label">Verification Code</label>
            <input class="form-control mb-4 text-center fs-4 fw-bold" type="text" name="otp" maxlength="6" pattern="\d{6}" required autocomplete="one-time-code" style="letter-spacing: 5px;">
            <button class="btn btn-primary w-100 mb-3" type="submit"><i class="bi bi-shield-check me-1"></i>Verify Account</button>
            <div class="text-center text-muted" style="font-size:0.9rem;">
                <a href="<?= APP_BASE ?>/register.php" class="text-decoration-none">Start Over</a>
            </div>
        </form>
    </div>
</body>
</html>
