<?php
/**
 * REGISTRATION PAGE
 * File: auth/register.php
 * Handles new user registration
 */

require_once '../app/Core/init.php';

// Redirect if already logged in
if (Auth::check()) {
    $user_type = $_SESSION['user_type'];
    if ($user_type === 'admin') {
        redirect('/admin/index.php');
    } elseif ($user_type === 'vendor') {
        redirect('/vendor/index.php');
    } elseif ($user_type === 'customer') {
        // redirect('/customer/index.php');
        redirect('../index.php');
    }
}

$errors = [];
$data = [
    'first_name' => '',
    'last_name' => '',
    'email' => '',
    'phone' => '',
    'user_type' => 'customer',
    'agree_terms' => false
];

// Handle registration form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data['first_name'] = trim($_POST['first_name'] ?? '');
    $data['last_name'] = trim($_POST['last_name'] ?? '');
    $data['email'] = trim($_POST['email'] ?? '');
    $data['phone'] = trim($_POST['phone'] ?? '');
    $data['user_type'] = $_POST['user_type'] ?? 'customer';
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    $data['agree_terms'] = isset($_POST['agree_terms']);
    
    // Validate inputs
    if (empty($data['first_name'])) {
        $errors['first_name'] = 'First name is required';
    } elseif (strlen($data['first_name']) < 2) {
        $errors['first_name'] = 'First name must be at least 2 characters';
    }
    
    if (empty($data['last_name'])) {
        $errors['last_name'] = 'Last name is required';
    } elseif (strlen($data['last_name']) < 2) {
        $errors['last_name'] = 'Last name must be at least 2 characters';
    }
    
    if (empty($data['email'])) {
        $errors['email'] = 'Email is required';
    } elseif (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
        $errors['email'] = 'Please enter a valid email address';
    } else {
        // Check if email already exists
        $user_model = new User();
        if ($user_model->findByEmail($data['email'])) {
            $errors['email'] = 'This email is already registered';
        }
    }
    
    if (empty($data['phone'])) {
        $errors['phone'] = 'Phone number is required';
    } elseif (!preg_match('/^[0-9]{10,15}$/', $data['phone'])) {
        $errors['phone'] = 'Please enter a valid phone number';
    }
    
    if (empty($password)) {
        $errors['password'] = 'Password is required';
    } elseif (strlen($password) < 8) {
        $errors['password'] = 'Password must be at least 8 characters';
    } elseif (!preg_match('/[A-Z]/', $password)) {
        $errors['password'] = 'Password must contain at least one uppercase letter';
    } elseif (!preg_match('/[a-z]/', $password)) {
        $errors['password'] = 'Password must contain at least one lowercase letter';
    } elseif (!preg_match('/[0-9]/', $password)) {
        $errors['password'] = 'Password must contain at least one number';
    }
    
    if (empty($confirm_password)) {
        $errors['confirm_password'] = 'Please confirm your password';
    } elseif ($password !== $confirm_password) {
        $errors['confirm_password'] = 'Passwords do not match';
    }
    
    if (!$data['agree_terms']) {
        $errors['agree_terms'] = 'You must agree to the terms of service';
    }
    
    // If no errors, create user account
    if (empty($errors)) {
        try {
            $user_model = new User();
            
            // Generate email verification token
            $verification_token = bin2hex(random_bytes(32));
            
            // Create user account
            $user_id = $user_model->create([
                'first_name' => $data['first_name'],
                'last_name' => $data['last_name'],
                'email' => $data['email'],
                'phone' => $data['phone'],
                'password' => password_hash($password, PASSWORD_DEFAULT),
                'user_type' => $data['user_type'],
                'status' => 'active',
                'email_verified' => 0,
                'verification_token' => $verification_token
            ]);
            
            if ($user_id) {
                // Create customer or vendor profile
                if ($data['user_type'] === 'customer') {
                    $customer_model = new Customer();
                    $customer_model->create([
                        'user_id' => $user_id,
                        'first_name' => $data['first_name'],
                        'last_name' => $data['last_name'],
                        'phone' => $data['phone']
                    ]);
                } elseif ($data['user_type'] === 'vendor') {
                    $vendor_model = new Vendor();
                    $vendor_model->create([
                        'user_id' => $user_id,
                        'business_name' => $data['first_name'] . ' ' . $data['last_name'],
                        'first_name' => $data['first_name'],
                        'last_name' => $data['last_name'],
                        'phone' => $data['phone'],
                        'approval_status' => 'pending'
                    ]);
                }
                
                // Send verification email
                $mailer = new Mailer();
                $mailer->sendVerificationEmail(
                    $data['email'],
                    $data['first_name'],
                    $verification_token
                );
                
                // Set success message
                flash('success', 'Registration successful! Please check your email to verify your account.', 'success');
                redirect('login.php');
            } else {
                $errors['general'] = 'Registration failed. Please try again.';
            }
        } catch (Exception $e) {
            log_error("Registration error: " . $e->getMessage());
            $errors['general'] = 'An error occurred during registration. Please try again.';
        }
    }
}

