<?php
/**
 * Register Page - PREMIUM VERSION
 * Digital Marketplace
 */

require_once __DIR__ . '/config/database.php';

$page_title = 'Create Account';

// Redirect if already logged in
if (is_user_logged_in()) {
    header('Location: ' . BASE_URL . '/account/index.php');
    exit;
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid request. Please try again.';
    } else {
        $name = sanitize($_POST['name'] ?? '');
        $email = sanitize_email($_POST['email'] ?? '');
        $phone = sanitize($_POST['phone'] ?? '');
        $password = $_POST['password'] ?? '';
        $confirm_password = $_POST['confirm_password'] ?? '';
        $agree_terms = isset($_POST['agree_terms']);
        
        // Validation
        if (empty($name) || strlen($name) < 2) {
            $errors[] = 'Full name is required (min 2 characters)';
        }
        if (empty($email) || !validate_email($email)) {
            $errors[] = 'Valid email address is required';
        }
        if (empty($password) || strlen($password) < 8) {
            $errors[] = 'Password must be at least 8 characters';
        }
        if ($password !== $confirm_password) {
            $errors[] = 'Passwords do not match';
        }
        if (!$agree_terms) {
            $errors[] = 'You must agree to the Terms of Service and Privacy Policy';
        }
        
        // Check if email exists
        if (empty($errors)) {
            $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->execute([$email]);
            if ($stmt->fetch()) {
                $errors[] = 'Email address already registered';
            }
        }
        
        if (empty($errors)) {
            // Create user
            $user_data = [
                'name' => $name,
                'email' => $email,
                'phone' => $phone,
                'password' => $password
            ];
            
            $user_id = create_user($user_data);
            
            if ($user_id) {
                // Check for affiliate referral
                if (isset($_COOKIE['affiliate_code'])) {
                    $affiliate = get_affiliate_by_code($_COOKIE['affiliate_code']);
                    if ($affiliate) {
                        $stmt = $pdo->prepare("UPDATE users SET referred_by = ? WHERE id = ?");
                        $stmt->execute([$affiliate['user_id'], $user_id]);
                    }
                }
                
                // Send welcome email
                send_welcome_email($user_id);
                
                // Log activity
                log_activity('user_registered', "New user registered: {$email}");
                
                // Auto login
                $_SESSION['user_id'] = $user_id;
                $_SESSION['user_logged_in'] = true;
                $_SESSION['user_name'] = $name;
                $_SESSION['user_email'] = $email;
                
                set_flash_message('Welcome to ' . get_setting('site_name', 'Digital Marketplace') . '! Your account has been created.', 'success');
                header('Location: ' . BASE_URL . '/account/index.php');
                exit;
            } else {
                $errors[] = 'Failed to create account. Please try again.';
            }
        }
    }
}

include __DIR__ . '/includes/header.php';
?>

<section class="section">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8 col-lg-6">
                <div class="card auth-card" data-aos="fade-up">
                    <div class="card-body p-5">
                        <div class="text-center mb-4">
                            <div class="auth-icon mb-3">
                                <i class="fas fa-user-plus"></i>
                            </div>
                            <h2 class="mb-2">Create Account</h2>
                            <p class="text-muted">Join our community today</p>
                        </div>
                        
                        <?php if (!empty($errors)): ?>
                            <div class="alert alert-danger">
                                <?php foreach ($errors as $error): ?>
                                    <div><i class="fas fa-exclamation-circle me-2"></i><?php echo $error; ?></div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                        
                        <form method="POST" id="registerForm">
                            <?php echo csrf_field(); ?>
                            
                            <div class="row g-3">
                                <div class="col-12">
                                    <label class="form-label">Full Name *</label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-user"></i></span>
                                        <input type="text" name="name" class="form-control" 
                                               placeholder="Enter your full name" required
                                               value="<?php echo sanitize($_POST['name'] ?? ''); ?>">
                                    </div>
                                </div>
                                
                                <div class="col-12">
                                    <label class="form-label">Email Address *</label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-envelope"></i></span>
                                        <input type="email" name="email" class="form-control" 
                                               placeholder="Enter your email" required
                                               value="<?php echo sanitize($_POST['email'] ?? ''); ?>">
                                    </div>
                                </div>
                                
                                <div class="col-12">
                                    <label class="form-label">Phone Number</label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-phone"></i></span>
                                        <input type="tel" name="phone" class="form-control" 
                                               placeholder="Enter your phone number"
                                               value="<?php echo sanitize($_POST['phone'] ?? ''); ?>">
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <label class="form-label">Password *</label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-lock"></i></span>
                                        <input type="password" name="password" class="form-control" 
                                               placeholder="Create password" required
                                               id="passwordInput" minlength="8">
                                        <button type="button" class="input-group-text password-toggle" data-target="#passwordInput">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                    </div>
                                    <small class="text-muted">Minimum 8 characters</small>
                                </div>
                                
                                <div class="col-md-6">
                                    <label class="form-label">Confirm Password *</label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-lock"></i></span>
                                        <input type="password" name="confirm_password" class="form-control" 
                                               placeholder="Confirm password" required>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="form-check mt-4 mb-4">
                                <input type="checkbox" name="agree_terms" class="form-check-input" id="agreeTerms" required>
                                <label class="form-check-label" for="agreeTerms">
                                    I agree to the <a href="<?php echo BASE_URL; ?>/page.php?slug=terms-of-service" target="_blank">Terms of Service</a> 
                                    and <a href="<?php echo BASE_URL; ?>/page.php?slug=privacy-policy" target="_blank">Privacy Policy</a>
                                </label>
                            </div>
                            
                            <button type="submit" class="btn btn-primary w-100 btn-lg mb-3">
                                <i class="fas fa-user-plus me-2"></i>Create Account
                            </button>
                            
                            <div class="text-center">
                                <p class="mb-0">Already have an account? <a href="<?php echo BASE_URL; ?>/login.php" class="text-primary">Sign in</a></p>
                            </div>
                        </form>
                        
                        <hr class="my-4">
                        
                        <div class="text-center">
                            <p class="text-muted mb-3">Or sign up with</p>
                            <div class="social-login">
                                <a href="#" class="social-btn google">
                                    <i class="fab fa-google"></i>
                                </a>
                                <a href="#" class="social-btn facebook">
                                    <i class="fab fa-facebook-f"></i>
                                </a>
                                <a href="#" class="social-btn github">
                                    <i class="fab fa-github"></i>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<style>
/* Same as login page */
.auth-card {
    border: 1px solid var(--dark-lighter);
    background: var(--gradient-card);
}

.auth-icon {
    width: 80px;
    height: 80px;
    margin: 0 auto;
    display: flex;
    align-items: center;
    justify-content: center;
    background: var(--gradient-primary);
    border-radius: 50%;
    font-size: 2.5rem;
    color: var(--white);
}

.password-toggle {
    cursor: pointer;
    background: var(--dark-lighter);
    border: 1px solid var(--dark-lighter);
    color: var(--gray-400);
}

.password-toggle:hover {
    color: var(--white);
}

.social-login {
    display: flex;
    justify-content: center;
    gap: 12px;
}

.social-btn {
    width: 50px;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: var(--dark-lighter);
    border-radius: var(--radius);
    color: var(--white);
    font-size: 1.25rem;
    transition: var(--transition);
}

.social-btn:hover {
    background: var(--primary);
    color: var(--white);
}
</style>

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