<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

if (!defined('VALID_ACCESS')) { include(__DIR__ . '/include/config.php'); }

if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true) {
    header('Location: ' . $site_data['web_url'] . '/user/dashboard'); exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    require_once('include/pocketfi.php');
    if (empty($_POST['csrf_token']) || !isset($_SESSION['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        $_SESSION['error'] = "Invalid request. Please try again."; header('Location: ' . $site_data['web_url'] . '/signup'); exit();
    }
    unset($_SESSION['csrf_token']);

    $captcha_answer = isset($_POST['captcha_answer']) ? intval($_POST['captcha_answer']) : -1;
    $captcha_expected = isset($_SESSION['captcha_result']) ? intval($_SESSION['captcha_result']) : null;
    unset($_SESSION['captcha_result']);
    if ($captcha_expected === null || $captcha_answer !== $captcha_expected) {
        $_SESSION['error'] = "Incorrect captcha answer. Please try again."; header('Location: ' . $site_data['web_url'] . '/signup'); exit();
    }

    $username = trim($_POST['RegistrationForm']['login']);
    $email = trim($_POST['RegistrationForm']['email']);
    $first_name = trim($_POST['RegistrationForm']['first_name']);
    $last_name = trim($_POST['RegistrationForm']['last_name']);
    $phone = trim($_POST['RegistrationForm']['phone']);
    $password = $_POST['RegistrationForm']['password'];
    $password_again = $_POST['RegistrationForm']['password_again'];
    $referral_code = isset($_POST['referral_code']) ? trim($_POST['referral_code']) : '';

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $_SESSION['error'] = "Please enter a valid email address!"; header('Location: ' . $site_data['web_url'] . '/signup'); exit(); }
    try { $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ? LIMIT 1"); $stmt->execute([$email]); if ($stmt->fetch()) { $_SESSION['error'] = "This email is already registered."; header('Location: ' . $site_data['web_url'] . '/signup'); exit(); } } catch (PDOException $e) { $_SESSION['error'] = "Registration failed."; header('Location: ' . $site_data['web_url'] . '/signup'); exit(); }
    if (empty($phone) || !preg_match('/^\+?[0-9]{7,15}$/', $phone)) { $_SESSION['error'] = "Please enter a valid phone number!"; header('Location: ' . $site_data['web_url'] . '/signup'); exit(); }

    $full_name = trim($first_name . ' ' . $last_name);
    if ($password !== $password_again) { $_SESSION['error'] = "Passwords do not match!"; header('Location: ' . $site_data['web_url'] . '/signup'); exit(); }
    if (strlen($password) < 8) { $_SESSION['error'] = "Password must be at least 8 characters!"; header('Location: ' . $site_data['web_url'] . '/signup'); exit(); }

    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
    $new_user_referral_code = $username;
    $referrer_id = null;
    if (!empty($referral_code)) { try { $stmt = $pdo->prepare("SELECT id FROM users WHERE referral_code = ?"); $stmt->execute([$referral_code]); $referrer = $stmt->fetch(PDO::FETCH_ASSOC); if ($referrer) $referrer_id = $referrer['id']; } catch (PDOException $e) {} }

    try {
        $stmt = $pdo->prepare("INSERT INTO users (username, email, password, full_name, phone, referral_code, email_verified) VALUES (?, ?, ?, ?, ?, ?, 1)");
        $stmt->execute([$username, $email, $hashedPassword, $full_name, $phone, $new_user_referral_code]);
        $new_user_id = $pdo->lastInsertId();
        if (intval($site_data['pocketfi_enabled'] ?? 0) === 1) { $pocketfi_result = createPocketfiVirtualAccount($pdo, $site_data, $new_user_id, $full_name, $email, $phone); if (!$pocketfi_result['success']) { error_log("[Signup] Pocketfi failed for user {$new_user_id}: " . $pocketfi_result['message']); } }
        if ($referrer_id) { try { $pdo->prepare("INSERT INTO referrals (referrer_id, referred_user_id, referral_code, status) VALUES (?, ?, ?, 'pending')")->execute([$referrer_id, $new_user_id, $referral_code]); } catch (PDOException $e) {} }

        // Send welcome email
        $welcome_subject = "Welcome to " . WEB_NAME;
        $welcome_message = "<html><body style='font-family:sans-serif;max-width:600px;margin:0 auto;padding:20px'>"
            . "<div style='background:#4D148C;padding:25px;text-align:center;border-radius:8px 8px 0 0'>"
            . "<h1 style='color:#fff;margin:0;font-size:28px;'>Welcome to " . htmlspecialchars(WEB_NAME) . "</h1></div>"
            . "<div style='background:#f9f9f9;padding:30px;border:1px solid #e0e0e0;border-top:none;border-radius:0 0 8px 8px;'>"
            . "<p style='font-size:16px;color:#333;margin-bottom:20px;'>Hi " . htmlspecialchars($first_name ?: $username) . ",</p>"
            . "<p style='font-size:14px;color:#555;line-height:1.7;margin-bottom:20px;'>Thanks for joining " . htmlspecialchars(WEB_NAME) . ". Your account is now active, and you can start using our services right away.</p>"
            . "<p style='font-size:14px;color:#555;line-height:1.7;margin-bottom:25px;'>Visit your dashboard to explore services, fund your wallet, and place orders.</p>"
            . "<a href='" . htmlspecialchars($site_data['web_url']) . "/user/dashboard' style='display:inline-block;padding:12px 24px;background:#4D148C;color:#fff;text-decoration:none;border-radius:8px;font-weight:700;'>Go to Dashboard</a>"
            . "<p style='font-size:12px;color:#999;margin-top:25px;'>If you need help, reply to this email or visit our support page.</p>"
            . "</div></body></html>";

        $welcome_sent = send_system_email($email, $welcome_subject, $welcome_message, $pdo, $site_data);
        if (!$welcome_sent) {
            error_log("[Signup] Welcome email failed for {$email}");
        }

        $_SESSION['logged_in'] = true;
        $_SESSION['verified'] = true;
        $_SESSION['email'] = $email;
        $_SESSION['user_id'] = $new_user_id;
        header('Location: ' . $site_data['web_url'] . '/user/dashboard'); exit();
    } catch (PDOException $e) {
        if ($e->getCode() == 23000) {
            if (strpos($e->getMessage(), 'username') !== false) $_SESSION['error'] = "Username already taken!";
            elseif (strpos($e->getMessage(), 'email') !== false) $_SESSION['error'] = "Email already registered!";
            elseif (strpos($e->getMessage(), 'phone') !== false) $_SESSION['error'] = "Phone number already registered!";
            elseif (strpos($e->getMessage(), 'referral_code') !== false) $_SESSION['error'] = "Username already in use.";
            else $_SESSION['error'] = "Registration failed.";
        } else $_SESSION['error'] = "Registration failed.";
        header('Location: ' . $site_data['web_url'] . '/signup'); exit();
    }
}

$referral_from_url = isset($_GET['ref']) ? htmlspecialchars($_GET['ref']) : '';
if (empty($_SESSION['csrf_token'])) $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
$csrf_token = $_SESSION['csrf_token'];

$captcha_num1 = rand(1, 15); $captcha_num2 = rand(1, 10);
$captcha_op = rand(0, 1) ? '+' : '-';
if ($captcha_op === '-' && $captcha_num1 < $captcha_num2) { $tmp = $captcha_num1; $captcha_num1 = $captcha_num2; $captcha_num2 = $tmp; }
$_SESSION['captcha_result'] = $captcha_op === '+' ? $captcha_num1 + $captcha_num2 : $captcha_num1 - $captcha_num2;
$captcha_question = $captcha_num1 . ' ' . $captcha_op . ' ' . $captcha_num2 . ' = ?';

$page_title = $site_data['web_name'] . " | Create Account";
include('include/header.php');
?>

<!-- Signup Page -->
<section class="py-12 px-4 sm:px-6 lg:px-8 max-w-7xl mx-auto flex flex-col lg:flex-row items-start gap-12">

  <!-- Left: Info -->
  <div class="flex-1 hidden lg:block sticky top-28">
    <div class="glassmorphism rounded-3xl p-10 shadow-premium">
      <h2 class="text-3xl font-extrabold text-slate-900 mb-4">Join <span class="text-accent"><?php echo htmlspecialchars($site_data['web_name']); ?></span></h2>
      <p class="text-slate-600 text-sm leading-relaxed mb-8">Create your free account and get instant access to all our digital services.</p>
      <div class="space-y-4">
        <div class="flex items-center gap-4 bg-slate-50 p-4 rounded-xl border border-slate-100">
          <div class="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center flex-shrink-0"><i class="fa-solid fa-rocket text-primary"></i></div>
          <div><h4 class="text-sm font-bold text-slate-800">Social Media Growth</h4><p class="text-xs text-slate-500">Instant followers, likes & views for all platforms</p></div>
        </div>
        <div class="flex items-center gap-4 bg-slate-50 p-4 rounded-xl border border-slate-100">
          <div class="w-10 h-10 rounded-xl bg-accent/10 flex items-center justify-center flex-shrink-0"><i class="fa-solid fa-bolt text-accent"></i></div>
          <div><h4 class="text-sm font-bold text-slate-800">Instant Delivery</h4><p class="text-xs text-slate-500">Orders processed in seconds, 24/7</p></div>
        </div>
        <div class="flex items-center gap-4 bg-slate-50 p-4 rounded-xl border border-slate-100">
          <div class="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center flex-shrink-0"><i class="fa-solid fa-wallet text-primary"></i></div>
          <div><h4 class="text-sm font-bold text-slate-800">Secure Wallet</h4><p class="text-xs text-slate-500">Fund once, order anytime. Balance never expires</p></div>
        </div>
      </div>
      <div class="grid grid-cols-3 gap-4 mt-8 pt-6 border-t border-slate-200">
        <div class="text-center"><p class="text-xl font-black text-primary">10K+</p><p class="text-[10px] text-slate-400 uppercase font-semibold">Users</p></div>
        <div class="text-center"><p class="text-xl font-black text-accent">50K+</p><p class="text-[10px] text-slate-400 uppercase font-semibold">Orders</p></div>
        <div class="text-center"><p class="text-xl font-black text-primary">99.9%</p><p class="text-[10px] text-slate-400 uppercase font-semibold">Uptime</p></div>
      </div>
    </div>
  </div>

  <!-- Right: Form -->
  <div class="w-full max-w-md">
    <div class="glassmorphism rounded-3xl p-8 shadow-premium">
      <div class="mb-6">
        <div class="inline-flex items-center gap-2 bg-primary/10 border border-primary/20 rounded-full px-3 py-1 mb-4">
          <span class="w-1.5 h-1.5 rounded-full bg-primary animate-pulse"></span>
          <span class="text-[10px] font-bold text-primary uppercase tracking-wider">New Account</span>
        </div>
        <h1 class="text-2xl font-extrabold text-slate-900">Create Account</h1>
        <p class="text-sm text-slate-500 mt-1">Fill in your details to get started</p>
      </div>

      <?php if (isset($_SESSION['error'])): ?>
      <div class="bg-red-50 border border-red-200 rounded-xl p-4 mb-4 flex items-center gap-3">
        <i class="fa-solid fa-circle-exclamation text-red-500"></i>
        <span class="text-sm text-red-800"><?php echo htmlspecialchars($_SESSION['error']); unset($_SESSION['error']); ?></span>
      </div>
      <?php endif; ?>

      <form action="" method="POST" id="signupForm">
        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">

        <div class="mb-4">
          <label class="block text-xs font-bold text-slate-600 uppercase tracking-wider mb-2">Username *</label>
          <div class="relative">
            <i class="fa-solid fa-user absolute left-4 top-1/2 -translate-y-1/2 text-primary/50 text-sm"></i>
            <input type="text" name="RegistrationForm[login]" required class="w-full bg-slate-50 border border-slate-200 rounded-xl pl-11 pr-4 py-3 text-sm text-slate-800 focus:outline-none focus:border-primary transition-all" placeholder="johndoe" autocomplete="username">
          </div>
          <p class="text-[11px] text-slate-400 mt-1">This will also be your referral code</p>
        </div>

        <div class="grid grid-cols-2 gap-3 mb-4">
          <div>
            <label class="block text-xs font-bold text-slate-600 uppercase tracking-wider mb-2">First Name *</label>
            <input type="text" name="RegistrationForm[first_name]" required class="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-3 text-sm text-slate-800 focus:outline-none focus:border-primary transition-all" placeholder="John">
          </div>
          <div>
            <label class="block text-xs font-bold text-slate-600 uppercase tracking-wider mb-2">Last Name *</label>
            <input type="text" name="RegistrationForm[last_name]" required class="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-3 text-sm text-slate-800 focus:outline-none focus:border-primary transition-all" placeholder="Doe">
          </div>
        </div>

        <div class="mb-4">
          <label class="block text-xs font-bold text-slate-600 uppercase tracking-wider mb-2">Email *</label>
          <div class="relative">
            <i class="fa-solid fa-envelope absolute left-4 top-1/2 -translate-y-1/2 text-primary/50 text-sm"></i>
            <input type="email" name="RegistrationForm[email]" required class="w-full bg-slate-50 border border-slate-200 rounded-xl pl-11 pr-4 py-3 text-sm text-slate-800 focus:outline-none focus:border-primary transition-all" placeholder="you@example.com" autocomplete="email">
          </div>
        </div>

        <div class="mb-4">
          <label class="block text-xs font-bold text-slate-600 uppercase tracking-wider mb-2">Phone *</label>
          <div class="relative">
            <i class="fa-solid fa-phone absolute left-4 top-1/2 -translate-y-1/2 text-primary/50 text-sm"></i>
            <input type="tel" name="RegistrationForm[phone]" id="phone" required class="w-full bg-slate-50 border border-slate-200 rounded-xl pl-11 pr-4 py-3 text-sm text-slate-800 focus:outline-none focus:border-primary transition-all" placeholder="09162671360" autocomplete="tel">
          </div>
          <p class="text-[11px] text-slate-400 mt-1">Include country code (e.g. 0...)</p>
        </div>

        <div class="mb-4">
          <label class="block text-xs font-bold text-slate-600 uppercase tracking-wider mb-2">Password *</label>
          <div class="relative">
            <i class="fa-solid fa-lock absolute left-4 top-1/2 -translate-y-1/2 text-primary/50 text-sm"></i>
            <input id="password" type="password" name="RegistrationForm[password]" required class="w-full bg-slate-50 border border-slate-200 rounded-xl pl-11 pr-12 py-3 text-sm text-slate-800 focus:outline-none focus:border-primary transition-all" placeholder="Min. 8 characters" oninput="checkMatch()" autocomplete="new-password">
            <button type="button" onclick="togglePw('password')" class="absolute right-3 top-1/2 -translate-y-1/2 w-8 h-8 rounded-lg bg-white border border-slate-200 flex items-center justify-center text-slate-400 hover:text-primary"><i class="fa-solid fa-eye text-xs"></i></button>
          </div>
        </div>

        <div class="mb-4">
          <label class="block text-xs font-bold text-slate-600 uppercase tracking-wider mb-2">Confirm Password *</label>
          <div class="relative">
            <i class="fa-solid fa-shield-halved absolute left-4 top-1/2 -translate-y-1/2 text-primary/50 text-sm"></i>
            <input id="password_again" type="password" name="RegistrationForm[password_again]" required class="w-full bg-slate-50 border border-slate-200 rounded-xl pl-11 pr-4 py-3 text-sm text-slate-800 focus:outline-none focus:border-primary transition-all" placeholder="Re-enter password" oninput="checkMatch()" autocomplete="new-password">
          </div>
          <p id="matchMsg" class="text-[11px] mt-1 hidden"></p>
        </div>

        <div class="mb-4">
          <label class="block text-xs font-bold text-slate-600 uppercase tracking-wider mb-2">Referral Code <span class="text-slate-400 font-normal normal-case">(optional)</span></label>
          <div class="relative">
            <i class="fa-solid fa-gift absolute left-4 top-1/2 -translate-y-1/2 text-primary/50 text-sm"></i>
            <input type="text" name="referral_code" class="w-full bg-slate-50 border border-slate-200 rounded-xl pl-11 pr-4 py-3 text-sm text-slate-800 focus:outline-none focus:border-primary transition-all" placeholder="Enter referral code" value="<?php echo $referral_from_url; ?>">
          </div>
        </div>

        <div class="mb-5">
          <label class="block text-xs font-bold text-slate-600 uppercase tracking-wider mb-2">Solve: <span class="text-primary text-sm ml-1"><?php echo $captcha_question; ?></span></label>
          <div class="relative">
            <i class="fa-solid fa-calculator absolute left-4 top-1/2 -translate-y-1/2 text-primary/50 text-sm"></i>
            <input type="number" name="captcha_answer" required class="w-full bg-slate-50 border border-slate-200 rounded-xl pl-11 pr-4 py-3 text-sm text-slate-800 focus:outline-none focus:border-primary transition-all" placeholder="Your answer" autocomplete="off">
          </div>
        </div>

        <button type="submit" id="submitBtn" class="w-full bg-primary hover:bg-primary-light text-white font-bold text-sm py-4 rounded-xl transition-all shadow-glow-purple flex items-center justify-center gap-2">
          <i class="fa-solid fa-user-plus"></i> <span id="btnText">Create Account</span>
        </button>
      </form>

      <div class="text-center mt-6 pt-5 border-t border-slate-200">
        <p class="text-sm text-slate-500">Already have an account? <a href="<?php echo $site_data['web_url']; ?>/signin" class="font-bold text-primary hover:text-accent transition-colors">Sign in →</a></p>
      </div>
    </div>
  </div>
</section>

<script>
function togglePw(id){var f=document.getElementById(id);f.type=f.type==='password'?'text':'password';}
function checkMatch(){
  var pw=document.getElementById('password').value,pc=document.getElementById('password_again').value,m=document.getElementById('matchMsg');
  if(!pc){m.classList.add('hidden');return;}
  m.classList.remove('hidden');
  if(pw===pc){m.textContent='✓ Passwords match';m.className='text-[11px] mt-1 text-green-600';}
  else{m.textContent='✗ Passwords do not match';m.className='text-[11px] mt-1 text-red-500';}
}
document.getElementById('signupForm').addEventListener('submit',function(e){
  var pw=document.getElementById('password').value,pc=document.getElementById('password_again').value;
  if(pw!==pc||pw.length<8){e.preventDefault();return;}
  var btn=document.getElementById('submitBtn');btn.disabled=true;btn.classList.add('opacity-50');
  document.getElementById('btnText').textContent='Creating account...';
});
</script>

<?php include('include/footer.php'); ?>
