<?php
session_start();
require_once '../includes/config.php';
require_once 'functions.php';

requireLogin();

$admin_id = $_SESSION['admin_id'];

// Profil Güncelleme
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    if (verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $username = trim($_POST['username']);
        $email = trim($_POST['email']);
        
        try {
            $stmt = $pdo->prepare("UPDATE admin_users SET username = ?, email = ? WHERE id = ?");
            $stmt->execute([$username, $email, $admin_id]);
            
            $_SESSION['admin_username'] = $username;
            $_SESSION['admin_email'] = $email;
            
            setSuccessMessage('Profil başarıyla güncellendi!');
            header('Location: profile.php');
            exit;
        } catch (PDOException $e) {
            setErrorMessage('Profil güncellenirken hata oluştu: ' . $e->getMessage());
        }
    } else {
        setErrorMessage('Güvenlik hatası! Lütfen tekrar deneyin.');
    }
}

// Şifre Değiştirme
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])) {
    if (verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $current_password = $_POST['current_password'];
        $new_password = $_POST['new_password'];
        $confirm_password = $_POST['confirm_password'];
        
        // Mevcut şifreyi kontrol et
        $stmt = $pdo->prepare("SELECT password FROM admin_users WHERE id = ?");
        $stmt->execute([$admin_id]);
        $user = $stmt->fetch();
        
        if (!password_verify($current_password, $user['password'])) {
            setErrorMessage('Mevcut şifre hatalı!');
        } elseif ($new_password !== $confirm_password) {
            setErrorMessage('Yeni şifreler eşleşmiyor!');
        } elseif (strlen($new_password) < 6) {
            setErrorMessage('Şifre en az 6 karakter olmalıdır!');
        } else {
            try {
                $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("UPDATE admin_users SET password = ? WHERE id = ?");
                $stmt->execute([$hashed_password, $admin_id]);
                
                setSuccessMessage('Şifre başarıyla değiştirildi!');
                header('Location: profile.php');
                exit;
            } catch (PDOException $e) {
                setErrorMessage('Şifre değiştirilirken hata oluştu: ' . $e->getMessage());
            }
        }
    } else {
        setErrorMessage('Güvenlik hatası! Lütfen tekrar deneyin.');
    }
}

// Kullanıcı bilgilerini çek
$stmt = $pdo->prepare("SELECT * FROM admin_users WHERE id = ?");
$stmt->execute([$admin_id]);
$admin = $stmt->fetch();

$page_title = 'Profilim';
include 'includes/header.php';
?>

<div class="max-w-4xl mx-auto space-y-6">
    <!-- Profil Bilgileri -->
    <div class="bg-white rounded-xl shadow-md p-8">
        <div class="flex items-center gap-4 mb-6 pb-6 border-b border-gray-200">
            <div class="w-20 h-20 bg-gradient-to-br from-amber-400 to-orange-500 rounded-full flex items-center justify-center text-white text-3xl font-bold">
                <?php echo strtoupper(substr($admin['username'], 0, 2)); ?>
            </div>
            <div>
                <h2 class="text-2xl font-bold text-gray-800"><?php echo h($admin['username']); ?></h2>
                <p class="text-gray-600"><?php echo h($admin['email']); ?></p>
                <p class="text-sm text-gray-500 mt-1">
                    Son Giriş: <?php echo $admin['last_login'] ? formatDate($admin['last_login']) : 'Henüz yok'; ?>
                </p>
            </div>
        </div>

        <form method="POST" action="profile.php" class="space-y-6">
            <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
            <input type="hidden" name="update_profile" value="1">
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Kullanıcı Adı</label>
                <input type="text" name="username" required 
                       value="<?php echo h($admin['username']); ?>"
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-transparent">
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">E-posta</label>
                <input type="email" name="email" required 
                       value="<?php echo h($admin['email']); ?>"
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-transparent">
            </div>

            <button type="submit" 
                    class="bg-amber-600 hover:bg-amber-700 text-white font-bold py-3 px-8 rounded-lg transition">
                Profili Güncelle
            </button>
        </form>
    </div>

    <!-- Şifre Değiştirme -->
    <div class="bg-white rounded-xl shadow-md p-8">
        <h2 class="text-2xl font-bold text-gray-800 mb-6 flex items-center">
            <svg class="w-6 h-6 mr-2 text-amber-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path>
            </svg>
            Şifre Değiştir
        </h2>
        
        <form method="POST" action="profile.php" class="space-y-6">
            <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
            <input type="hidden" name="change_password" value="1">
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Mevcut Şifre</label>
                <input type="password" name="current_password" required 
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-transparent">
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Yeni Şifre (min 6 karakter)</label>
                <input type="password" name="new_password" required minlength="6"
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-transparent">
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Yeni Şifre Tekrar</label>
                <input type="password" name="confirm_password" required minlength="6"
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-transparent">
            </div>

            <button type="submit" 
                    class="bg-green-600 hover:bg-green-700 text-white font-bold py-3 px-8 rounded-lg transition">
                Şifreyi Değiştir
            </button>
        </form>
    </div>

    <!-- Hesap İstatistikleri -->
    <div class="bg-white rounded-xl shadow-md p-8">
        <h2 class="text-2xl font-bold text-gray-800 mb-6">Hesap Bilgileri</h2>
        
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
            <div class="text-center p-4 bg-blue-50 rounded-lg">
                <div class="text-3xl font-bold text-blue-600 mb-2">
                    <?php echo $pdo->query("SELECT COUNT(*) FROM categories")->fetchColumn(); ?>
                </div>
                <div class="text-sm text-gray-600">Toplam Kategori</div>
            </div>
            
            <div class="text-center p-4 bg-green-50 rounded-lg">
                <div class="text-3xl font-bold text-green-600 mb-2">
                    <?php echo $pdo->query("SELECT COUNT(*) FROM products")->fetchColumn(); ?>
                </div>
                <div class="text-sm text-gray-600">Toplam Ürün</div>
            </div>
            
            <div class="text-center p-4 bg-amber-50 rounded-lg">
                <div class="text-3xl font-bold text-amber-600 mb-2">
                    <?php echo date('d.m.Y', strtotime($admin['created_at'])); ?>
                </div>
                <div class="text-sm text-gray-600">Hesap Oluşturma</div>
            </div>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>