<?php
require_once __DIR__ . '/config/database.php'; // Veritabanı ve temel ayarlar
global $db, $translations;

// Zaten giriş yapmışsa ana sayfaya yönlendir
if (is_logged_in()) {
    redirect('index.php');
}

$errors = [];
$success = null;

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

    // CSRF kontrolü
    if (!verify_csrf_token($csrf_token)) {
        $errors[] = __('error_occurred', $translations);
    } else {
        // Doğrulama kontrolleri
        if (empty($username)) {
            $errors[] = __('username_required', $translations); // Çeviri eklenmeli
        }
        if (empty($email)) {
            $errors[] = __('email_required', $translations); // Çeviri eklenmeli
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = __('invalid_email', $translations); // Çeviri eklenmeli
        }
        if (empty($password)) {
            $errors[] = __('password_required', $translations); // Çeviri eklenmeli
        } elseif (strlen($password) < 6) {
            $errors[] = __('password_too_short', $translations); // Çeviri eklenmeli (en az 6 karakter)
        }
        if ($password !== $confirm_password) {
            $errors[] = __('passwords_do_not_match', $translations);
        }

        // Veritabanı bağlantısı kontrolü
        if (!$db) {
            $errors[] = __('db_error', $translations);
        }

        // Hata yoksa veritabanı kontrolleri
        if (empty($errors) && $db) {
            try {
                // Kullanıcı adı kontrolü
                $stmt = $db->prepare("SELECT id FROM users WHERE username = ?");
                $stmt->execute([$username]);
                if ($stmt->fetch()) {
                    $errors[] = __('username_taken', $translations); // Çeviri eklenmeli
                }

                // E-posta kontrolü
                $stmt = $db->prepare("SELECT id FROM users WHERE email = ?");
                $stmt->execute([$email]);
                if ($stmt->fetch()) {
                    $errors[] = __('email_taken', $translations); // Çeviri eklenmeli
                }

                // Hata yoksa kullanıcıyı ekle
                if (empty($errors)) {
                    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                    $default_lang = 'tr'; // Varsayılan dil
                    $default_theme = 'light'; // Varsayılan tema

                    $stmt = $db->prepare("INSERT INTO users (username, email, password, lang, theme, created_at) VALUES (?, ?, ?, ?, ?, NOW())");
                    $stmt->execute([$username, $email, $hashed_password, $default_lang, $default_theme]);

                    $success = __('registration_successful', $translations); // Çeviri eklenmeli
                    // Kullanıcıyı otomatik giriş yaptırmak yerine login'e yönlendir
                    // header("Refresh: 3; url=login.php"); // 3 saniye sonra yönlendir
                }
            } catch (PDOException $e) {
                $errors[] = __('db_error', $translations);
                 // error_log("Registration Error: " . $e->getMessage());
            }
        }
    }
}

require_once __DIR__ . '/includes/header.php'; // Header'ı dahil et
?>

<div class="min-h-screen flex items-center justify-center bg-gray-100 dark:bg-gray-900 px-4">
    <!-- Ana Sayfaya Dönüş Butonu -->
    <a href="index.php" class="fixed top-4 left-4 inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary-600 hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 transition-all duration-300 transform hover:scale-105">
        <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"/>
        </svg>
        <?php echo __('home', $translations); ?>
    </a>

    <div class="max-w-md w-full bg-white dark:bg-gray-800 shadow-md rounded-lg p-8">
        <h2 class="text-2xl font-bold text-center text-gray-800 dark:text-white mb-6"><?php echo __('register', $translations); ?></h2>

        <?php if (!empty($errors)): ?>
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4" role="alert">
                <ul>
                    <?php foreach ($errors as $error): ?>
                        <li><?php echo e($error); ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative mb-4" role="alert">
                <span class="block sm:inline"><?php echo e($success); ?></span>
                 <p class="text-sm mt-2"><a href="login.php" class="font-medium text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-300"><?php echo __('go_to_login', $translations); // Çeviri eklenmeli ?></a></p>
            </div>
        <?php else: // Sadece başarı mesajı yoksa formu göster ?>
            <form action="register.php" method="POST">
                <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                <div class="mb-4">
                    <label for="username" class="block text-sm font-medium text-gray-700 dark:text-gray-300"><?php echo __('username', $translations); ?></label>
                    <input type="text" name="username" id="username" value="<?php echo e($_POST['username'] ?? ''); ?>" required
                           class="mt-1 block w-full px-3 py-2 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm">
                </div>
                <div class="mb-4">
                    <label for="email" class="block text-sm font-medium text-gray-700 dark:text-gray-300"><?php echo __('email', $translations); ?></label>
                    <input type="email" name="email" id="email" value="<?php echo e($_POST['email'] ?? ''); ?>" required
                           class="mt-1 block w-full px-3 py-2 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm">
                </div>
                <div class="mb-4">
                    <label for="password" class="block text-sm font-medium text-gray-700 dark:text-gray-300"><?php echo __('password', $translations); ?></label>
                    <input type="password" name="password" id="password" required
                           class="mt-1 block w-full px-3 py-2 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm">
                </div>
                <div class="mb-6">
                    <label for="confirm_password" class="block text-sm font-medium text-gray-700 dark:text-gray-300"><?php echo __('confirm_password', $translations); ?></label>
                    <input type="password" name="confirm_password" id="confirm_password" required
                           class="mt-1 block w-full px-3 py-2 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm">
                </div>
                <div>
                    <button type="submit" class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary-600 hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500">
                        <?php echo __('register', $translations); ?>
                    </button>
                </div>
            </form>
        <?php endif; ?>

        <p class="mt-6 text-center text-sm text-gray-600 dark:text-gray-400">
            <?php echo __('already_have_account', $translations); ?>
            <a href="login.php" class="font-medium text-primary-600 hover:text-primary-700 dark:text-primary-400 dark:hover:text-primary-300">
                <?php echo __('login', $translations); ?>
            </a>
        </p>
    </div>
</div>

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