<?php
// --- LOGIC BLOCK: All PHP processing must happen before any HTML is sent ---
require_once 'includes/db.php';

// If a user is already logged in, redirect them to their dashboard
if (isset($_SESSION['user_id'])) {
    header("Location: dashboard/");
    exit();
}

// Capture a referral code from the URL if it exists
if (isset($_GET['ref'])) {
    // Sanitize the referral code before storing it in the session
    $_SESSION['referral_code'] = preg_replace("/[^a-zA-Z0-9]+/", "", $_GET['ref']);
}

$error_msg = '';
// Process the form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Sanitize and retrieve all form data
    $title = trim($_POST['title']);
    $full_name = trim(strip_tags($_POST['full_name']));
    $suffix = trim(strip_tags($_POST['suffix']));
    $email = trim(filter_var($_POST['email'], FILTER_SANITIZE_EMAIL));
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];

    // --- Form Validation ---
    if (empty($full_name) || empty($email) || empty($password)) {
        $error_msg = "Please fill in all required fields.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error_msg = "Please enter a valid email address.";
    } elseif (strlen($password) < 8) {
        $error_msg = "Password must be at least 8 characters long.";
    } elseif ($password !== $confirm_password) {
        $error_msg = "Passwords do not match.";
    } else {
        // Check if the email address is already in use
        $stmt_check = $conn->prepare("SELECT id FROM users WHERE email = ?");
        $stmt_check->bind_param("s", $email);
        $stmt_check->execute();
        if ($stmt_check->get_result()->num_rows > 0) {
            $error_msg = "An account with this email already exists.";
        } else {
            // --- All validation passed, proceed to create the new user ---
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            
            $stmt_insert = $conn->prepare("INSERT INTO users (title, full_name, suffix, email, password, role, status) VALUES (?, ?, ?, ?, ?, 'customer', 'active')");
            $stmt_insert->bind_param("sssss", $title, $full_name, $suffix, $email, $hashed_password);
            
            if ($stmt_insert->execute()) {
                $new_user_id = $stmt_insert->insert_id;
                $referrer_id = null;
                
                // --- Affiliate System Logic ---
                // 1. If the new user was referred by someone, find the referrer's ID
                if (isset($_SESSION['referral_code'])) {
                    $ref_code = $_SESSION['referral_code'];
                    $stmt_ref = $conn->prepare("SELECT id FROM users WHERE referral_code = ?");
                    $stmt_ref->bind_param("s", $ref_code);
                    $stmt_ref->execute();
                    $ref_result = $stmt_ref->get_result();
                    if ($ref_result->num_rows > 0) {
                        $referrer_id = $ref_result->fetch_assoc()['id'];
                    }
                    unset($_SESSION['referral_code']); // Clear the session variable after use
                }

                // 2. Generate a truly unique referral code for this new user
                do {
                    $new_ref_code = strtoupper(substr(str_shuffle('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 8));
                    $stmt_code_check = $conn->prepare("SELECT id FROM users WHERE referral_code = ?");
                    $stmt_code_check->bind_param("s", $new_ref_code);
                    $stmt_code_check->execute();
                    $code_exists = $stmt_code_check->get_result()->num_rows > 0;
                } while ($code_exists);

                // 3. Save the new code and the referrer ID (if found) to the new user's record
                $stmt_update = $conn->prepare("UPDATE users SET referral_code = ?, referred_by = ? WHERE id = ?");
                $stmt_update->bind_param("sii", $new_ref_code, $referrer_id, $new_user_id);
                $stmt_update->execute();
                
                // --- Auto-Login the New User ---
                session_regenerate_id(true); // Create a fresh, secure session
                $_SESSION['user_id'] = $new_user_id;
                $_SESSION['user_name'] = $full_name;
                $_SESSION['user_role'] = 'customer';
                header("Location: dashboard/");
                exit();
            } else {
                $error_msg = "An error occurred during registration. Please try again.";
            }
        }
    }
}
// --- PRESENTATION BLOCK ---
include 'includes/header.php';
?>
<main class="container my-5">
    <div class="row justify-content-center">
        <div class="col-md-7">
            <div class="card shadow-lg">
                <div class="card-body p-5">
                    <h2 class="text-center mb-4">Create a Customer Account</h2>
                    <?php if ($error_msg): ?><div class="alert alert-danger"><?php echo $error_msg; ?></div><?php endif; ?>
                    <form method="POST" action="register.php" novalidate>
                        <div class="row">
                            <div class="col-md-3 mb-3">
                                <label class="form-label">Title</label>
                                <select name="title" class="form-select">
                                    <option value="Mr.">Mr.</option>
                                    <option value="Ms.">Ms.</option>
                                    <option value="Mrs.">Mrs.</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Full Name</label>
                                <input type="text" class="form-control" name="full_name" required value="<?php echo isset($_POST['full_name']) ? htmlspecialchars($_POST['full_name']) : ''; ?>">
                            </div>
                            <div class="col-md-3 mb-3">
                                <label class="form-label">Suffix</label>
                                <input type="text" class="form-control" name="suffix" placeholder="e.g., Jr., III" value="<?php echo isset($_POST['suffix']) ? htmlspecialchars($_POST['suffix']) : ''; ?>">
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Email Address</label>
                            <input type="email" class="form-control" name="email" required value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>">
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Password (min. 8 characters)</label>
                                <input type="password" class="form-control" name="password" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Confirm Password</label>
                                <input type="password" class="form-control" name="confirm_password" required>
                            </div>
                        </div>
                        <div class="d-grid"><button type="submit" class="btn btn-primary">Register</button></div>
                        <p class="text-center mt-3">Already have an account? <a href="login.php">Log In</a></p>
                    </form>
                </div>
            </div>
        </div>
    </div>
</main>
<?php include 'includes/footer.php'; ?>
