<?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');
}

$error = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $usernameOrEmail = trim($_POST['username_or_email'] ?? '');
    $password = trim($_POST['password'] ?? '');
    $remember = isset($_POST['remember']); // "Beni Hatırla" işaretli mi?
    $csrf_token = $_POST['csrf_token'] ?? '';

    // CSRF kontrolü
    if (!verify_csrf_token($csrf_token)) {
        $error = __('error_occurred', $translations); // Genel bir hata mesajı
    } elseif (empty($usernameOrEmail) || empty($password)) {
        $error = __('fill_all_fields', $translations); // Bu çeviri eklenmeli
    } elseif (!isset($db) || !($db instanceof PDO)) { // Veritabanı bağlantısı kontrolü
        $error = __('db_error', $translations); 
    } else {
        try {
            // Kullanıcı adı veya e-posta ile kullanıcıyı bul
            $sql = "SELECT id, username, password, is_admin, is_banned, lang, theme FROM users WHERE username = :username OR email = :email";
            $stmt = $db->prepare($sql);
            if (!$stmt) {
                throw new PDOException("Sorgu hazırlama hatası");
            }
            
            $stmt->bindParam(':username', $usernameOrEmail);
            $stmt->bindParam(':email', $usernameOrEmail);
            $stmt->execute();
            $user = $stmt->fetch();

            if ($user && password_verify($password, $user['password'])) {
                if ($user['is_banned']) {
                    $error = __('banned_message', $translations);
                } else {
                    // Başarılı giriş
                    session_regenerate_id(true); // Oturum kimliğini yeniden oluştur

                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['username'] = $user['username'];
                    $_SESSION['is_admin'] = (int)$user['is_admin']; // Integer olarak sakla
                    $_SESSION['lang'] = $user['lang']; // Kullanıcının dil tercihini session'a ata
                    $_SESSION['theme'] = $user['theme']; // Kullanıcının tema tercihini session'a ata

                    // "Beni Hatırla" işaretliyse cookie oluştur (örneğin 30 gün)
                    if ($remember) {
                        $token = bin2hex(random_bytes(16));
                        $expiry = time() + (30 * 24 * 60 * 60); // 30 gün
                        // TODO: Remember me token'ını veritabanında saklama ve doğrulama mekanizması eklenmeli
                        // setcookie('remember_me_token', $token, $expiry, "/", "", false, true); // HttpOnly
                    }

                    // Kullanıcının session'daki dil ve tema tercihine göre cookie'leri güncelle
                    setcookie('lang', $user['lang'], time() + (365 * 24 * 60 * 60), "/");
                    setcookie('theme', $user['theme'], time() + (365 * 24 * 60 * 60), "/");

                    redirect('index.php');
                }
            } else {
                $error = __('invalid_credentials', $translations); // Bu çeviri eklenmeli
            }
        } catch (PDOException $e) {
            // Üretime hazır hata mesajı
            $error = __('db_error', $translations);
            
            // Hatayı loglama
            error_log("Login Query PDOException: " . $e->getMessage());
        }
    }
}

// Hata mesajı varsa URL'den al (örn. banlanma durumu)
if (isset($_GET['error'])) {
    if ($_GET['error'] === 'banned') {
        $error = __('banned_message', $translations);
    }
}

// Header'ı burada dahil et, çünkü redirect'ten önce çıktı olmamalı
require_once __DIR__ . '/includes/header.php';
?>

<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 __('login', $translations); ?></h2>

        <?php if ($error): ?>
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4" role="alert">
                <span class="block sm:inline"><?php echo e($error); ?></span>
            </div>
        <?php endif; ?>

        <form action="login.php" method="POST">
             <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
            <div class="mb-4">
                <label for="username_or_email" class="block text-sm font-medium text-gray-700 dark:text-gray-300"><?php echo __('username', $translations); ?> / <?php echo __('email', $translations); ?></label>
                <input type="text" name="username_or_email" id="username_or_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="flex items-center justify-between mb-6">
                <div class="flex items-center">
                    <input id="remember" name="remember" type="checkbox" class="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded">
                    <label for="remember" class="ml-2 block text-sm text-gray-900 dark:text-gray-300">
                        <?php echo __('remember_me', $translations); ?>
                    </label>
                </div>
                <!-- Şifremi Unuttum özelliği daha sonra eklenebilir -->
                <!-- <div class="text-sm">
                    <a href="forgot-password.php" class="font-medium text-primary-600 hover:text-primary-700 dark:text-primary-400 dark:hover:text-primary-300">
                        <?php echo __('forgot_password', $translations); ?>
                    </a>
                </div> -->
            </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 __('login', $translations); ?>
                </button>
            </div>
        </form>

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

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