$page_title = "Sign Up - " . APP_NAME;
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="../assets/images/favicon.png">
    <title><?= $page_title ?></title>
    <link href="../assets/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../assets/plugins/fontawesome/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>

<body>
    <!-- Navbar -->
    <?php include '../templates/layouts/frontend/navbar.php'; ?>
    
    <div class="p-3 p-sm-5">
        <div class="row g-4 g-xl-5 justify-content-center">
            <div class="col-xl-5 col-lg-6 col-md-8">
                <div class="authentication-wrap overflow-hidden position-relative text-center text-sm-start my-5">
                    
                    <!-- Header -->
                    <div class="mb-5">
                        <h2 class="display-6 fw-semibold mb-3">Create Your <span class="font-caveat text-primary">Account</span></h2>
                        <p class="mb-0">Join our community and start renting or listing items today!</p>
                    </div>
                    
                    <!-- Display general errors -->
                    <?php if (isset($errors['general'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="fas fa-exclamation-circle me-2"></i>
                            <?= Security::escapeOutput($errors['general']) ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <!-- Registration Form -->
                    <form method="POST" action="" class="register-form">
                        <?= Security::csrfField() ?>
                        
                        <!-- User Type Selection -->
                        <div class="form-group mb-4">
                            <label class="required">I want to</label>
                            <div class="row g-2">
                                <div class="col-6">
                                    <input type="radio" class="btn-check" name="user_type" value="customer" id="typeCustomer" 
                                           <?= $data['user_type'] === 'customer' ? 'checked' : '' ?>>
                                    <label class="btn btn-outline-primary w-100" for="typeCustomer">
                                        <i class="fas fa-shopping-cart me-2"></i>Rent Items
                                    </label>
                                </div>
                                <div class="col-6">
                                    <input type="radio" class="btn-check" name="user_type" value="vendor" id="typeVendor"
                                           <?= $data['user_type'] === 'vendor' ? 'checked' : '' ?>>
                                    <label class="btn btn-outline-primary w-100" for="typeVendor">
                                        <i class="fas fa-store me-2"></i>List Items
                                    </label>
                                </div>
                            </div>
                        </div>
                        
                        <!-- First Name -->
                        <div class="form-group mb-4">
                            <label class="required">First Name</label>
                            <input type="text" name="first_name" class="form-control <?= isset($errors['first_name']) ? 'is-invalid' : '' ?>" 
                                   value="<?= Security::escapeOutput($data['first_name']) ?>" placeholder="Enter first name" required>
                            <?php if (isset($errors['first_name'])): ?>
                                <div class="invalid-feedback text-start"><?= $errors['first_name'] ?></div>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Last Name -->
                        <div class="form-group mb-4">
                            <label class="required">Last Name</label>
                            <input type="text" name="last_name" class="form-control <?= isset($errors['last_name']) ? 'is-invalid' : '' ?>" 
                                   value="<?= Security::escapeOutput($data['last_name']) ?>" placeholder="Enter last name" required>
                            <?php if (isset($errors['last_name'])): ?>
                                <div class="invalid-feedback text-start"><?= $errors['last_name'] ?></div>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Email -->
                        <div class="form-group mb-4">
                            <label class="required">Email Address</label>
                            <input type="email" name="email" class="form-control <?= isset($errors['email']) ? 'is-invalid' : '' ?>" 
                                   value="<?= Security::escapeOutput($data['email']) ?>" placeholder="Enter your email" required>
                            <?php if (isset($errors['email'])): ?>
                                <div class="invalid-feedback text-start"><?= $errors['email'] ?></div>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Phone -->
                        <div class="form-group mb-4">
                            <label class="required">Phone Number</label>
                            <input type="tel" name="phone" class="form-control <?= isset($errors['phone']) ? 'is-invalid' : '' ?>" 
                                   value="<?= Security::escapeOutput($data['phone']) ?>" placeholder="Enter phone number" required>
                            <?php if (isset($errors['phone'])): ?>
                                <div class="invalid-feedback text-start"><?= $errors['phone'] ?></div>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Password -->
                        <div class="form-group mb-4">
                            <label class="required">Password</label>
                            <div class="position-relative">
                                <input id="password" type="password" name="password" 
                                       class="form-control password <?= isset($errors['password']) ? 'is-invalid' : '' ?>" 
                                       placeholder="Create password" required autocomplete="off">
                                <i data-bs-toggle="#password" class="fa-regular fa-eye-slash toggle-password"></i>
                            </div>
                            <?php if (isset($errors['password'])): ?>
                                <div class="invalid-feedback text-start d-block"><?= $errors['password'] ?></div>
                            <?php endif; ?>
                            <small class="text-muted">Must be 8+ characters with uppercase, lowercase, and number</small>
                        </div>
                        
                        <!-- Confirm Password -->
                        <div class="form-group mb-4">
                            <label class="required">Confirm Password</label>
                            <div class="position-relative">
                                <input id="confirmPassword" type="password" name="confirm_password" 
                                       class="form-control c-password <?= isset($errors['confirm_password']) ? 'is-invalid' : '' ?>" 
                                       placeholder="Confirm password" required autocomplete="off">
                                <i data-bs-toggle="#confirmPassword" class="fa-regular fa-eye-slash toggle-password"></i>
                            </div>
                            <?php if (isset($errors['confirm_password'])): ?>
                                <div class="invalid-feedback text-start d-block"><?= $errors['confirm_password'] ?></div>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Terms Checkbox -->
                        <div class="form-check mb-4 text-start">
                            <input class="form-check-input <?= isset($errors['agree_terms']) ? 'is-invalid' : '' ?>" 
                                   type="checkbox" name="agree_terms" value="1" id="agreeTerms" 
                                   <?= $data['agree_terms'] ? 'checked' : '' ?>>
                            <label class="form-check-label" for="agreeTerms">
                                I agree to the <a href="../terms-conditions.php" target="_blank" class="text-decoration-underline">Terms of Service</a> 
                                and <a href="../privacy-policy.php" target="_blank" class="text-decoration-underline">Privacy Policy</a>
                            </label>
                            <?php if (isset($errors['agree_terms'])): ?>
                                <div class="invalid-feedback text-start d-block"><?= $errors['agree_terms'] ?></div>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Submit Button -->
                        <button type="submit" class="btn btn-primary btn-lg w-100">Create Account</button>
                    </form>
                    
                    <!-- Bottom Text -->
                    <div class="bottom-text text-center mt-4">
                        Already have an account? <a href="login.php" class="fw-medium text-decoration-underline">Sign In</a>
                    </div>
                </div>
            </div>
            <div class="col-xl-7 d-none d-xl-block">
                <div class="background-image bg-light d-flex flex-column h-100 justify-content-center p-5 rounded-4" data-image-src="assets/images/lines.svg">
                    <div class="py-5 text-center">
                        <div class="mb-5">
                            <h2 class="fw-semibold">Effortlessly organize your<br> workspace with ease.</h2>
                            <p>It is a long established fact that a reader will be distracted by the readable<br> content of a page when looking at its layout. </p>
                        </div>
                        <img src="../assets/images/png-img/real-time-analytics.png" alt="" class="img-fluid">
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Footer -->
    <?php include '../templates/layouts/frontend/footer.php'; ?>
    
    <!-- Scripts -->
    <script src="../assets/plugins/jQuery/jquery.min.js"></script>
    <script src="../assets/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="../assets/js/script.js"></script>
    
    <script>
        // Toggle password visibility
        document.querySelectorAll('.toggle-password').forEach(icon => {
            icon.addEventListener('click', function() {
                const input = document.querySelector(this.getAttribute('data-bs-toggle'));
                if (input.type === 'password') {
                    input.type = 'text';
                    this.classList.remove('fa-eye-slash');
                    this.classList.add('fa-eye');
                } else {
                    input.type = 'password';
                    this.classList.remove('fa-eye');
                    this.classList.add('fa-eye-slash');
                }
            });
        });
    </script>
</body>
</html>