<?php
include '../config/db.php';
include '../config/config.php';
include '../config/function.php';

$alert_script = '';

// Process form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Define required fields
    $required_fields = [
        'first_name', 'last_name', 'email', 'phone_no', 
        'street_address', 'state', 'country', 'gender', 
        'dob', 'password', 'password_confirmation'
    ];
    
    // Check for empty required fields
    $errors = [];
    foreach ($required_fields as $field) {
        if (empty($_POST[$field])) {
            $errors[] = ucfirst(str_replace('_', ' ', $field)) . ' is required';
        }
    }
    
    // Check if passwords match
    if ($_POST['password'] !== $_POST['password_confirmation']) {
        $errors[] = 'Passwords do not match';
    }
    
    // Validate email format
    if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Invalid email format';
    }
    
    // Validate password strength (minimum 8 characters)
    if (strlen($_POST['password']) < 8) {
        $errors[] = 'Password must be at least 8 characters long';
    }
    
    // If there are errors, display them
    if (!empty($errors)) {
        $alert_script = show_errors($errors);
    } else {
        // All validations passed, proceed with registration
        $first_name = text_input($_POST['first_name']);
        $last_name = text_input($_POST['last_name']);
        $email = text_input($_POST['email']);
        $phone_no = text_input($_POST['phone_no']);
        $street_address = text_input($_POST['street_address']);
        $state = text_input($_POST['state']);
        $country = text_input($_POST['country']);
        $gender = text_input($_POST['gender']);
        $dob = text_input($_POST['dob']);
        $referred_by = !empty($_POST['referred_by']) ? text_input($_POST['referred_by']) : null;
        $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $randomCode = generateRandomCode();
        
        // Check if email already exists
        $stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $stmt->store_result();
        
        if ($stmt->num_rows > 0) {
            // Email already exists
            $alert_script = show_error("Email address is already registered");
        } else {
            // Insert new user
            $stmt = $conn->prepare("INSERT INTO users (first_name, last_name, email, phone_no, street_address, state, country, gender, dob, referred_by, password, account_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
            $stmt->bind_param("ssssssssssss", $first_name, $last_name, $email, $phone_no, $street_address, $state, $country, $gender, $dob, $referred_by, $password, $randomCode);
            
            if ($stmt->execute()) {
                // Registration successful - send welcome email
                $username = $first_name . ' ' . $last_name;
                $uid = $randomCode;
                
                $subject = "Welcome to $sitename!";
                $body = "
                <div style='background: #E4E9F0; padding: 20px; font-family: Arial, sans-serif;'>
                    <div style='max-width: 600px; margin: 0 auto; background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);'>
                        <div style='background-color: #1e293b; padding: 16px; display: flex; align-items: center;'>
                            <div style='display: flex; align-items: center;'>
                                <center><img src='$site_url/image/logo.png' width='100px' style='margin-right: 8px;'></center>
                            </div>
                        </div>
                        <div style='padding: 32px; text-align: center;'>
                            <h1 style='font-size: 28px; color: #1e293b; margin-bottom: 24px; line-height: 1.2;'>
                                Welcome to $sitename!
                            </h1>
                            <p style='font-size: 18px; color: #4b5563; margin-bottom: 32px;'>
                                Hi, <b>$username</b>, your account has been successfully created.
                            </p>
                            
                            <p style='font-size: 18px; color: #4b5563; margin-bottom: 32px;'>
                                Your account UID is: <b>$uid</b>
                            </p>
                            <p style='font-size: 18px; color: #4b5563; margin-bottom: 32px;'>
                                Thank you for joining us. We're excited to have you on board!
                            </p>
                            <p style='font-size: 18px; color: #4b5563; margin-bottom: 32px;'>
                                <a href='$site_url/auth/login.php' style='color: dodgerblue; text-decoration: none'>Login to your account</a>
                            </p>
                            <div style='margin-top: 32px; border-top: 1px solid #e5e7eb; padding-top: 24px; text-align: left;'>
                                <p style='color: #4b5563; margin-bottom: 8px;'>Thanks,</p>
                                <p style='color: #4b5563; font-weight: bold;'>Support Team, $sitename</p>
                            </div>
                            <div style='margin-top: 32px; font-size: 12px; color: #6b7280; text-align: left;'>
                                <p style='margin-bottom: 4px;'>Please consider all emails from us as confidential.</p>
                            </div>
                        </div>
                    </div>
                </div>";

                $send = sendMail($email, $subject, $body);
                
                // Registration successful
                $alert_script = show_success("Registration successful! You can now login.");
            } else {
                // Error occurred
                $alert_script = show_error("Error occurred during registration. Please try again.");
            }
        }
        
        $stmt->close();
    }
}

