<?php
require_once 'db.php';
session_start();

$errors = [];
$success = false;

if (isset($_FILES['profile-picture'])) {
    $uploadDir = '/../cdn.imators.com/uploads/';
    $cdnPrefix = 'https://cdn.imators.com/uploads/';
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    $maxFileSize = 5 * 1024 * 1024;

    if ($_FILES['profile-picture']['error'] === UPLOAD_ERR_OK) {
        $fileType = mime_content_type($_FILES['profile-picture']['tmp_name']);
        $fileSize = $_FILES['profile-picture']['size'];

        if (in_array($fileType, $allowedTypes) && $fileSize <= $maxFileSize) {
            $fileName = uniqid() . '_' . bin2hex(random_bytes(8)) . '.' . pathinfo($_FILES['profile-picture']['name'], PATHINFO_EXTENSION);
            $uploadPath = $uploadDir . $fileName;
            $cdnUrl = $cdnPrefix . $fileName;

            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }

            if (move_uploaded_file($_FILES['profile-picture']['tmp_name'], $uploadPath)) {
                $_SESSION['profile-picture'] = $cdnUrl;
            } else {
                $errors[] = "Error uploading image";
            }
        } else {
            $errors[] = "Invalid file type or size";
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $db = new Database();
    $conn = $db->connect();

    $username = htmlspecialchars(trim($_POST['username']));
    $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
    $password = $_POST['password'];
    $profilePicture = $_SESSION['profile-picture'] ?? null;
    
    $errors = [];

    if (empty($username) || strlen($username) < 3) {
        $errors[] = "Username must be at least 3 characters long";
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email address";
    }

    $stmt = $conn->prepare("SELECT id FROM utilisateurs WHERE email = ?");
    $stmt->execute([$email]);
    if ($stmt->rowCount() > 0) {
        $errors[] = "Email already exists";
    }

    $passwordErrors = [];
    if (strlen($password) < 8) {
        $passwordErrors[] = "Password must be at least 8 characters long";
    }
    if (!preg_match("/[A-Z]/", $password)) {
        $passwordErrors[] = "Password must contain at least one uppercase letter";
    }
    if (!preg_match("/[a-z]/", $password)) {
        $passwordErrors[] = "Password must contain at least one lowercase letter";
    }
    if (!preg_match("/[0-9]/", $password)) {
        $passwordErrors[] = "Password must contain at least one number";
    }
    $errors = array_merge($errors, $passwordErrors);

    if (empty($errors)) {
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
        $verificationCode = sprintf("%06d", mt_rand(0, 999999));
        
        try {
            $stmt = $conn->prepare("INSERT INTO utilisateurs (username, email, password, verification_code, `profile-picture`) VALUES (?, ?, ?, ?, ?)");
            if($stmt->execute([$username, $email, $hashedPassword, $verificationCode, $profilePicture])) {
                $_SESSION['pending_email'] = $email;
                header('Location: verify.php');
                exit;
            } else {
                $errors[] = "Registration failed";
            }
        } catch (PDOException $e) {
            $errors[] = "Registration failed: " . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Create Account - Imators</title>
    <meta name="description" content="Create your Imators account to access a multitude of features that give you control over the system at your fingertips.">

    <meta property="og:url" content="https://accounts.imators.com/register">
    <meta property="og:type" content="website">
    <meta property="og:title" content="Create Account - Imators">
    <meta property="og:description" content="Create your Imators account to access a multitude of features that give you control over the system at your fingertips.">
    <meta property="og:image" content="https://opengraph.b-cdn.net/production/images/fb6bc1ea-5744-46f1-bee6-fc033a6c6b56.png?token=_EL6e3nPPtxSgvlGKURhJgrJb5NireVFT99X4BXVrYA&height=600&width=1200&expires=33267345049">

    <meta name="twitter:card" content="summary_large_image">
    <meta property="twitter:domain" content="accounts.imators.com">
    <meta property="twitter:url" content="https://accounts.imators.com/register">
    <meta name="twitter:title" content="Create Account - Imators">
    <meta name="twitter:description" content="Create your Imators account to access a multitude of features that give you control over the system at your fingertips.">
    <meta name="twitter:image" content="https://opengraph.b-cdn.net/production/images/fb6bc1ea-5744-46f1-bee6-fc033a6c6b56.png?token=_EL6e3nPPtxSgvlGKURhJgrJb5NireVFT99X4BXVrYA&height=600&width=1200&expires=33267345049">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet">
    <link href="https://cdn.imators.com/logo.png" rel="icon" type="image/png" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Poppins', sans-serif;
            background: #000;
            color: #fff;
            overflow-x: hidden;
        }
        
        .container {
            height: 100vh;
            display: flex;
        }
        
        .image-section {
            width: 50%;
            background: linear-gradient(45deg, #0a0a0a, #1a1a1a);
            position: relative;
            overflow: hidden;
        }
        
        .image-section::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: url('./img_pc.png') center/cover;
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            filter: brightness(0.3);
        }
        
        .image-overlay {
            position: absolute;
            bottom: 40px;
            left: 40px;
            z-index: 2;
        }
        
        .form-section {
            width: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 40px;
            overflow-y: auto;
        }
        
        .form-container {
            width: 100%;
            max-width: 400px;
            max-height: 90vh;
            overflow-y: auto;
        }
        
        .logo {
            height: 40px;
            margin-bottom: 30px;
        }
        
        .title {
            font-size: 28px;
            font-weight: 300;
            margin-bottom: 8px;
            line-height: 1.2;
        }
        
        .subtitle {
            color: #666;
            font-size: 14px;
            margin-bottom: 30px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-label {
            display: block;
            font-size: 14px;
            margin-bottom: 8px;
            color: #ccc;
        }
        
        .form-input {
            width: 100%;
            padding: 12px 0;
            border: none;
            border-bottom: 1px solid #333;
            background: transparent;
            color: #fff;
            font-size: 16px;
            transition: border-color 0.3s;
        }
        
        .form-input:focus {
            outline: none;
            border-bottom-color: #fff;
        }
        
        .form-input.error {
            border-bottom-color: #dc3545;
        }
        
        .file-input {
            padding: 8px 0;
            border: 1px solid #333;
            border-radius: 4px;
            background: transparent;
            color: #ccc;
        }
        
        .password-container {
            position: relative;
        }
        
        .password-toggle {
            position: absolute;
            right: 0;
            bottom: 12px;
            background: none;
            border: none;
            color: #666;
            cursor: pointer;
            font-size: 14px;
        }
        
        .password-requirements {
            margin-top: 8px;
            font-size: 12px;
        }
        
        .password-check {
            display: flex;
            align-items: center;
            margin-bottom: 4px;
            color: #666;
            transition: color 0.3s;
        }
        
        .password-check i {
            margin-right: 8px;
            width: 12px;
        }
        
        .password-check.valid {
            color: #22c55e;
        }
        
        .password-check.invalid {
            color: #ef4444;
        }
        
        .profile-preview {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            object-fit: cover;
            margin: 10px auto;
            display: block;
        }
        
        .register-btn {
            width: 100%;
            padding: 16px;
            background: #fff;
            color: #000;
            border: none;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            margin-top: 30px;
            transition: background-color 0.3s;
        }
        
        .register-btn:hover {
            background: #f0f0f0;
        }
        
        .register-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        .links {
            margin-top: 30px;
            text-align: center;
        }
        
        .links a {
            color: #666;
            text-decoration: none;
            font-size: 14px;
            transition: color 0.3s;
        }
        
        .links a:hover {
            color: #fff;
        }
        
        .alert {
            padding: 12px;
            margin-bottom: 20px;
            border-radius: 4px;
            font-size: 14px;
        }
        
        .alert-error {
            background: rgba(220, 53, 69, 0.1);
            border: 1px solid #dc3545;
            color: #dc3545;
        }
        
        .terms-link {
            color: #22c55e;
            text-decoration: underline;
        }
        
        .mobile-register-btn {
            position: fixed;
            bottom: 30px;
            left: 50%;
            transform: translateX(-50%);
            background: #fff;
            color: #000;
            padding: 16px 40px;
            border: none;
            border-radius: 25px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1);
            z-index: 10;
            display: none;
        }
        
        @media (max-width: 768px) {
            .container {
                flex-direction: column;
            }
            
            .image-section {
                width: 100%;
                height: 30vh;
                transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1);
            }
            
            .image-section::before {
                background: url('./img_pc.png') center/cover;
                background-size: cover;
                background-position: center;
                background-repeat: no-repeat;
                filter: brightness(0.3);
            }
            
            .image-section.hidden {
                height: 0;
                opacity: 0;
            }
            
            .form-section {
                width: 100%;
                height: 70vh;
                padding: 20px;
                transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1);
            }
            
            .form-section.expanded {
                height: 100vh;
            }
            
            .mobile-register-btn {
                display: block;
            }
            
            .mobile-register-btn.hidden {
                opacity: 0;
                transform: translateX(-50%) translateY(100px);
                pointer-events: none;
            }
            
            .form-container {
                transform: translateY(50px);
                opacity: 0;
                transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1);
                max-height: 85vh;
            }
            
            .form-container.visible {
                transform: translateY(0);
                opacity: 1;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="image-section" id="imageSection">
            <div class="image-overlay">
                <img src="https://cdn.imators.com/logo.png" alt="Imators" class="logo">
                <h2 style="font-size: 24px; font-weight: 300;">Join Us</h2>
                <p style="color: #ccc; margin-top: 8px;">Create an account to manage your subscribed services with us</p>
            </div>
        </div>
        
        <div class="form-section" id="formSection">
            <div class="form-container" id="formContainer">
                <img src="https://cdn.imators.com/logo.png" alt="Imators" class="logo">
                
                <h1 class="title">Create Account</h1>
                <p class="subtitle">Join Imators today</p>
                
                <?php if (!empty($errors)): ?>
                    <div class="alert alert-error">
                        <ul style="list-style: disc; padding-left: 20px;">
                            <?php foreach ($errors as $error): ?>
                                <li><?php echo htmlspecialchars($error); ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                <?php endif; ?>
                
                <form method="POST" enctype="multipart/form-data" id="registerForm">
                    <div class="form-group">
                        <label class="form-label">Username</label>
                        <input type="text" name="username" class="form-input" required 
                            value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>">
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Email</label>
                        <input type="email" name="email" class="form-input" required 
                            value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>">
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Profile Picture (Optional)</label>
                        <input type="file" name="profile-picture" accept="image/*" class="form-input file-input">
                        
                        <?php if (!empty($_SESSION['profile-picture'])): ?>
                            <img src="<?php echo $_SESSION['profile-picture']; ?>" alt="Profile Preview" class="profile-preview">
                        <?php endif; ?>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Password</label>
                        <div class="password-container">
                            <input type="password" name="password" class="form-input" id="passwordField" required>
                            <button type="button" class="password-toggle" onclick="togglePassword()">Show</button>
                        </div>
                        
                        <div class="password-requirements">
                            <div class="password-check" id="length-check">
                                <i class="fas fa-times-circle"></i>
                                <span>At least 8 characters</span>
                            </div>
                            <div class="password-check" id="uppercase-check">
                                <i class="fas fa-times-circle"></i>
                                <span>One uppercase letter</span>
                            </div>
                            <div class="password-check" id="lowercase-check">
                                <i class="fas fa-times-circle"></i>
                                <span>One lowercase letter</span>
                            </div>
                            <div class="password-check" id="number-check">
                                <i class="fas fa-times-circle"></i>
                                <span>One number</span>
                            </div>
                        </div>
                    </div>
                    
                    <button type="submit" class="register-btn">
                        Create Account
                    </button>
                </form>
                
                <div class="links">
                    <a href="login.php">Already have an account? Login</a>
                </div>
                
                <p style="font-size: 12px; color: #666; margin-top: 20px; text-align: center;">
                    By creating an account, you agree to our 
                    <a href="https://imators.com/terms-of-use" class="terms-link">Terms of Service</a>
                </p>
            </div>
        </div>
        
        <button class="mobile-register-btn" id="mobileRegisterBtn" onclick="showRegisterForm()">
            Create my account
        </button>
    </div>

    <script>
    function togglePassword() {
        const field = document.getElementById('passwordField');
        const btn = document.querySelector('.password-toggle');
        
        if (field.type === 'password') {
            field.type = 'text';
            btn.textContent = 'Hide';
        } else {
            field.type = 'password';
            btn.textContent = 'Show';
        }
    }

    function showRegisterForm() {
        const imageSection = document.getElementById('imageSection');
        const formSection = document.getElementById('formSection');
        const formContainer = document.getElementById('formContainer');
        const mobileBtn = document.getElementById('mobileRegisterBtn');
        
        imageSection.classList.add('hidden');
        formSection.classList.add('expanded');
        mobileBtn.classList.add('hidden');
        
        setTimeout(() => {
            formContainer.classList.add('visible');
        }, 300);
    }

    const password = document.getElementById('passwordField');
    const lengthCheck = document.getElementById('length-check');
    const uppercaseCheck = document.getElementById('uppercase-check');
    const lowercaseCheck = document.getElementById('lowercase-check');
    const numberCheck = document.getElementById('number-check');

    const requirements = {
        length: false,
        uppercase: false,
        lowercase: false,
        number: false
    };

    function updateRequirement(element, valid) {
        element.classList.toggle('valid', valid);
        element.classList.toggle('invalid', !valid);
        element.querySelector('i').className = valid ? 'fas fa-check-circle' : 'fas fa-times-circle';
    }

    function checkPassword(password) {
        requirements.length = password.length >= 8;
        requirements.uppercase = /[A-Z]/.test(password);
        requirements.lowercase = /[a-z]/.test(password);
        requirements.number = /[0-9]/.test(password);

        updateRequirement(lengthCheck, requirements.length);
        updateRequirement(uppercaseCheck, requirements.uppercase);
        updateRequirement(lowercaseCheck, requirements.lowercase);
        updateRequirement(numberCheck, requirements.number);
    }

    password.addEventListener('input', (e) => {
        checkPassword(e.target.value);
    });

    checkPassword(password.value);
    </script>
</body>
</html>