<?php
session_start();
require 'config/db.php';

$success = ""; 
$error = "";

// 1. Check for Referral Code in URL
$ref_code_url = isset($_GET['ref']) ? trim($_GET['ref']) : '';

if (isset($_POST['register'])) {
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $password = $_POST['password'];
    $ref_code_input = trim($_POST['referral_code']); 
    
    // Check Email
    $check = $pdo->prepare("SELECT id FROM users WHERE email = ?");
    $check->execute([$email]);
    
    if ($check->rowCount() > 0) {
        $error = "Email already registered. Please login.";
    } else {
        $hash = password_hash($password, PASSWORD_DEFAULT);
        
        // Generate Unique Referral Code
        $my_ref_code = strtoupper(substr(str_replace(' ', '', $name), 0, 4) . rand(100, 999));

        // Find Referrer ID
        $referred_by = 0;
        if (!empty($ref_code_input)) {
            $refStmt = $pdo->prepare("SELECT id FROM users WHERE referral_code = ?");
            $refStmt->execute([$ref_code_input]);
            $referrer = $refStmt->fetch();
            if ($referrer) {
                $referred_by = $referrer['id'];
            }
        }

        // Insert User (Auto-Verified = 1)
        // We removed 'otp_code' and set 'is_verified' to 1 directly
        $stmt = $pdo->prepare("INSERT INTO users (name, email, phone, password_hash, referral_code, referred_by, is_verified) VALUES (?, ?, ?, ?, ?, ?, 1)");
        
        if ($stmt->execute([$name, $email, $phone, $hash, $my_ref_code, $referred_by])) {
            $new_user_id = $pdo->lastInsertId();

            // Log Referral
            if ($referred_by > 0) {
                $pdo->prepare("INSERT INTO referrals (referrer_id, referred_user_id, status) VALUES (?, ?, 'pending')")
                    ->execute([$referred_by, $new_user_id]);
            }

            // AUTO LOGIN AFTER REGISTRATION
            $_SESSION['user_id'] = $new_user_id;
            $_SESSION['user_name'] = $name;
            $_SESSION['role'] = 'user';
            $_SESSION['reseller_status'] = 'none';

            // Redirect to Dashboard
            header("Location: profile.php");
            exit();
        } else {
            $error = "Registration failed. Please try again.";
        }
    }
}

include 'includes/header.php'; 
?>

<style>
    .register-wrapper {
        background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
        min-height: 85vh;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 20px;
    }
    .register-card {
        background: rgba(255, 255, 255, 0.95);
        width: 100%;
        max-width: 400px;
        padding: 40px;
        border-radius: 20px;
        text-align: center;
        box-shadow: 0 20px 50px rgba(0,0,0,0.3);
    }
    .register-card h2 { color: #333; margin-bottom: 25px; font-weight: 800; }
    .styled-input { width: 100%; padding: 12px; border: 2px solid #eee; border-radius: 8px; margin-bottom: 15px; box-sizing: border-box; font-size: 14px; }
    .styled-input:focus { border-color: #38ef7d; outline: none; }
    .btn-register { width: 100%; padding: 14px; background: linear-gradient(to right, #11998e, #38ef7d); color: white; border: none; border-radius: 8px; font-weight: bold; cursor: pointer; box-shadow: 0 5px 15px rgba(17, 153, 142, 0.3); font-size: 16px; }
    .btn-register:hover { transform: scale(1.02); }
</style>

<div class="register-wrapper">
    <div class="register-card">
        <h2>Create Account</h2>

        <?php if($error): ?>
            <div style="background:#ffdddd; color:#c0392b; padding:10px; border-radius:5px; margin-bottom:20px;">
                <?php echo $error; ?>
            </div>
        <?php endif; ?>

        <form method="POST">
            <input type="text" name="name" class="styled-input" placeholder="Full Name" required>
            <input type="email" name="email" class="styled-input" placeholder="Email Address" required>
            <input type="text" name="phone" class="styled-input" placeholder="WhatsApp Number" required>
            <input type="password" name="password" class="styled-input" placeholder="Create Password" required>
            
            <label style="display:block; text-align:left; font-size:12px; color:#666; margin-bottom:5px; font-weight:bold;">Referral Code (Optional)</label>
            <input type="text" name="referral_code" class="styled-input" placeholder="e.g. RUSHI123" value="<?php echo htmlspecialchars($ref_code_url); ?>">
            
            <button type="submit" name="register" class="btn-register">REGISTER NOW</button>
        </form>

        <div style="margin-top: 20px; font-size: 14px;">
            Already have an account? <a href="login.php" style="color:#11998e; font-weight:bold; text-decoration:none;">Login Here</a>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>