<?php
require_once __DIR__ . '/includes/functions.php';
startSecureSession();

if (isLoggedIn()) {
    header('Location: dashboard.php');
    exit;
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrfVerify();
    $action = $_POST['action'] ?? 'register';

    $sysSettings = getAdminSettings();
    if (empty($sysSettings['allow_registration'])) {
        $error = 'New merchant registrations are currently disabled by the site administrator.';
        if (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false) {
            echo json_encode(['status'=>'error', 'message'=>$error]); exit;
        }
    }

    if ($action === 'register') {
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $password = $_POST['password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';

        $turnstileResponse = $_POST['cf-turnstile-response'] ?? '';

        if (!$name || !$email || !$phone || !$password || !$confirmPassword) {
            $error = 'Please fill in all fields.';
        } elseif (!verifyTurnstile($turnstileResponse)) {
            $error = 'Please complete the security check.';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Please enter a valid email address.';
        } elseif (!preg_match('/^[0-9]{10}$/', $phone)) {
            $error = 'Please enter a valid 10-digit phone number.';
        } elseif (strlen($password) < 6) {
            $error = 'Password must be at least 6 characters.';
        } elseif ($password !== $confirmPassword) {
            $error = 'Passwords do not match.';
        } elseif (getUserByEmail($email)) {
            $error = 'An account with this email already exists. Please login instead.';
        } else {
            // Generate OTP
            $otp = str_pad((string)random_int(0, 999999), 6, '0', STR_PAD_LEFT);
            $_SESSION['pending_reg'] = [
                'name' => $name,
                'email' => $email,
                'phone' => $phone,
                'password' => $password,
                'otp' => $otp,
                'expires' => time() + 600 // 10 minutes
            ];

            // Send OTP Email
            $subject = "Your FamGateway Verification Code: $otp";
            $body = "
                <div style='font-family: Arial, sans-serif; padding: 20px; color: #333;'>
                    <h2>Verify Your Email</h2>
                    <p>Hi $name,</p>
                    <p>Thank you for registering at FamGateway. Your OTP code is:</p>
                    <h1 style='color: #2563eb; letter-spacing: 4px;'>$otp</h1>
                    <p>This code will expire in 10 minutes. If you did not request this, please ignore this email.</p>
                </div>
            ";
            sendSMTPMail($email, $subject, $body, true);

            if (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false) {
                echo json_encode(['status'=>'otp_required']); exit;
            }
        }
    } elseif ($action === 'verify_otp') {
        $otp = trim($_POST['otp'] ?? '');
        
        if (!isset($_SESSION['pending_reg']) || time() > $_SESSION['pending_reg']['expires']) {
            $error = 'OTP expired or session invalid. Please refresh the page and try registering again.';
        } elseif ($otp !== $_SESSION['pending_reg']['otp']) {
            $error = 'Invalid OTP. Please try again.';
        } else {
            // OTP is valid! Register the user
            $regData = $_SESSION['pending_reg'];
            $name = $regData['name'];
            $email = $regData['email'];
            $phone = $regData['phone'];
            $password = $regData['password'];

            if (getUserByEmail($email)) {
                $error = 'An account with this email already exists.';
            } else {
                $userId = generateUserId();
                $apiKey = generateApiKey();
                $nowObj = nowIST();

                $avatarBase64 = '';
                $hash = md5(strtolower(trim($email)));
                $monsterUrl = "https://www.gravatar.com/avatar/{$hash}?d=monsterid&s=150";
                $ctx = stream_context_create(['http' => ['timeout' => 3, 'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)\r\n"]]);
                $imgData = @file_get_contents($monsterUrl, false, $ctx);
                if ($imgData !== false && strlen($imgData) > 500) {
                    $avatarBase64 = 'data:image/png;base64,' . base64_encode($imgData);
                }

                $newUser = [
                    'id' => $userId,
                    'name' => $name,
                    'email' => $email,
                    'phone' => $phone,
                    'password_hash' => password_hash($password, PASSWORD_DEFAULT),
                    'created_at' => $nowObj->format('Y-m-d H:i:s'),
                    'fampay_gmail' => '',
                    'fampay_app_password_encrypted' => '',
                    'fampay_upi_id' => '',
                    'gmail_connected' => false,
                    'api_keys' => [['key' => $apiKey, 'label' => 'Default', 'created_at' => $nowObj->format('Y-m-d H:i:s')]],
                    'reset_chances' => 100,
                    'avatar' => $avatarBase64,
                    'plan_id' => 'free',
                    'plan_label' => 'Free',
                    'plan_expires_at' => null,
                    'total_requests' => 0,
                    'total_success' => 0,
                    'total_failed' => 0,
                    'total_amount_received' => 0,
                    'status' => 'active'
                ];

                saveUser($newUser);

                // Send Welcome Email
                $welcomeTpl = getEmailTemplate('welcome_email');
                if ($welcomeTpl) {
                    $loginUrl = "https://famgateway.in/login.php";
                    $body = str_replace(
                        ['{name}', '{email}', '{login_url}'],
                        [htmlspecialchars($name), htmlspecialchars($email), '<a href="'.$loginUrl.'">'.$loginUrl.'</a>'],
                        $welcomeTpl['body']
                    );
                    $subject = str_replace(
                        ['{name}', '{email}'],
                        [$name, $email],
                        $welcomeTpl['subject']
                    );
                    sendSMTPMail($email, $subject, $body, true);
                }

                // Clear session and auto-login
                unset($_SESSION['pending_reg']);
                $_SESSION['user_id'] = $userId;
                
                if (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false) {
                    echo json_encode(['status'=>'success', 'redirect'=>'dashboard.php']); exit;
                }
                header('Location: dashboard.php');
                exit;
            }
        }
    }

    if ($error && isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false) {
        echo json_encode(['status'=>'error', 'message'=>$error]);
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php $pageTitle = "Create Account — FamGateway"; include 'includes/header.php'; ?>
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
<style>
  * { box-sizing: border-box; margin: 0; padding: 0; }
  body { display: flex; min-height: 100vh; background: #f6f8fb; color: #0f172a; font-family: 'Poppins', sans-serif; }
  .auth-left {
    display: none;
    flex: 0 0 460px;
    background: linear-gradient(160deg, #0f172a 0%, #1e3a8a 60%, #1d4ed8 100%);
    position: relative; overflow: hidden;
    padding: 48px 52px;
    flex-direction: column; justify-content: space-between;
  }
  @media (min-width: 900px) { .auth-left { display: flex; } }
  .auth-left-bg {
    position: absolute; inset: 0;
    background: radial-gradient(ellipse at 30% 20%, rgba(59,130,246,0.25) 0%, transparent 55%),
                radial-gradient(ellipse at 80% 80%, rgba(16,185,129,0.15) 0%, transparent 50%);
  }
  .auth-left-grid {
    position: absolute; inset: 0;
    background-image: linear-gradient(rgba(255,255,255,0.03) 1px, transparent 1px),
                      linear-gradient(90deg, rgba(255,255,255,0.03) 1px, transparent 1px);
    background-size: 40px 40px;
  }
  .auth-left-content { position: relative; z-index: 1; }
  .auth-left-brand { display: flex; align-items: center; gap: 12px; margin-bottom: 52px; }
  .auth-left-brand-icon {
    width: 38px; height: 38px; border-radius: 11px;
    background: rgba(255,255,255,0.12); border: 1px solid rgba(255,255,255,0.15);
    display: flex; align-items: center; justify-content: center;
  }
  .auth-left-brand-name { font-size: 16px; font-weight: 700; color: #f8fafc; }
  .auth-left-heading { font-size: 36px; font-weight: 800; line-height: 1.2; letter-spacing: -1px; color: #fff; margin-bottom: 18px; }
  .auth-left-heading span { background: linear-gradient(90deg, #34d399, #60a5fa); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; }
  .auth-left-desc { font-size: 15px; color: #94a3b8; line-height: 1.65; margin-bottom: 40px; }
  .auth-features { display: flex; flex-direction: column; gap: 14px; }
  .auth-feature { display: flex; align-items: center; gap: 14px; font-size: 14px; color: #e2e8f0; }
  .auth-feature-dot {
    width: 28px; height: 28px; border-radius: 50%;
    background: rgba(52,211,153,0.15); border: 1px solid rgba(52,211,153,0.3);
    display: flex; align-items: center; justify-content: center; flex-shrink: 0; color: #34d399;
  }
  .auth-left-footer { position: relative; z-index: 1; font-size: 12px; color: #475569; }

  .auth-right {
    flex: 1; display: flex; flex-direction: column;
    justify-content: center; align-items: center;
    padding: 40px 24px; background: #f6f8fb; position: relative; overflow-y: auto;
  }
  .auth-back {
    position: absolute; top: 24px; left: 24px;
    display: flex; align-items: center; gap: 6px;
    font-size: 13px; font-weight: 500; color: #64748b;
    text-decoration: none; transition: color 0.15s;
    padding: 7px 12px; border-radius: 9px;
    border: 1px solid #e2e8f0; background: #ffffff;
    box-shadow: 0 1px 2px rgba(0,0,0,0.04);
  }
  .auth-back:hover { color: #0f172a; background: #f1f5f9; }
  .auth-form-card {
    width: 100%; max-width: 440px;
    background: #ffffff;
    border: 1px solid #e2e8f0;
    border-radius: 20px;
    padding: 38px 34px;
    box-shadow: 0 12px 32px -4px rgba(15, 23, 42, 0.08), 0 4px 12px -2px rgba(15, 23, 42, 0.04);
  }
  @media (max-width: 600px) {
    .auth-back { position: relative; top: auto; left: auto; align-self: flex-start; margin-bottom: 16px; }
    .auth-form-card { padding: 28px 20px; border-radius: 16px; margin-top: 0; }
  }
  .auth-form-header { margin-bottom: 24px; text-align: center; }
  .auth-form-logo { width: 42px; height: 42px; border-radius: 12px; background: linear-gradient(135deg, #2563eb, #059669); display: flex; align-items: center; justify-content: center; margin: 0 auto 18px auto; box-shadow: 0 4px 14px rgba(37,99,235,0.3); }
  .auth-form-title { font-size: 22px; font-weight: 800; letter-spacing: -0.5px; color: #0f172a; margin-bottom: 5px; }
  .auth-form-subtitle { font-size: 14px; color: #64748b; }
  .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
  .form-group { margin-bottom: 14px; }
  .form-label { display: block; font-size: 13px; font-weight: 500; color: #334155; margin-bottom: 6px; }
  .form-input { width: 100%; padding: 11px 14px; border: 1px solid #e2e8f0; border-radius: 10px; font-size: 14px; color: #0f172a; background: #f8fafc; transition: all 0.15s; outline: none; font-family: 'Poppins', sans-serif; }
  .form-input:focus { border-color: #2563eb; background: #fff; box-shadow: 0 0 0 3px rgba(37,99,235,0.12); }
  .form-input::placeholder { color: #94a3b8; }
  .phone-input-wrapper { display: flex; align-items: center; border: 1px solid #e2e8f0; border-radius: 10px; background: #f8fafc; transition: all 0.15s; }
  .phone-input-wrapper:focus-within { border-color: #2563eb; background: #fff; box-shadow: 0 0 0 3px rgba(37,99,235,0.12); }
  .phone-prefix { padding: 11px 0 11px 14px; font-size: 14px; color: #64748b; font-weight: 500; user-select: none; }
  .phone-input-wrapper input { width: 100%; padding: 11px 14px 11px 8px; border: none; outline: none; background: transparent; font-size: 14px; color: #0f172a; font-family: 'Poppins', sans-serif; }
  .phone-input-wrapper input::placeholder { color: #94a3b8; }
  .btn-auth { width: 100%; padding: 13px; background: #2563eb; color: #fff; border: none; border-radius: 12px; font-size: 15px; font-weight: 600; cursor: pointer; transition: all 0.15s; box-shadow: 0 2px 8px rgba(37,99,235,0.3); margin-top: 6px; font-family: 'Poppins', sans-serif; }
  .btn-auth:hover { background: #1d4ed8; transform: translateY(-1px); box-shadow: 0 4px 16px rgba(37,99,235,0.4); }
  .btn-auth:active { transform: none; box-shadow: none; }
  .auth-switch { text-align: center; margin-top: 20px; font-size: 14px; color: #64748b; }
  .auth-switch a { color: #2563eb; font-weight: 600; text-decoration: none; }
  .auth-switch a:hover { text-decoration: underline; }
  .alert-error { background: #fee2e2; border: 1px solid #fca5a5; color: #dc2626; padding: 12px 14px; border-radius: 10px; font-size: 13px; margin-bottom: 18px; display: flex; align-items: center; gap: 8px; }
  .terms-note { font-size: 12px; color: #94a3b8; text-align: center; margin-top: 14px; line-height: 1.6; }
</style>
</head>
<body>

<div class="auth-left">
  <div class="auth-left-bg"></div>
  <div class="auth-left-grid"></div>
  <div class="auth-left-content dash-anim-in" style="opacity:1; animation: dashFadeIn 0.8s ease forwards;">
    <div class="auth-left-brand">
      <img src="assets/img/logo-navbar-bright.png" alt="FamGateway" style="height:30px;width:auto;display:block;object-fit:contain;">
    </div>
    <h1 class="auth-left-heading">Get started<br><span>in minutes.</span></h1>
    <p class="auth-left-desc">Create a free account and start accepting UPI payments through our API instantly.</p>
    <div class="auth-features">
      <div class="auth-feature"><div class="auth-feature-dot"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg></div>Free forever — zero platform fees</div>
      <div class="auth-feature"><div class="auth-feature-dot"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg></div>Connect FamPay Gmail in 30 seconds</div>
      <div class="auth-feature"><div class="auth-feature-dot"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg></div>Instant API key & live webhook alerts</div>
    </div>
  </div>
  <div class="auth-left-footer">© <?= date('Y') ?> Aryanispe FamGateway</div>
</div>

<div class="auth-right">
  <a href="index.php" class="auth-back">
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
    Home
  </a>
  <div class="auth-form-card dash-anim-up" style="opacity:1; animation: dashFadeUp 0.6s cubic-bezier(.22,1,.36,1) forwards;">
    <div class="auth-form-header">
      <div class="auth-form-logo" style="background:none;box-shadow:none;width:auto;height:auto;">
        <img src="assets/img/logo-navbar-bright.png" alt="FamGateway" style="height:28px;width:auto;display:block;object-fit:contain;filter:invert(1) hue-rotate(180deg);">
      </div>
      <h2 class="auth-form-title">Create your account</h2>
      <a href="auth-google.php" class="btn-auth" style="background: #fff; color: #334155; border: 1px solid #e2e8f0; display: flex; align-items: center; justify-content: center; gap: 10px; margin-bottom: 20px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); text-decoration: none;">
      <svg width="20" height="20" viewBox="0 0 48 48">
        <path fill="#EA4335" d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z"/>
        <path fill="#4285F4" d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z"/>
        <path fill="#FBBC05" d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z"/>
        <path fill="#34A853" d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z"/>
      </svg>
      Continue with Google
    </a>

    <div style="display: flex; align-items: center; margin-bottom: 20px;">
      <div style="flex-grow: 1; height: 1px; background: #e2e8f0;"></div>
      <span style="padding: 0 12px; font-size: 13px; color: #64748b;">or sign up with email</span>
      <div style="flex-grow: 1; height: 1px; background: #e2e8f0;"></div>
    </div>
      <p class="auth-form-subtitle">Free forever. No credit card required.</p>
    </div>

    <?php if ($error): ?>
    <div class="alert-error">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
      <?= htmlspecialchars($error) ?>
    </div>
    <?php endif; ?>

    <form method="POST" action="register.php" id="registerForm">
      <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
      <input type="hidden" name="action" value="register">
      <div class="form-group">
        <label class="form-label">Full Name</label>
        <input type="text" name="name" class="form-input" placeholder="Aryan Gupta" required autofocus autocomplete="name">
      </div>
      <div class="form-group">
        <label class="form-label">Email address</label>
        <input type="email" name="email" class="form-input" placeholder="you@example.com" required autocomplete="email">
      </div>
      <div class="form-group">
        <label class="form-label">Phone Number (WhatsApp)</label>
        <div class="phone-input-wrapper">
          <span class="phone-prefix">+91</span>
          <input type="tel" name="phone" placeholder="9876543210" pattern="[0-9]{10}" title="Please enter a valid 10-digit mobile number" required autocomplete="tel">
        </div>
      </div>
      <div class="form-group">
        <label class="form-label">Password</label>
        <div style="position: relative;">
          <input type="password" name="password" class="form-input" placeholder="Min. 6 characters" required autocomplete="new-password" style="padding-right: 40px;">
          <button type="button" onclick="togglePassword(this)" style="position: absolute; right: 12px; top: 50%; transform: translateY(-50%); background: none; border: none; cursor: pointer; color: #64748b; padding: 4px; display: flex;">
            <svg class="eye-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>
            <svg class="eye-off-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:none;"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path><line x1="1" y1="1" x2="23" y2="23"></line></svg>
          </button>
        </div>
      </div>
      <div class="form-group">
        <label class="form-label">Confirm Password</label>
        <div style="position: relative;">
          <input type="password" name="confirm_password" class="form-input" placeholder="Repeat password" required autocomplete="new-password" style="padding-right: 40px;">
          <button type="button" onclick="togglePassword(this)" style="position: absolute; right: 12px; top: 50%; transform: translateY(-50%); background: none; border: none; cursor: pointer; color: #64748b; padding: 4px; display: flex;">
            <svg class="eye-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>
            <svg class="eye-off-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:none;"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path><line x1="1" y1="1" x2="23" y2="23"></line></svg>
          </button>
        </div>
      </div>
      <?php if (defined('TURNSTILE_SITE_KEY') && TURNSTILE_SITE_KEY): ?>
      <div class="cf-turnstile" data-sitekey="<?= TURNSTILE_SITE_KEY ?>" style="margin-bottom: 14px; display: flex; justify-content: center;"></div>
      <?php endif; ?>
      <button type="submit" class="btn-auth" id="registerBtn">Create Account →</button>
      
      <p class="auth-switch">Already have an account? <a href="login.php">Sign in</a></p>
      <p class="terms-note">By creating an account, you agree to our <a href="terms.php" target="_blank" style="color: var(--color-primary); text-decoration: none;">Terms of Service</a> and <a href="privacy.php" target="_blank" style="color: var(--color-primary); text-decoration: none;">Privacy Policy</a>.</p>
    </form>

    <!-- OTP Form (Hidden by default) -->
    <form method="POST" action="register.php" id="otpForm" style="display:none;">
      <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
      <input type="hidden" name="action" value="verify_otp">
      <div class="alert-success" style="background: #dcfce7; border: 1px solid #bbf7d0; color: #166534; padding: 12px 14px; border-radius: 10px; font-size: 13px; margin-bottom: 18px; display: flex; align-items: center; gap: 8px;">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>
        OTP sent to your email!
      </div>
      <div class="form-group">
        <label class="form-label">Enter 6-digit OTP</label>
        <input type="text" name="otp" class="form-input" placeholder="123456" required autocomplete="off" maxlength="6" style="text-align: center; letter-spacing: 4px; font-size: 18px; font-weight: bold;">
      </div>
      <button type="submit" class="btn-auth" id="otpBtn">Verify & Complete Registration</button>
      <p class="auth-switch"><a href="#" onclick="window.location.reload(); return false;">← Go Back</a></p>
    </form>
  </div>
</div>

<script>
function togglePassword(btn) {
    const input = btn.previousElementSibling;
    const eye = btn.querySelector('.eye-icon');
    const eyeOff = btn.querySelector('.eye-off-icon');
    if (input.type === 'password') {
        input.type = 'text';
        eye.style.display = 'none';
        eyeOff.style.display = 'block';
    } else {
        input.type = 'password';
        eye.style.display = 'block';
        eyeOff.style.display = 'none';
    }
}

if (window.lucide) { lucide.createIcons(); }

// Helper function to handle form submissions
async function handleFormSubmit(form, btn, loadingText, successAction) {
    const originalText = btn.innerHTML;
    btn.innerHTML = '<svg class="spin-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg> ' + loadingText;
    btn.style.opacity = '0.8';
    btn.disabled = true;

    try {
        const formData = new FormData(form);
        const [res] = await Promise.all([
            fetch('/register.php', {
                method: 'POST',
                body: formData,
                credentials: 'same-origin',
                headers: { 'Accept': 'application/json' }
            }),
            new Promise(r => setTimeout(r, 800)) // Artificial delay
        ]);
        
        const textData = await res.text();
        try {
            const data = JSON.parse(textData);
            successAction(data, form, btn, originalText);
        } catch(parseErr) {
            alert("Server returned non-JSON response:\n\n" + textData.substring(0, 500));
            if (typeof turnstile !== 'undefined') turnstile.reset();
            btn.innerHTML = originalText;
            btn.disabled = false;
            btn.style.opacity = '1';
        }
    } catch(err) {
        alert("Network Error (Fetch failed). Please try again.");
        if (typeof turnstile !== 'undefined') turnstile.reset();
        btn.innerHTML = originalText;
        btn.disabled = false;
        btn.style.opacity = '1';
    }
}

document.getElementById('registerForm')?.addEventListener('submit', function(e) {
    e.preventDefault();
    handleFormSubmit(this, document.getElementById('registerBtn'), 'Sending OTP...', (data, form, btn, originalText) => {
        if (data.status === 'otp_required') {
            // Hide register form, show OTP form
            form.style.display = 'none';
            document.getElementById('otpForm').style.display = 'block';
            document.querySelector('.auth-form-title').innerText = 'Check your email';
            document.querySelector('.auth-form-subtitle').innerText = 'We sent a 6-digit code to ' + form.email.value;
            
            // Remove any old errors on the register form
            const oldErr = form.parentElement.querySelector('.alert-error');
            if (oldErr) oldErr.remove();
        } else if (data.status === 'error') {
            showError(form, data.message);
            if (typeof turnstile !== 'undefined') turnstile.reset();
            btn.innerHTML = originalText;
            btn.disabled = false;
            btn.style.opacity = '1';
        }
    });
});

document.getElementById('otpForm')?.addEventListener('submit', function(e) {
    e.preventDefault();
    handleFormSubmit(this, document.getElementById('otpBtn'), 'Verifying...', (data, form, btn, originalText) => {
        if (data.status === 'success') {
            btn.innerHTML = originalText;
            
            const successDiv = document.createElement('div');
            successDiv.className = 'callout callout-success dash-anim-up';
            successDiv.style.animation = 'dashFadeUp 0.4s ease forwards';
            successDiv.innerHTML = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg> <div style="display:flex; flex-direction:column; gap:2px;"><b style="font-size:14px;color:#166534;">Account Created Successfully!</b><span style="color:#15803d;font-size:12.5px;">Redirecting to your dashboard...</span></div>';
            
            const oldErr = form.parentElement.querySelector('.alert-error');
            if (oldErr) oldErr.remove();
            
            form.parentNode.insertBefore(successDiv, form);
            
            form.style.transition = 'opacity 0.4s';
            form.style.opacity = '0.3';
            form.style.pointerEvents = 'none';

            setTimeout(() => window.location.href = data.redirect, 2500);
        } else {
            showError(form, data.message);
            btn.innerHTML = originalText;
            btn.disabled = false;
            btn.style.opacity = '1';
        }
    });
});

function showError(form, message) {
    const errDiv = document.createElement('div');
    errDiv.className = 'alert-error';
    errDiv.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg> ' + (message || 'Error occurred');
    
    const oldErr = form.parentElement.querySelector('.alert-error');
    if (oldErr) oldErr.remove();
    
    form.parentNode.insertBefore(errDiv, form);
}
</script>
</body>
</html>

