<?php
/**
 * Hostxolo - User Registration Page
 */
require_once 'config.php';

// Redirect if already logged in
if (is_logged_in()) {
    redirect(BASE_URL . 'user/dashboard.php');
}

$errors = [];

// Process registration form
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid security token. Please try again.';
    } else {
        $full_name = sanitize($_POST['full_name'] ?? '');
        $email = sanitize($_POST['email'] ?? '');
        $phone = sanitize($_POST['phone'] ?? '');
        $password = $_POST['password'] ?? '';
        $confirm_password = $_POST['confirm_password'] ?? '';
        $company_name = sanitize($_POST['company_name'] ?? '');
        
        // Validation
        if (empty($full_name)) {
            $errors[] = 'Full name is required.';
        } elseif (strlen($full_name) < 3) {
            $errors[] = 'Full name must be at least 3 characters.';
        }
        
        if (empty($email)) {
            $errors[] = 'Email address is required.';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = 'Please enter a valid email address.';
        }
        
        if (empty($phone)) {
            $errors[] = 'Phone number is required.';
        } elseif (!preg_match('/^[0-9]{10}$/', $phone)) {
            $errors[] = 'Please enter a valid 10-digit phone number.';
        }
        
        if (empty($password)) {
            $errors[] = 'Password is required.';
        } elseif (strlen($password) < 6) {
            $errors[] = 'Password must be at least 6 characters.';
        }
        
        if ($password !== $confirm_password) {
            $errors[] = 'Passwords do not match.';
        }
        
        // Check if email already exists
        if (empty($errors)) {
            try {
                $stmt = db()->prepare("SELECT id FROM users WHERE email = ?");
                $stmt->execute([$email]);
                if ($stmt->fetch()) {
                    $errors[] = 'An account with this email already exists. Please login.';
                }
            } catch (PDOException $e) {
                $errors[] = 'Registration failed. Please try again.';
            }
        }
        
        // Create account
        if (empty($errors)) {
            try {
                $hashed_password = password_hash($password, PASSWORD_BCRYPT);
                
                $stmt = db()->prepare("INSERT INTO users (full_name, email, phone, password, company_name, status, created_at) 
                                      VALUES (?, ?, ?, ?, ?, 'active', NOW())");
                $stmt->execute([$full_name, $email, $phone, $hashed_password, $company_name]);
                
                $user_id = db()->lastInsertId();
                
                // Log activity
                log_activity('register', 'New user registered', $user_id, 'user');
                
                // Auto login
                $_SESSION['user_id'] = $user_id;
                $_SESSION['user_name'] = $full_name;
                $_SESSION['user_email'] = $email;
                $_SESSION['user_role'] = 'user';
                
                // Send welcome email
                if (function_exists('send_welcome_email')) {
                    $email_sent = send_welcome_email($email, $full_name);
                    if ($email_sent) {
                        error_log("Welcome email sent to: $email");
                    } else {
                        error_log("Failed to send welcome email to: $email");
                    }
                }
                
                redirect(BASE_URL . 'user/dashboard.php', 'success', 'Welcome to Hostxolo! Your account has been created successfully.');
                
            } catch (PDOException $e) {
                $errors[] = 'Registration failed. Please try again.';
                error_log("Registration error: " . $e->getMessage());
            }
        }
    }
}

$csrf_token = generate_csrf_token();

// Set page specific SEO
$page_title = 'Register - Hostxolo';

include 'includes/header.php';
?>

<section class="py-5" style="margin-top: 70px; min-height: calc(100vh - 300px);">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8 col-lg-6">
                <div class="card shadow-lg border-0">
                    <div class="card-body p-4 p-md-5">
                        <div class="text-center mb-4">
                            <div class="mb-3">
                                <i class="bi bi-person-plus text-primary" style="font-size: 4rem;"></i>
                            </div>
                            <h2 class="fw-bold">Create Account</h2>
                            <p class="text-muted">Join Hostxolo and grow your business</p>
                        </div>
                        
                        <?php if (!empty($errors)): ?>
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <ul class="mb-0 ps-3">
                                    <?php foreach ($errors as $error): ?>
                                        <li><?php echo $error; ?></li>
                                    <?php endforeach; ?>
                                </ul>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>
                        
                        <form method="POST" action="" class="needs-validation" novalidate>
                            <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="full_name" class="form-label">Full Name *</label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="bi bi-person"></i></span>
                                        <input type="text" class="form-control" id="full_name" name="full_name" required 
                                               placeholder="Your full name" value="<?php echo $_POST['full_name'] ?? ''; ?>">
                                    </div>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label for="company_name" class="form-label">Company Name</label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="bi bi-building"></i></span>
                                        <input type="text" class="form-control" id="company_name" name="company_name" 
                                               placeholder="Your company" value="<?php echo $_POST['company_name'] ?? ''; ?>">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="email" class="form-label">Email Address *</label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="bi bi-envelope"></i></span>
                                        <input type="email" class="form-control" id="email" name="email" required 
                                               placeholder="your@email.com" value="<?php echo $_POST['email'] ?? ''; ?>">
                                    </div>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label for="phone" class="form-label">Phone Number *</label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="bi bi-phone"></i></span>
                                        <input type="tel" class="form-control" id="phone" name="phone" required 
                                               placeholder="10-digit mobile number" maxlength="10"
                                               value="<?php echo $_POST['phone'] ?? ''; ?>">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="password" class="form-label">Password *</label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="bi bi-lock"></i></span>
                                        <input type="password" class="form-control" id="password" name="password" required 
                                               placeholder="Create password" minlength="6">
                                        <button class="btn btn-outline-secondary password-toggle" type="button">
                                            <i class="bi bi-eye"></i>
                                        </button>
                                    </div>
                                    <div class="form-text">Must be at least 6 characters</div>
                                </div>
                                
                                <div class="col-md-6 mb-4">
                                    <label for="confirm_password" class="form-label">Confirm Password *</label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="bi bi-lock-fill"></i></span>
                                        <input type="password" class="form-control" id="confirm_password" name="confirm_password" required 
                                               placeholder="Confirm password">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mb-4">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="terms" name="terms" required>
                                    <label class="form-check-label" for="terms">
                                        I agree to the <a href="<?php echo BASE_URL; ?>terms-conditions.php" target="_blank">Terms & Conditions</a> 
                                        and <a href="<?php echo BASE_URL; ?>privacy-policy.php" target="_blank">Privacy Policy</a>
                                    </label>
                                </div>
                            </div>
                            
                            <div class="d-grid mb-4">
                                <button type="submit" class="btn btn-primary btn-lg">
                                    <i class="bi bi-person-plus me-2"></i>Create Account
                                </button>
                            </div>
                            
                            <div class="text-center">
                                <p class="text-muted mb-0">Already have an account? 
                                    <a href="<?php echo BASE_URL; ?>login.php" class="fw-bold">Sign in</a>
                                </p>
                            </div>
                        </form>
                        
                        <hr class="my-4">
                        
                        <!-- Social Login (Placeholder) -->
                        <div class="text-center">
                            <p class="text-muted mb-3">Or register with</p>
                            <div class="d-flex justify-content-center gap-2">
                                <a href="#" class="btn btn-outline-secondary">
                                    <i class="bi bi-google"></i> Google
                                </a>
                                <a href="#" class="btn btn-outline-secondary">
                                    <i class="bi bi-facebook"></i> Facebook
                                </a>
                                <a href="#" class="btn btn-outline-secondary">
                                    <i class="bi bi-linkedin"></i> LinkedIn
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<?php include 'includes/footer.php'; ?>
