<?php
require_once __DIR__ . '/includes/auth.php'; // Giriş kontrolü
require_once __DIR__ . '/includes/header.php'; // Header'ı dahil et

global $db, $translations;
$user_id = $_SESSION['user_id'];

$profile_success = null;
$profile_error = null;
$password_success = null;
$password_error = null;

// Profil güncelleme işlemi
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    $username = trim($_POST['username'] ?? '');
    $lang = $_POST['lang'] ?? 'tr';
    $theme = $_POST['theme'] ?? 'light';
    $csrf_token = $_POST['csrf_token'] ?? '';

    if (!verify_csrf_token($csrf_token)) {
        $profile_error = __('error_occurred', $translations);
    } elseif (empty($username)) {
        $profile_error = __('fill_all_fields', $translations);
    } elseif (!in_array($lang, ['tr', 'en'])) {
        $profile_error = __('invalid_language', $translations);
    } elseif (!in_array($theme, ['light', 'dark'])) {
        $profile_error = __('invalid_theme', $translations);
    } elseif (!$db) {
        $profile_error = __('db_error', $translations);
    } else {
        try {
            // Sadece kullanıcı adı kontrolü yap
            $stmt = $db->prepare("SELECT id FROM users WHERE username = ? AND id != ?");
            $stmt->execute([$username, $user_id]);
            if ($stmt->fetch()) {
                $profile_error = __('username_taken', $translations);
            } else {
                $stmt = $db->prepare("UPDATE users SET username = ?, lang = ?, theme = ? WHERE id = ?");
                $stmt->execute([$username, $lang, $theme, $user_id]);

                // Session ve Cookie'leri güncelle
                $_SESSION['username'] = $username;
                $_SESSION['lang'] = $lang;
                $_SESSION['theme'] = $theme;
                setcookie('lang', $lang, time() + (365 * 24 * 60 * 60), "/");
                setcookie('theme', $theme, time() + (365 * 24 * 60 * 60), "/");

                $profile_success = __('profile_updated', $translations);
                echo "<script>window.location.href = window.location.href;</script>";
                exit;
            }
        } catch (PDOException $e) {
            $profile_error = __('db_error', $translations);
        }
    }
}

// Şifre değiştirme işlemi
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])) {
    $current_password = trim($_POST['current_password'] ?? '');
    $new_password = trim($_POST['new_password'] ?? '');
    $confirm_new_password = trim($_POST['confirm_new_password'] ?? '');
    $csrf_token = $_POST['csrf_token'] ?? '';

     if (!verify_csrf_token($csrf_token)) {
        $password_error = __('error_occurred', $translations);
    } elseif (empty($current_password) || empty($new_password) || empty($confirm_new_password)) {
        $password_error = __('fill_all_fields', $translations);
    } elseif ($new_password !== $confirm_new_password) {
        $password_error = __('passwords_do_not_match', $translations);
    } elseif (strlen($new_password) < 6) {
        $password_error = __('password_too_short', $translations);
    } elseif (!$db) { // Veritabanı bağlantısı kontrolü
        $password_error = __('db_error', $translations);
    } else {
        try {
            // Mevcut şifreyi doğrula
            $stmt = $db->prepare("SELECT password FROM users WHERE id = ?");
            $stmt->execute([$user_id]);
            $user = $stmt->fetch();

            if ($user && password_verify($current_password, $user['password'])) {
                // Yeni şifreyi hashle ve güncelle
                $hashed_new_password = password_hash($new_password, PASSWORD_DEFAULT);
                $stmt = $db->prepare("UPDATE users SET password = ? WHERE id = ?");
                $stmt->execute([$hashed_new_password, $user_id]);
                $password_success = __('password_updated', $translations);
            } else {
                $password_error = __('invalid_current_password', $translations);
            }
        } catch (PDOException $e) {
            $password_error = __('db_error', $translations);
        }
    }
}

