<?php
session_start();
if (!file_exists(__DIR__ . '/db.php')) {
    header("Location: install");
    exit;
}
require 'db.php';
require 'lang.php';

if (isset($_SESSION['user_id'])) {
    header("Location: ./");
    exit;
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username']);
    $email    = trim($_POST['email']);
    $password = $_POST['password'];

    if ($username && $email && $password) {
        $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
        $stmt->execute([$username, $email]);
        if ($stmt->rowCount() > 0) {
            $error = $t['error_taken'];
        } else {
            $avatarPath = 'assets/default_avatar.png';
            if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] === 0) {
                $ext = pathinfo($_FILES['avatar']['name'], PATHINFO_EXTENSION);
                $newName = time() . '_' . uniqid() . '.' . $ext;
                $target = 'assets/avatars/' . $newName;
                if (!is_dir('assets/avatars')) mkdir('assets/avatars', 0777, true);
                if (move_uploaded_file($_FILES['avatar']['tmp_name'], $target)) {
                    $avatarPath = $target;
                }
            }

            $hash = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("INSERT INTO users (username, email, password, avatar) VALUES (?, ?, ?, ?)");
            if ($stmt->execute([$username, $email, $hash, $avatarPath])) {
                $_SESSION['user_id'] = $pdo->lastInsertId();
                $_SESSION['username'] = $username;
                $_SESSION['avatar'] = $avatarPath;
                $_SESSION['role'] = 'user'; // Default
                header("Location: ./");
                exit;
            } else {
                $error = $t['registration_failed'];
            }
        }
    } else {
        $error = $t['error_fields'];
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $t['register_title']; ?> - Chat</title>
    <link rel="stylesheet" href="assets/style.css">
    <style>
        body {
            margin: 0;
            padding: 0;
            min-height: 100vh;
            overflow: hidden;
            position: relative;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 25%, #f093fb 50%, #4facfe 75%, #00f2fe 100%);
            background-size: 400% 400%;
            animation: gradientShift 15s ease infinite;
        }

        @keyframes gradientShift {
            0% {
                background-position: 0% 50%;
            }

            50% {
                background-position: 100% 50%;
            }

            100% {
                background-position: 0% 50%;
            }
        }

        /* Animated particles */
        .particles {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            overflow: hidden;
            z-index: 1;
            pointer-events: none;
        }

        .particle {
            position: absolute;
            width: 10px;
            height: 10px;
            background: rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            animation: float 20s infinite;
        }

        @keyframes float {

            0%,
            100% {
                transform: translateY(0) translateX(0) scale(1);
                opacity: 0;
            }

            10% {
                opacity: 0.8;
            }

            90% {
                opacity: 0.8;
            }

            100% {
                transform: translateY(-100vh) translateX(100px) scale(0.5);
                opacity: 0;
            }
        }

        .auth-container {
            position: relative;
            z-index: 10;
            backdrop-filter: blur(10px);
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37);
        }

        .file-input-wrapper {
            margin-bottom: 20px;
            position: relative;
        }

        .file-input {
            display: none;
        }

        .file-label {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            background: rgba(255, 255, 255, 0.05);
            border: 1px dashed rgba(255, 255, 255, 0.3);
            border-radius: 12px;
            cursor: pointer;
            transition: all 0.3s ease;
            color: rgba(255, 255, 255, 0.8);
            font-size: 0.9rem;
        }

        .file-label:hover {
            background: rgba(255, 255, 255, 0.1);
            border-color: rgba(255, 255, 255, 0.6);
            transform: translateY(-2px);
        }

        .upload-btn-text {
            margin-left: auto;
            background: rgba(255, 255, 255, 0.15);
            padding: 4px 10px;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
    </style>
</head>

<body>
    <!-- Animated particles background -->
    <div class="particles" id="particles"></div>

    <div class="auth-container">
        <?php echo lang_links(); ?>

        <div style="text-align: center; margin-bottom: 25px;">
            <img src="assets/logo.png" alt="Logo" style="width: 80px; height: 80px; margin-bottom: 12px; filter: drop-shadow(0 4px 6px rgba(0,0,0,0.3)); border-radius: 20px;">
            <p style="color: rgba(255,255,255,0.95); font-size: 1.1rem; font-weight: 600; margin: 0 0 5px 0; text-shadow: 0 2px 4px rgba(0,0,0,0.4); letter-spacing: 0.5px;">
                <?php echo $t['audio_video_calls']; ?>
            </p>
            <p style="color: rgba(255,255,255,0.6); font-size: 0.75rem; font-weight: 400; margin: 0; text-transform: uppercase; letter-spacing: 1px;">
                <?php echo $t['next_gen_messenger']; ?>
            </p>
        </div>

        <h2><?php echo $t['register_title']; ?></h2>
        <?php if ($error): ?>
            <p style="color: #cf6679; text-align: center;"><?php echo htmlspecialchars($error); ?></p>
        <?php endif; ?>
        <form method="POST" enctype="multipart/form-data">
            <input type="text" name="username" placeholder="<?php echo $t['username']; ?>" required>
            <input type="email" name="email" placeholder="<?php echo $t['email']; ?>" required>
            <input type="password" name="password" placeholder="<?php echo $t['password']; ?>" required>
            <div class="file-input-wrapper">
                <input type="file" name="avatar" id="avatarInput" accept="image/*" class="file-input">
                <label for="avatarInput" class="file-label">
                    <div id="previewContainer" style="width: 40px; height: 40px; border-radius: 50%; background: rgba(255,255,255,0.1); display: flex; align-items: center; justify-content: center; overflow: hidden; flex-shrink: 0; box-shadow: 0 2px 5px rgba(0,0,0,0.2);">
                        <span id="defaultIcon" style="font-size: 1.2rem;">📷</span>
                        <img id="avatarPreview" src="" style="width: 100%; height: 100%; object-fit: cover; display: none;">
                    </div>
                    <span id="fileName" style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 190px;"><?php echo $t['avatar_optional']; ?></span>
                    <span class="upload-btn-text">Select</span>
                </label>
            </div>
            <button type="submit"><?php echo $t['register_btn']; ?></button>
        </form>
        <div class="link">
            <?php echo $t['has_account']; ?> <a href="login"><?php echo $t['login_btn']; ?></a>
        </div>
        <div style="margin-top: 20px; text-align: center; font-size: 0.7rem; color: rgba(255,255,255,0.4);">
            &copy; <?php echo date('Y'); ?> by <strong>ANUS_TANGA</strong>
        </div>
    </div>

    <script>
        // Avatar Preview
        document.getElementById('avatarInput').addEventListener('change', function(e) {
            const file = this.files[0];
            const fileNameEl = document.getElementById('fileName');
            const previewEl = document.getElementById('avatarPreview');
            const iconEl = document.getElementById('defaultIcon');

            if (file) {
                fileNameEl.textContent = file.name;

                const reader = new FileReader();
                reader.onload = function(ev) {
                    previewEl.src = ev.target.result;
                    previewEl.style.display = 'block';
                    iconEl.style.display = 'none';
                }
                reader.readAsDataURL(file);
            } else {
                fileNameEl.textContent = '<?php echo $t['avatar_optional']; ?>';
                previewEl.style.display = 'none';
                iconEl.style.display = 'block';
                previewEl.src = '';
            }
        });

        // Generate particles
        const particlesContainer = document.getElementById('particles');
        const particleCount = 50;

        for (let i = 0; i < particleCount; i++) {
            const particle = document.createElement('div');
            particle.className = 'particle';
            particle.style.left = Math.random() * 100 + '%';
            particle.style.animationDelay = Math.random() * 20 + 's';
            particle.style.animationDuration = (15 + Math.random() * 10) + 's';
            particlesContainer.appendChild(particle);
        }
    </script>
</body>

</html>