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

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

$error = '';
$step = isset($_GET['step']) ? (int)$_GET['step'] : 1;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($step === 1) {
        $username = trim($_POST['username'] ?? '');
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        
        if (empty($username) || empty($name) || empty($email)) {
            $error = 'Please fill in all fields.';
        } elseif (!preg_match('/^[a-zA-Z0-9_]{3,20}$/', $username)) {
            $error = 'Username must be 3-20 characters (letters, numbers, underscore only).';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Please enter a valid email address.';
        } elseif (isUsernameTaken($username)) {
            $error = 'This username is already taken. Try another.';
        } elseif (getUserByEmail($email)) {
            $error = 'An account with this email already exists.';
        } else {
            $otp = saveOTP($email, 'register');
            if (!sendOTPEmail($email, $otp, 'register')) {
                $error = 'Email bhejne mein problem aa rahi hai. Thodi der baad try karo ya support se contact karo.';
            } else {
                $_SESSION['reg_username'] = $username;
                $_SESSION['reg_name'] = $name;
                $_SESSION['reg_email'] = $email;
                $step = 2;
            }
        }
    } elseif ($step === 2) {
        $otp = trim($_POST['otp'] ?? '');
        $email = $_SESSION['reg_email'] ?? '';
        
        if (empty($email)) {
            $error = 'Session expire ho gaya. Dobara shuru karo — naya OTP aayega usi pe click karke.';
            $step = 1;
        } elseif (empty($otp)) {
            $error = 'Please enter the verification code.';
        } elseif (strlen($otp) !== 6) {
            $error = 'Verification code must be 6 digits.';
        } elseif (!verifyOTP($email, $otp, 'register')) {
            $error = 'Invalid or expired code. Dhyan do: sabse NAYA wala mail ka hi code daalo.';
        } else {
            $step = 3;
        }
    } elseif ($step === 3) {
        $password = $_POST['password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';
        
        if (empty($password) || empty($confirmPassword)) {
            $error = 'Please fill in all fields.';
        } elseif (strlen($password) < 6) {
            $error = 'Password must be at least 6 characters.';
        } elseif ($password !== $confirmPassword) {
            $error = 'Passwords do not match.';
        } else {
            $userId = generateUserId();
            $apiKey = generateApiKey();
            $now = nowIST();
            $username = $_SESSION['reg_username'] ?? '';
            $name = $_SESSION['reg_name'] ?? '';
            $email = $_SESSION['reg_email'] ?? '';
            
            $newUser = [
                'id' => $userId,
                'username' => $username,
                'name' => $name,
                'email' => $email,
                'password_hash' => password_hash($password, PASSWORD_DEFAULT),
                'created_at' => $now->format('Y-m-d H:i:s'),
                'fampay_gmail' => '',
                'fampay_app_password_encrypted' => '',
                'fampay_upi_id' => '',
                'gmail_connected' => false,
                'api_key' => $apiKey,
                'api_keys' => [
                    ['key' => $apiKey, 'label' => 'Default', 'created_at' => $now->format('Y-m-d H:i:s')]
                ],
                'reset_chances' => 10,
                'avatar' => '',
                'plan_id' => 'trial',
                'plan_label' => '1 Day Free Trial',
                'plan_expires_at' => $now->modify('+1 day')->format('Y-m-d H:i:s'),
                'total_requests' => 0,
                'total_success' => 0,
                'total_failed' => 0,
                'total_amount_received' => 0,
                'status' => 'active',
                'webhook_url' => '',
                'qr_center_image' => 0,
                'email_verified' => 1
            ];
            
            saveUser($newUser);
            $_SESSION['user_id'] = $userId;
            unset($_SESSION['reg_username'], $_SESSION['reg_name'], $_SESSION['reg_email']);
            header('Location: dashboard.php');
            exit;
        }
    }
}

