<?php
session_start();

// Use __DIR__ to ensure files are loaded from same directory
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/email_helper.php';

// Function to generate unique 5-character referral code
function generateReferralCode($conn) {
    do {
        $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $code = '';
        for ($i = 0; $i < 5; $i++) {
            $code .= $characters[rand(0, strlen($characters) - 1)];
        }
        
        // Check if code already exists
        $check = "SELECT id FROM users WHERE referral_code='$code'";
        $result = mysqli_query($conn, $check);
    } while (mysqli_num_rows($result) > 0);
    
    return $code;
}

// Get referral code from URL if present
$referral_from_url = isset($_GET['ref']) ? mysqli_real_escape_string($conn, $_GET['ref']) : '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $phone = mysqli_real_escape_string($conn, $_POST['phone_number']);
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $referral_input = mysqli_real_escape_string($conn, $_POST['referral_code']);
    
    // Check if user already exists
    $check = "SELECT * FROM users WHERE phone_number='$phone' OR email='$email'";
    $result = mysqli_query($conn, $check);
    
    if (mysqli_num_rows($result) > 0) {
        $error = "Phone or email already exists!";
    } else {
        // Generate unique referral code for new user
        $new_referral_code = generateReferralCode($conn);
        
        // Find referrer ID if referral code was provided
        $referrer_id = null;
        if (!empty($referral_input)) {
            $referrer_query = "SELECT id FROM users WHERE referral_code='$referral_input'";
            $referrer_result = mysqli_query($conn, $referrer_query);
            
            if (mysqli_num_rows($referrer_result) > 0) {
                $referrer = mysqli_fetch_assoc($referrer_result);
                $referrer_id = $referrer['id'];
            } else {
                $error = "Invalid referral code!";
            }
        }
        
        // Only proceed if no error
        if (!isset($error)) {
            $sql = "INSERT INTO users (phone_number, email, password, referral_code, referrer_id) 
                    VALUES ('$phone', '$email', '$password', '$new_referral_code', " . 
                    ($referrer_id ? "'$referrer_id'" : "NULL") . ")";
            
            if (mysqli_query($conn, $sql)) {
                $user_id = mysqli_insert_id($conn);
                
                // Give registration bonus of ZMW 15
                $bonus_amount = 15.00;
                mysqli_query($conn, "UPDATE users SET balance = balance + $bonus_amount WHERE id = $user_id");
                mysqli_query($conn, "INSERT INTO profits (user_id, amount, source) VALUES ($user_id, $bonus_amount, 'Registration Bonus')");

                
                // Send welcome email
                try {
                    $emailSent = sendWelcomeEmail($email, $new_referral_code);
                    
                    if ($emailSent) {
                        error_log("✓ Welcome email sent successfully to: $email");
                    } else {
                        error_log("✗ Failed to send welcome email to: $email");
                    }
                } catch (Exception $e) {
                    error_log("✗ Email exception: " . $e->getMessage());
                }
                
                // Set session and redirect
                $_SESSION['user_id'] = $user_id;
                $_SESSION['success_message'] = "Registration successful! 🎉 ZMW 15 bonus added to your balance. Your referral code is: $new_referral_code";
                
                if (isset($emailSent) && $emailSent) {
                    $_SESSION['success_message'] .= " Check your email for more details!";
                }
                
                header("Location: home.php");
                exit();
            } else {
                $error = "Registration failed! " . mysqli_error($conn);
                error_log("Registration SQL error: " . mysqli_error($conn));
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register - MTM180</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            background-color: #000;
            color: #fff;
            font-family: Arial, sans-serif;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .container {
            width: 100%;
            max-width: 340px;
            padding: 25px;
            background: #111;
            border-radius: 8px;
            box-shadow: 0 0 15px rgba(255, 215, 0, 0.3);
        }
        .logo {
            text-align: center;
            margin-bottom: 15px;
        }
        .logo img {
            max-width: 160px;
            height: auto;
            display: block;
            margin: 0 auto;
        }
        h2 {
            text-align: center;
            margin-bottom: 20px;
            color: #fff;
            font-size: 22px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            color: #fff;
            font-size: 13px;
        }
        input {
            width: 100%;
            padding: 10px;
            background: #000;
            border: 1px solid #333;
            border-radius: 5px;
            color: #fff;
            font-size: 14px;
        }
        input:focus {
            outline: none;
            border-color: #FFD700;
        }
        button {
            width: 100%;
            padding: 11px;
            background: #FFD700;
            color: #000;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            margin-top: 8px;
            transition: background 0.3s;
        }
        button:hover {
            background: #FFA500;
        }
        .google-btn {
            background: #fff;
            color: #333;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            margin-top: 12px;
        }
        .google-btn:hover {
            background: #f0f0f0;
        }
        .google-btn img.google-icon {
            width: 20px;
            height: 20px;
        }
        .error {
            background: #ff0000;
            color: #fff;
            padding: 8px;
            border-radius: 5px;
            margin-bottom: 12px;
            text-align: center;
            font-size: 13px;
        }
        .success {
            background: #28a745;
            color: #fff;
            padding: 8px;
            border-radius: 5px;
            margin-bottom: 12px;
            text-align: center;
            font-size: 13px;
        }
        .link {
            text-align: center;
            margin-top: 15px;
            font-size: 13px;
        }
        .link a {
            color: #FFD700;
            text-decoration: none;
            font-weight: bold;
        }
        .link a:hover {
            text-decoration: underline;
        }
        .optional {
            font-size: 11px;
            color: #888;
        }
        .divider {
            text-align: center;
            margin: 15px 0;
            position: relative;
            color: #666;
            font-size: 12px;
        }
        .divider:before,
        .divider:after {
            content: '';
            position: absolute;
            top: 50%;
            width: 40%;
            height: 1px;
            background: #333;
        }
        .divider:before {
            left: 0;
        }
        .divider:after {
            right: 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="logo">
            <img src="https://pvp360.us/zambia/logoo.png" alt="PVP360">
        </div>
        <h2>Create Account</h2>
        
        <?php if (isset($error)): ?>
            <div class="error"><i class="fas fa-exclamation-circle"></i> <?php echo $error; ?></div>
        <?php endif; ?>
        
        <?php if (!empty($referral_from_url)): ?>
            <div class="success">
                <i class="fas fa-user-plus"></i> Invited! Code applied.
            </div>
        <?php endif; ?>
        
        <form method="POST">
            <div class="form-group">
                <label><i class="fas fa-phone"></i> Phone Number</label>
                <input type="text" name="phone_number" placeholder="0977123456" required>
            </div>
            
            <div class="form-group">
                <label><i class="fas fa-envelope"></i> Email</label>
                <input type="email" name="email" placeholder="your@email.com" required>
            </div>
            
            <div class="form-group">
                <label><i class="fas fa-lock"></i> Password</label>
                <input type="password" name="password" placeholder="password" minlength="4" required>
            </div>
            
            <div class="form-group">
                <label>
                    <i class="fas fa-gift"></i> Referral Code 
                    <span class="optional">(Optional)</span>
                </label>
                <input type="text" 
                       name="referral_code" 
                       placeholder="5-character code"
                       value="<?php echo htmlspecialchars($referral_from_url); ?>"
                       maxlength="5"
                       style="text-transform: uppercase;">
            </div>
            
            <button type="submit">
                <i class="fas fa-user-plus"></i> Register
            </button>
        </form>
        
        <div class="divider">OR</div>
        
        <button class="google-btn" onclick="window.location.href='google_register.php'">
            <img class="google-icon" src="https://180mtm.site/google.png" alt="Google">
            Continue with Google
        </button>
        
        <div class="link">
            Have an account? <a href="login.php">Login</a>
        </div>
    </div>
</body>
</html>