function show_errors($errors) {
    $error_list = '';
    foreach ($errors as $error) {
        $error_list .= "<li>$error</li>";
    }
    
    return "<script>
        document.addEventListener('DOMContentLoaded', function() {
            Swal.fire({
                icon: 'error',
                title: 'Validation Error',
                html: 'Please fix the following errors:<ul>$error_list</ul>',
                confirmButtonText: 'OK'
            });
        });
    </script>";
}

function show_error($message) {
    return "<script>
        document.addEventListener('DOMContentLoaded', function() {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: '$message'
            });
        });
    </script>";
}

function show_success($message) {
    return "<script>
        document.addEventListener('DOMContentLoaded', function() {
            Swal.fire({
                icon: 'success',
                title: 'Success',
                text: '$message'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = 'login.php';
                }
            });
        });
    </script>";
}

$conn->close();
?>
<!DOCTYPE html>
<html lang="zxx">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Links of CSS files -->
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/aos.css">
    <link rel="stylesheet" href="assets/css/animate.min.css">
    <link rel="stylesheet" href="assets/css/meanmenu.min.css">
    <link rel="stylesheet" href="assets/css/remixicon.css">
    <link rel="stylesheet" href="assets/css/flaticon.css">
    <link rel="stylesheet" href="assets/css/odometer.min.css">
    <link rel="stylesheet" href="assets/css/owl.carousel.min.css">
    <link rel="stylesheet" href="assets/css/owl.theme.default.min.css">
    <link rel="stylesheet" href="assets/css/magnific-popup.min.css">
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="stylesheet" href="assets/css/navbar.css">
    <link rel="stylesheet" href="assets/css/footer.css">
    <link rel="stylesheet" href="assets/css/dark.css">
    <link rel="stylesheet" href="assets/css/responsive.css">
    
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <!--=== Title & Favicon ===-->
    <title><?php echo $sitename ?></title>
    <link rel="icon" type="image/png" href="assets/images/favicon.png">
</head>
<body>
    
    <!-- Start Register Area -->
    <div class="login-area ptb-100">
        <div class="container">
            <div class="login-form">
                <h2>Create Account</h2>
                <p>Fill in your details to register</p>

                <form method="post">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>First Name *</label>
                                <input type="text" class="form-control" name="first_name" placeholder="Your first name" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Last Name *</label>
                                <input type="text" class="form-control" name="last_name" placeholder="Your last name" required>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Email Address *</label>
                        <input type="email" class="form-control" name="email" placeholder="Your email address" required>
                    </div>

                    <div class="form-group">
                        <label>Phone Number *</label>
                        <input type="tel" class="form-control" name="phone_no" placeholder="Your phone number" required>
                    </div>

                    <div class="form-group">
                        <label>Street Address *</label>
                        <input type="text" class="form-control" name="street_address" placeholder="Your street address" required>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>State *</label>
                                <input type="text" class="form-control" name="state" placeholder="Your state" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Country *</label>
                                <input type="text" class="form-control" name="country" placeholder="Your country" required>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Gender *</label>
                                <select class="form-control" name="gender" required>
                                    <option value="">Select Gender</option>
                                    <option value="Male">Male</option>
                                    <option value="Female">Female</option>
                                    <option value="Other">Other</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Date of Birth *</label>
                                <input type="date" class="form-control" name="dob" required>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Referral Code (Optional)</label>
                        <input type="text" class="form-control" name="referred_by" placeholder="Referral code if any">
                    </div>

                    <div class="form-group">
                        <label>Password * (min 8 characters)</label>
                        <input type="password" class="form-control" name="password" placeholder="Your password" required>
                    </div>

                    <div class="form-group">
                        <label>Confirm Password *</label>
                        <input type="password" class="form-control" name="password_confirmation" placeholder="Confirm your password" required>
                    </div>

                    <button type="submit" class="default-btn">Register Now</button>

                    <div class="account-text">
                        <span>Already have an account? <a href="login.php">Login Here</a></span>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <!-- End Register Area -->

    <?php if (!empty($alert_script)) { echo $alert_script; } ?>
    
    <!-- Links of JS files -->
    <script src="assets/js/jquery.min.js"></script>
    <script src="assets/js/bootstrap.bundle.min.js"></script>
    <script src="assets/js/jquery.meanmenu.js"></script> 
    <script src="assets/js/owl.carousel.min.js"></script>
    <script src="assets/js/jquery.appear.js"></script>
    <script src="assets/js/odometer.min.js"></script>
    <script src="assets/js/jquery.magnific-popup.min.js"></script>
    <script src="assets/js/TweenMax.min.js"></script>
    <script src="assets/js/ScrollMagic.min.js"></script>
    <script src="assets/js/aos.js"></script>
    <script src="assets/js/jquery.ajaxchimp.min.js"></script>
    <script src="assets/js/form-validator.min.js"></script>
    <script src="assets/js/contact-form-script.js"></script>
    <script src="assets/js/wow.min.js"></script>
    <script src="assets/js/main.js"></script>
    
</body>
</html>