<?php
/**
 * Unamused Registration - Security Hardened
 */
define('UNAMUSED_APP', true);
require_once '../config/database.php';
require_once '../includes/functions.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start([
        'cookie_httponly' => true,
        'cookie_samesite' => 'Strict',
        'use_strict_mode' => true
    ]);
}

// Already logged in
if (isset($_SESSION['user_id'])) {
    header('Location: ../dashboard.php');
    exit();
}

$errors = [];

// CSRF token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    $_SESSION['csrf_token_time'] = time();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate CSRF
    $token = $_POST['csrf_token'] ?? '';
    if (!hash_equals($_SESSION['csrf_token'] ?? '', $token)) {
        $errors[] = "Invalid security token.";
        http_response_code(403);
    }
    
    // Rate limit check on IP
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $ip = filter_var($ip, FILTER_VALIDATE_IP) ? $ip : 'unknown';
    
    try {
        $hashedIp = hash('sha256', $ip);
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM login_attempts WHERE ip_hash = ? AND created_at > DATE_SUB(NOW(), INTERVAL 1 HOUR)");
        $stmt->execute([$hashedIp]);
        if ($stmt->fetchColumn() > 10) {
            $errors[] = "Too many attempts. Please try again later.";
            http_response_code(429);
        }
    } catch (PDOException $e) {
        error_log("Rate check failed: " . $e->getMessage());
    }
    
    // Sanitize and validate inputs
    $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
    $password = $_POST['password'] ?? '';
    $confirm = $_POST['confirm_password'] ?? '';
    $firstName = preg_replace('/[^a-zA-Z\s\-]/', '', substr($_POST['first_name'] ?? '', 0, 50));
    $lastName = preg_replace('/[^a-zA-Z\s\-]/', '', substr($_POST['last_name'] ?? '', 0, 50));
    $agreeTerms = isset($_POST['agree_terms']);
    
    // Validations
    if (!$email) $errors[] = "Valid email required.";
    if (strlen($password) < 12) $errors[] = "Password must be 12+ characters.";
    if (!preg_match('/[A-Z]/', $password)) $errors[] = "Password needs uppercase.";
    if (!preg_match('/[a-z]/', $password)) $errors[] = "Password needs lowercase.";
    if (!preg_match('/[0-9]/', $password)) $errors[] = "Password needs a number.";
    if (!preg_match('/[^A-Za-z0-9]/', $password)) $errors[] = "Password needs special character.";
    if ($password !== $confirm) $errors[] = "Passwords don't match.";
    if (strlen($firstName) < 2) $errors[] = "First name required.";
    if (strlen($lastName) < 2) $errors[] = "Last name required.";
    if (!$agreeTerms) $errors[] = "You must agree to terms.";
    
    // Check email exists
    if (empty($errors)) {
        try {
            $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ? LIMIT 1");
            $stmt->execute([strtolower($email)]);
            if ($stmt->fetch()) {
                $errors[] = "Email already registered.";
            }
        } catch (PDOException $e) {
            error_log("Email check failed: " . $e->getMessage());
            $errors[] = "System error. Please try again.";
        }
    }
    
    // Create account
    if (empty($errors)) {
        try {
            $verifyToken = bin2hex(random_bytes(32));
            $hash = password_hash($password, PASSWORD_ARGON2ID, ['memory_cost' => 65536, 'time_cost' => 4]);
            
            $stmt = $pdo->prepare("
                INSERT INTO users (email, password_hash, first_name, last_name, 
                                 verification_token, verification_expires, created_at,
                                 email_verified)
                VALUES (?, ?, ?, ?, ?, DATE_ADD(NOW(), INTERVAL 24 HOUR), NOW(), 0)
            ");
            
            $stmt->execute([
                strtolower($email),
                $hash,
                $firstName,
                $lastName,
                $verifyToken
            ]);
            
            $userId = $pdo->lastInsertId();
            
            // Log creation
            $stmt = $pdo->prepare("INSERT INTO login_attempts (ip_hash, email, success, created_at) VALUES (?, ?, 1, NOW())");
            $stmt->execute([$hashedIp, strtolower($email)]);
            
            // Create session
            session_regenerate_id(true);
            $_SESSION['user_id'] = (int)$userId;
            $_SESSION['user_email'] = strtolower($email);
            $_SESSION['user_first_name'] = htmlspecialchars($firstName, ENT_QUOTES, 'UTF-8');
            $_SESSION['verified'] = false;
            $_SESSION['pending_verification'] = true;
            
            // Queue email (implementation needed)
            // sendVerificationEmail($email, $verifyToken);
            
            header('Location: verify-required.php');
            exit();
            
        } catch (PDOException $e) {
            error_log("Registration failed: " . $e->getMessage());
            $errors[] = "Registration failed. Please try again.";
        }
    }
    
    // Regenerate token on failure
    if (!empty($errors)) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        $_SESSION['csrf_token_time'] = time();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Account | Unamused</title>
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Lucide Icons -->
    <script src="https://unpkg.com/lucide@latest"></script>
    
    <!-- Google Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&family=Crimson+Text:ital,wght@0,400;0,600;1,400&display=swap" rel="stylesheet">
    
    <style>
        :root {
            --color-bg: #fafaf9;
            --color-text: #1c1917;
            --color-accent: #dc2626;
            --color-border: #e7e5e4;
        }
        
        body {
            font-family: 'Inter', sans-serif;
            background-color: var(--color-bg);
            color: var(--color-text);
        }
        
        .font-serif {
            font-family: 'Crimson Text', serif;
        }
    </style>
</head>
<body class="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
    <div class="max-w-md w-full space-y-8 bg-white p-8 rounded-lg shadow-lg">
        <div>
            <a href="../index.html" class="flex items-center justify-center mb-6">
                <span class="text-2xl font-serif font-semibold">unamused<span class="text-red-600">.</span></span>
            </a>
            <h2 class="text-center text-3xl font-serif font-bold text-gray-900">
                Create your account
            </h2>
            <p class="mt-2 text-center text-sm text-gray-600">
                Join Unamused for a better shopping experience
            </p>
        </div>
        
        <?php if (!empty($errors)): ?>
            <div class="bg-red-50 border-l-4 border-red-400 p-4 mb-4">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <i data-lucide="alert-circle" class="h-5 w-5 text-red-400"></i>
                    </div>
                    <div class="ml-3">
                        <h3 class="text-sm font-medium text-red-800">Please fix the following errors:</h3>
                        <div class="mt-2 text-sm text-red-700">
                            <ul class="list-disc pl-5 space-y-1">
                                <?php foreach ($errors as $error): ?>
                                    <li><?php echo htmlspecialchars($error); ?></li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        <?php endif; ?>
        
        <form class="mt-8 space-y-6" method="POST" action="">
            <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label for="first_name" class="block text-sm font-medium text-gray-700">First name *</label>
                    <input id="first_name" name="first_name" type="text" required 
                           class="mt-1 appearance-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-gray-900 focus:z-10 sm:text-sm"
                           value="<?php echo isset($first_name) ? htmlspecialchars($first_name) : ''; ?>">
                </div>
                
                <div>
                    <label for="last_name" class="block text-sm font-medium text-gray-700">Last name *</label>
                    <input id="last_name" name="last_name" type="text" required 
                           class="mt-1 appearance-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-gray-900 focus:z-10 sm:text-sm"
                           value="<?php echo isset($last_name) ? htmlspecialchars($last_name) : ''; ?>">
                </div>
            </div>
            
            <div>
                <label for="email" class="block text-sm font-medium text-gray-700">Email address *</label>
                <input id="email" name="email" type="email" autocomplete="email" required 
                       class="mt-1 appearance-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-gray-900 focus:z-10 sm:text-sm"
                       value="<?php echo isset($email) ? htmlspecialchars($email) : ''; ?>">
            </div>
            
            <div>
                <label for="password" class="block text-sm font-medium text-gray-700">Password *</label>
                <input id="password" name="password" type="password" autocomplete="new-password" required 
                       class="mt-1 appearance-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-gray-900 focus:z-10 sm:text-sm">
                <p class="mt-1 text-xs text-gray-500">
                    Must be at least 8 characters with uppercase, lowercase, number, and special character.
                </p>
            </div>
            
            <div>
                <label for="confirm_password" class="block text-sm font-medium text-gray-700">Confirm password *</label>
                <input id="confirm_password" name="confirm_password" type="password" autocomplete="new-password" required 
                       class="mt-1 appearance-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-gray-900 focus:z-10 sm:text-sm">
            </div>
            
            <div class="flex items-center">
                <input id="agree_terms" name="agree_terms" type="checkbox" required 
                       class="h-4 w-4 text-gray-900 focus:ring-gray-900 border-gray-300 rounded">
                <label for="agree_terms" class="ml-2 block text-sm text-gray-900">
                    I agree to the <a href="../legal.html" class="font-medium text-gray-900 hover:underline">Terms & Conditions</a> and <a href="#" class="font-medium text-gray-900 hover:underline">Privacy Policy</a>
                </label>
            </div>
            
            <div>
                <button type="submit" 
                        class="group relative w-full flex justify-center py-3 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-gray-900 hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900">
                    <span class="absolute left-0 inset-y-0 flex items-center pl-3">
                        <i data-lucide="user-plus" class="h-5 w-5 text-gray-300 group-hover:text-white"></i>
                    </span>
                    Create account
                </button>
            </div>
        </form>
        
        <div class="text-center mt-4">
            <p class="text-sm text-gray-600">
                Already have an account?
                <a href="login.php" class="font-medium text-gray-900 hover:underline">Sign in</a>
            </p>
        </div>
    </div>
    
    <!-- Lucide Icons -->
    <script src="https://unpkg.com/lucide@latest"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            if (typeof lucide !== 'undefined') {
                lucide.createIcons();
            }
            
            // Password strength indicator
            const passwordInput = document.getElementById('password');
            const confirmInput = document.getElementById('confirm_password');
            
            function checkPasswordMatch() {
                if (passwordInput.value !== confirmInput.value) {
                    confirmInput.setCustomValidity("Passwords don't match");
                } else {
                    confirmInput.setCustomValidity('');
                }
            }
            
            if (passwordInput && confirmInput) {
                passwordInput.addEventListener('input', checkPasswordMatch);
                confirmInput.addEventListener('input', checkPasswordMatch);
            }
        });
    </script>
</body>
</html>