// Kullanıcı bilgilerini formda göstermek için al
$user_data = null;
if ($db) { // Veritabanı bağlantısı varsa çek
    try {
        $stmt = $db->prepare("SELECT username, email, lang, theme FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $user_data = $stmt->fetch();
    } catch (PDOException $e) {
        $profile_error = __('db_error', $translations);
    }
} else {
     $profile_error = __('db_error', $translations);
}

?>

<div class="max-w-[1000px] mx-auto px-4 py-8">
    <div class="flex items-center justify-between mb-6">
        <h1 class="text-2xl font-bold text-gray-900 dark:text-white"><?php echo __('profile_settings', $translations); ?></h1>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
        <!-- Profil Bilgileri Formu -->
        <div class="bg-white dark:bg-gray-800 shadow-sm rounded-xl p-6 border border-gray-200 dark:border-gray-700">
            <h2 class="text-lg font-semibold text-gray-900 dark:text-white mb-4"><?php echo __('update_profile', $translations); ?></h2>

            <?php if ($profile_success): ?>
                <div class="bg-primary-50 dark:bg-primary-900/50 border border-primary-200 dark:border-primary-800 text-primary-800 dark:text-primary-200 px-4 py-3 rounded-lg mb-4" role="alert">
                    <span class="block sm:inline"><?php echo e($profile_success); ?></span>
                </div>
            <?php endif; ?>
            <?php if ($profile_error): ?>
                <div class="bg-red-50 dark:bg-red-900/50 border border-red-200 dark:border-red-800 text-red-800 dark:text-red-200 px-4 py-3 rounded-lg mb-4" role="alert">
                    <span class="block sm:inline"><?php echo e($profile_error); ?></span>
                </div>
            <?php endif; ?>

            <?php if ($user_data): ?>
                <form action="profile.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($user_data['username']); ?>" required
                               class="mt-1 block w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-lg shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary-500 dark:focus:ring-primary-500 focus:border-primary-500 dark:focus:border-primary-500 sm:text-sm transition duration-150 ease-in-out">
                    </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($user_data['email']); ?>" readonly
                               class="mt-1 block w-full px-3 py-2 bg-gray-50 dark:bg-gray-800 border border-gray-300 dark:border-gray-700 rounded-lg shadow-sm placeholder-gray-400 focus:outline-none cursor-not-allowed sm:text-sm">
                        <p class="mt-1 text-sm text-gray-500 dark:text-gray-400"><?php echo __('email_cannot_be_changed', $translations); ?></p>
                    </div>
                    <div class="mb-4">
                        <label for="lang" class="block text-sm font-medium text-gray-700 dark:text-gray-300"><?php echo __('language', $translations); ?></label>
                        <select name="lang" id="lang" class="mt-1 block w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-primary-500 dark:focus:ring-primary-500 focus:border-primary-500 dark:focus:border-primary-500 sm:text-sm transition duration-150 ease-in-out">
                            <option value="tr" <?php echo $user_data['lang'] === 'tr' ? 'selected' : ''; ?>>Türkçe</option>
                            <option value="en" <?php echo $user_data['lang'] === 'en' ? 'selected' : ''; ?>>English</option>
                        </select>
                    </div>
                    <div class="mb-4">
                        <label for="theme" class="block text-sm font-medium text-gray-700 dark:text-gray-300"><?php echo __('theme', $translations); ?></label>
                        <select name="theme" id="theme" class="mt-1 block w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-primary-500 dark:focus:ring-primary-500 focus:border-primary-500 dark:focus:border-primary-500 sm:text-sm transition duration-150 ease-in-out">
                            <option value="light" <?php echo $user_data['theme'] === 'light' ? 'selected' : ''; ?>>Light</option>
                            <option value="dark" <?php echo $user_data['theme'] === 'dark' ? 'selected' : ''; ?>>Dark</option>
                        </select>
                    </div>
                    <div>
                        <button type="submit" name="update_profile" class="w-full flex justify-center py-2 px-4 border border-transparent rounded-lg 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 duration-150 ease-in-out">
                            <?php echo __('update_profile', $translations); ?>
                        </button>
                    </div>
                </form>
            <?php endif; ?>
        </div>

        <!-- Şifre Değiştirme Formu -->
        <div class="bg-white dark:bg-gray-800 shadow-sm rounded-xl p-6 border border-gray-200 dark:border-gray-700">
            <h2 class="text-lg font-semibold text-gray-900 dark:text-white mb-4"><?php echo __('change_password', $translations); ?></h2>

            <?php if ($password_success): ?>
                <div class="bg-primary-50 dark:bg-primary-900/50 border border-primary-200 dark:border-primary-800 text-primary-800 dark:text-primary-200 px-4 py-3 rounded-lg mb-4" role="alert">
                    <span class="block sm:inline"><?php echo e($password_success); ?></span>
                </div>
            <?php endif; ?>
            <?php if ($password_error): ?>
                <div class="bg-red-50 dark:bg-red-900/50 border border-red-200 dark:border-red-800 text-red-800 dark:text-red-200 px-4 py-3 rounded-lg mb-4" role="alert">
                    <span class="block sm:inline"><?php echo e($password_error); ?></span>
                </div>
            <?php endif; ?>

            <form action="profile.php" method="POST">
                <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                <div class="mb-4">
                    <label for="current_password" class="block text-sm font-medium text-gray-700 dark:text-gray-300"><?php echo __('current_password', $translations); ?></label>
                    <input type="password" name="current_password" id="current_password" required
                           class="mt-1 block w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-lg shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary-500 dark:focus:ring-primary-500 focus:border-primary-500 dark:focus:border-primary-500 sm:text-sm transition duration-150 ease-in-out">
                </div>
                <div class="mb-4">
                    <label for="new_password" class="block text-sm font-medium text-gray-700 dark:text-gray-300"><?php echo __('new_password', $translations); ?></label>
                    <input type="password" name="new_password" id="new_password" required
                           class="mt-1 block w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-lg shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary-500 dark:focus:ring-primary-500 focus:border-primary-500 dark:focus:border-primary-500 sm:text-sm transition duration-150 ease-in-out">
                </div>
                <div class="mb-6">
                    <label for="confirm_new_password" class="block text-sm font-medium text-gray-700 dark:text-gray-300"><?php echo __('confirm_new_password', $translations); ?></label>
                    <input type="password" name="confirm_new_password" id="confirm_new_password" required
                           class="mt-1 block w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-lg shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary-500 dark:focus:ring-primary-500 focus:border-primary-500 dark:focus:border-primary-500 sm:text-sm transition duration-150 ease-in-out">
                </div>
                <div>
                    <button type="submit" name="change_password" class="w-full flex justify-center py-2 px-4 border border-transparent rounded-lg 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 duration-150 ease-in-out">
                        <?php echo __('update_password', $translations); ?>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php
require_once __DIR__ . '/includes/footer.php'; // Footer'ı dahil et
?> 