$pageTitle = 'Create Account';
$metaDesc = 'Create your free FamAPI account. Get instant access to UPI payment API with 1-day free trial.';
include __DIR__ . '/includes/public_header.php';
?>
<style>
.auth-page{min-height:100vh;display:flex;align-items:center;justify-content:center;padding:40px 20px;background:var(--soft)}
.auth-card{width:100%;max-width:420px;background:#fff;border:1px solid var(--line);border-radius:16px;box-shadow:var(--shadow-md);padding:40px 32px}
.auth-header{text-align:center;margin-bottom:32px}
.auth-logo{display:inline-flex;align-items:center;gap:10px;font-weight:800;font-size:22px;color:var(--ink);margin-bottom:16px}
.auth-logo .brand-accent{color:var(--brand)}
.auth-title{font-size:26px;font-weight:800;color:var(--ink);letter-spacing:-.5px;margin-bottom:8px}
.auth-sub{font-size:15px;color:var(--muted)}
.step-indicator{display:flex;justify-content:center;gap:8px;margin-bottom:28px}
.step-dot{width:40px;height:4px;border-radius:2px;background:var(--line);transition:all .3s}
.step-dot.active{background:var(--brand);width:60px}
.step-dot.done{background:var(--green)}
.auth-form{display:flex;flex-direction:column;gap:20px}
.form-group{display:flex;flex-direction:column;gap:6px}
.form-label{font-size:13px;font-weight:600;color:var(--ink)}
.form-input{padding:12px 14px;border:1.5px solid var(--line);border-radius:10px;font-size:15px;font-family:inherit;color:var(--ink);background:#fff;transition:all .2s ease;outline:none}
.form-input:focus{border-color:var(--brand);box-shadow:0 0 0 3px rgba(163,112,252,.15)}
.form-input::placeholder{color:var(--muted-soft)}
.btn-submit{padding:14px 24px;font-size:15px;font-weight:700;border-radius:10px;margin-top:8px}
.otp-inputs{display:flex;gap:8px;justify-content:center}
.otp-inputs input{width:48px;height:56px;text-align:center;font-size:22px;font-weight:700;border:2px solid var(--line);border-radius:12px;background:var(--soft);color:var(--ink);transition:border-color .2s}
.otp-inputs input:focus{border-color:var(--brand);outline:none}
.alert{padding:12px 14px;border-radius:10px;font-size:13.5px;font-weight:500;margin-bottom:20px}
.alert-error{background:#fef2f2;border:1px solid #fecaca;color:#dc2626}
.auth-back{text-align:center;margin-top:24px;font-size:14px;color:var(--muted)}
.auth-back a{color:var(--brand);font-weight:600;text-decoration:none}
.auth-back a:hover{text-decoration:underline}
</style>

<div class="auth-page">
  <div class="auth-card">
    <div class="auth-header">
      <a href="index.php" class="auth-logo">
        <svg width="32" height="32" viewBox="0 0 32 32" fill="none"><rect width="32" height="32" rx="8" fill="#a370fc"/><path d="M8 12l-3 3 3 3M24 12l3 3-3 3M21 8l-2 12" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
        Fam<span class="brand-accent">API</span>
      </a>
      <h1 class="auth-title"><?= $step === 1 ? 'Create your account' : ($step === 2 ? 'Verify your email' : 'Set your password') ?></h1>
      <p class="auth-sub">
        <?= $step === 1 ? 'Free 1-day trial included. No card required.' : ($step === 2 ? 'We sent a 6-digit code to <strong>' . htmlspecialchars($_SESSION['reg_email'] ?? '') . '</strong>' : 'Almost done! Create a password for your account.') ?>
      </p>
    </div>

    <?php if ($error): ?>
      <div class="alert alert-error"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <form method="POST" action="register.php?step=<?= $step ?>" class="auth-form">
      <?php if ($step === 1): ?>
        <div class="form-group">
          <label class="form-label" for="username">Username</label>
          <input class="form-input" type="text" id="username" name="username" placeholder="Choose a username" value="<?= htmlspecialchars($_POST['username'] ?? '') ?>" required pattern="[a-zA-Z0-9_]{3,20}" title="3-20 characters, letters, numbers, underscore">
        </div>
        <div class="form-group">
          <label class="form-label" for="name">Full Name</label>
          <input class="form-input" type="text" id="name" name="name" placeholder="Your Name" value="<?= htmlspecialchars($_POST['name'] ?? '') ?>" required>
        </div>
        <div class="form-group">
          <label class="form-label" for="email">Gmail Address</label>
          <input class="form-input" type="email" id="email" name="email" placeholder="you@gmail.com" value="<?= htmlspecialchars($_POST['email'] ?? '') ?>" required>
        </div>
        <button type="submit" class="btn btn-primary btn-block btn-submit">Continue & Verify Email</button>

      <?php elseif ($step === 2): ?>
        <div class="otp-inputs">
          <input type="text" maxlength="1" class="otp-digit" data-index="0" required autofocus>
          <input type="text" maxlength="1" class="otp-digit" data-index="1" required>
          <input type="text" maxlength="1" class="otp-digit" data-index="2" required>
          <input type="text" maxlength="1" class="otp-digit" data-index="3" required>
          <input type="text" maxlength="1" class="otp-digit" data-index="4" required>
          <input type="text" maxlength="1" class="otp-digit" data-index="5" required>
        </div>
        <input type="hidden" name="otp" id="otpHidden">
        <button type="submit" class="btn btn-primary btn-block btn-submit">Verify Code</button>
        <p style="text-align:center;margin-top:16px;font-size:13px;color:var(--muted);">
          Didn't receive code? <a href="register.php?step=1" style="font-weight:600;">Try again</a>
        </p>

      <?php elseif ($step === 3): ?>
        <div class="form-group">
          <label class="form-label" for="password">Password</label>
          <input class="form-input" type="password" id="password" name="password" placeholder="At least 6 characters" required>
        </div>
        <div class="form-group">
          <label class="form-label" for="confirm_password">Confirm Password</label>
          <input class="form-input" type="password" id="confirm_password" name="confirm_password" placeholder="Re-enter password" required>
        </div>
        <button type="submit" class="btn btn-primary btn-block btn-submit">Create Account & Continue</button>
      <?php endif; ?>
    </form>

    <div class="auth-back">
      <a href="register.php?step=1">← Back to start</a>
    </div>
  </div>
</div>

<script>
document.querySelectorAll('.otp-digit').forEach((input, index, inputs) => {
  input.addEventListener('input', (e) => {
    if (e.target.value.length === 1 && index < inputs.length - 1) {
      inputs[index + 1].focus();
    }
    updateOTP();
  });
  input.addEventListener('keydown', (e) => {
    if (e.key === 'Backspace' && !e.target.value && index > 0) {
      inputs[index - 1].focus();
    }
  });
  input.addEventListener('paste', (e) => {
    e.preventDefault();
    const paste = (e.clipboardData || window.clipboardData).getData('text').trim();
    if (/^\d{6}$/.test(paste)) {
      inputs.forEach((inp, i) => inp.value = paste[i]);
      inputs[5].focus();
      updateOTP();
    }
  });
});
function updateOTP() {
  const digits = Array.from(document.querySelectorAll('.otp-digit')).map(i => i.value).join('');
  document.getElementById('otpHidden').value = digits;
}
</script>

<?php include __DIR__ . '/includes/public_footer.php'; ?>