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

requireLogin();

$action = $_GET['action'] ?? 'list';
$user_id = $_GET['id'] ?? 0;

// Admin Ekleme
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'add') {
    if (verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $username = trim($_POST['username']);
        $email = trim($_POST['email']);
        $password = $_POST['password'];
        $confirm_password = $_POST['confirm_password'];
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        if ($password !== $confirm_password) {
            setErrorMessage('Şifreler eşleşmiyor!');
        } elseif (strlen($password) < 6) {
            setErrorMessage('Şifre en az 6 karakter olmalıdır!');
        } else {
            try {
                // Kullanıcı adı kontrolü
                $stmt = $pdo->prepare("SELECT COUNT(*) FROM admin_users WHERE username = ?");
                $stmt->execute([$username]);
                if ($stmt->fetchColumn() > 0) {
                    setErrorMessage('Bu kullanıcı adı zaten kullanılıyor!');
                } else {
                    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                    $stmt = $pdo->prepare("INSERT INTO admin_users (username, password, email, is_active) VALUES (?, ?, ?, ?)");
                    $stmt->execute([$username, $hashed_password, $email, $is_active]);
                    
                    setSuccessMessage('Admin kullanıcı başarıyla eklendi!');
                    header('Location: users.php');
                    exit;
                }
            } catch (PDOException $e) {
                setErrorMessage('Kullanıcı eklenirken hata oluştu: ' . $e->getMessage());
            }
        }
    } else {
        setErrorMessage('Güvenlik hatası! Lütfen tekrar deneyin.');
    }
}

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

// Şifre Sıfırlama
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'reset_password' && $user_id) {
    if (verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $new_password = $_POST['new_password'];
        $confirm_password = $_POST['confirm_password'];
        
        if ($new_password !== $confirm_password) {
            setErrorMessage('Ş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, $user_id]);
                
                setSuccessMessage('Şifre başarıyla sıfırlandı!');
                header('Location: users.php');
                exit;
            } catch (PDOException $e) {
                setErrorMessage('Şifre sıfırlanırken hata oluştu: ' . $e->getMessage());
            }
        }
    } else {
        setErrorMessage('Güvenlik hatası! Lütfen tekrar deneyin.');
    }
}

// Admin Silme
if ($action === 'delete' && $user_id) {
    // Kendi hesabını silemesin
    if ($user_id == $_SESSION['admin_id']) {
        setErrorMessage('Kendi hesabınızı silemezsiniz!');
        header('Location: users.php');
        exit;
    }
    
    try {
        $stmt = $pdo->prepare("DELETE FROM admin_users WHERE id = ?");
        $stmt->execute([$user_id]);
        
        setSuccessMessage('Kullanıcı başarıyla silindi!');
        header('Location: users.php');
        exit;
    } catch (PDOException $e) {
        setErrorMessage('Kullanıcı silinirken hata oluştu: ' . $e->getMessage());
    }
}

// Durum Değiştirme
if ($action === 'toggle' && $user_id) {
    // Kendi hesabını devre dışı bırakmasın
    if ($user_id == $_SESSION['admin_id']) {
        setErrorMessage('Kendi hesabınızın durumunu değiştiremezsiniz!');
        header('Location: users.php');
        exit;
    }
    
    try {
        $stmt = $pdo->prepare("UPDATE admin_users SET is_active = NOT is_active WHERE id = ?");
        $stmt->execute([$user_id]);
        
        setSuccessMessage('Kullanıcı durumu güncellendi!');
        header('Location: users.php');
        exit;
    } catch (PDOException $e) {
        setErrorMessage('Durum güncellenirken hata oluştu: ' . $e->getMessage());
    }
}

// Kullanıcı Bilgisi Çek (Düzenleme için)
$user = null;
if (($action === 'edit' || $action === 'reset_password') && $user_id) {
    $stmt = $pdo->prepare("SELECT * FROM admin_users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch();
    
    if (!$user) {
        setErrorMessage('Kullanıcı bulunamadı!');
        header('Location: users.php');
        exit;
    }
}

// Kullanıcı Listesi
$stmt = $pdo->query("SELECT * FROM admin_users ORDER BY created_at DESC");
$users = $stmt->fetchAll();

$page_title = $action === 'add' ? 'Yeni Admin Ekle' : ($action === 'edit' ? 'Admin Düzenle' : ($action === 'reset_password' ? 'Şifre Sıfırla' : 'Admin Kullanıcılar'));
include 'includes/header.php';
?>

<?php if ($action === 'list'): ?>
<!-- Kullanıcı Listesi -->
<div class="space-y-6">
    <div class="flex justify-between items-center">
        <div>
            <p class="text-gray-600">Sistem yöneticilerini yönetin</p>
        </div>
        <a href="users.php?action=add" class="bg-green-600 hover:bg-green-700 text-white px-6 py-2 rounded-lg transition inline-flex items-center">
            <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="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
            </svg>
            Yeni Admin Ekle
        </a>
    </div>

    <div class="bg-white rounded-xl shadow-md overflow-hidden">
        <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
                <tr>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Kullanıcı</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">E-posta</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Son Giriş</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Durum</th>
                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">İşlemler</th>
                </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
                <?php foreach ($users as $u): ?>
                    <tr class="hover:bg-gray-50">
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="flex items-center">
                                <div class="w-10 h-10 bg-gradient-to-br from-amber-400 to-orange-500 rounded-full flex items-center justify-center text-white font-bold mr-3">
                                    <?php echo strtoupper(substr($u['username'], 0, 2)); ?>
                                </div>
                                <div>
                                    <div class="text-sm font-medium text-gray-900">
                                        <?php echo h($u['username']); ?>
                                        <?php if ($u['id'] == $_SESSION['admin_id']): ?>
                                            <span class="ml-2 px-2 py-1 text-xs font-semibold rounded-full bg-blue-100 text-blue-800">Siz</span>
                                        <?php endif; ?>
                                    </div>
                                    <div class="text-sm text-gray-500">
                                        Kayıt: <?php echo formatDate($u['created_at']); ?>
                                    </div>
                                </div>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                            <?php echo h($u['email']); ?>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            <?php echo $u['last_login'] ? formatDate($u['last_login']) : 'Henüz yok'; ?>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <?php if ($u['id'] != $_SESSION['admin_id']): ?>
                                <a href="users.php?action=toggle&id=<?php echo $u['id']; ?>" class="inline-flex items-center">
                                    <?php if ($u['is_active']): ?>
                                        <span class="px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800">Aktif</span>
                                    <?php else: ?>
                                        <span class="px-2 py-1 text-xs font-semibold rounded-full bg-red-100 text-red-800">Pasif</span>
                                    <?php endif; ?>
                                </a>
                            <?php else: ?>
                                <span class="px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800">Aktif</span>
                            <?php endif; ?>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium space-x-2">
                            <a href="users.php?action=edit&id=<?php echo $u['id']; ?>" 
                               class="text-amber-600 hover:text-amber-900">Düzenle</a>
                            <a href="users.php?action=reset_password&id=<?php echo $u['id']; ?>" 
                               class="text-blue-600 hover:text-blue-900">Şifre</a>
                            <?php if ($u['id'] != $_SESSION['admin_id']): ?>
                                <a href="users.php?action=delete&id=<?php echo $u['id']; ?>" 
                                   onclick="return confirmDelete('Bu kullanıcıyı silmek istediğinizden emin misiniz?')"
                                   class="text-red-600 hover:text-red-900">Sil</a>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<?php elseif ($action === 'add'): ?>
<!-- Yeni Admin Ekleme Formu -->
<div class="max-w-2xl mx-auto">
    <div class="bg-white rounded-xl shadow-md p-8">
        <form method="POST" action="users.php?action=add">
            <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
            
            <div class="space-y-6">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Kullanıcı Adı *</label>
                    <input type="text" name="username" 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">E-posta *</label>
                    <input type="email" name="email" 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">Şifre * (min 6 karakter)</label>
                    <input type="password" name="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">Ş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>

                <div class="flex items-center">
                    <input type="checkbox" name="is_active" id="is_active" checked
                           class="h-4 w-4 text-amber-600 focus:ring-amber-500 border-gray-300 rounded">
                    <label for="is_active" class="ml-2 block text-sm text-gray-900">
                        Aktif
                    </label>
                </div>

                <div class="flex gap-4">
                    <button type="submit" 
                            class="flex-1 bg-amber-600 hover:bg-amber-700 text-white font-bold py-3 px-6 rounded-lg transition">
                        Ekle
                    </button>
                    <a href="users.php" 
                       class="flex-1 bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-3 px-6 rounded-lg transition text-center">
                        İptal
                    </a>
                </div>
            </div>
        </form>
    </div>
</div>

<?php elseif ($action === 'edit'): ?>
<!-- Admin Düzenleme Formu -->
<div class="max-w-2xl mx-auto">
    <div class="bg-white rounded-xl shadow-md p-8">
        <form method="POST" action="users.php?action=edit&id=<?php echo $user_id; ?>">
            <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
            
            <div class="space-y-6">
                <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($user['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($user['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>

                <?php if ($user['id'] != $_SESSION['admin_id']): ?>
                <div class="flex items-center">
                    <input type="checkbox" name="is_active" id="is_active" 
                           <?php echo $user['is_active'] ? 'checked' : ''; ?>
                           class="h-4 w-4 text-amber-600 focus:ring-amber-500 border-gray-300 rounded">
                    <label for="is_active" class="ml-2 block text-sm text-gray-900">
                        Aktif
                    </label>
                </div>
                <?php endif; ?>

                <div class="flex gap-4">
                    <button type="submit" 
                            class="flex-1 bg-amber-600 hover:bg-amber-700 text-white font-bold py-3 px-6 rounded-lg transition">
                        Güncelle
                    </button>
                    <a href="users.php" 
                       class="flex-1 bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-3 px-6 rounded-lg transition text-center">
                        İptal
                    </a>
                </div>
            </div>
        </form>
    </div>
</div>

<?php elseif ($action === 'reset_password'): ?>
<!-- Şifre Sıfırlama Formu -->
<div class="max-w-2xl mx-auto">
    <div class="bg-white rounded-xl shadow-md p-8">
        <div class="mb-6">
            <h3 class="text-lg font-semibold text-gray-800">
                Kullanıcı: <?php echo h($user['username']); ?>
            </h3>
            <p class="text-sm text-gray-600">Yeni şifre belirleyin</p>
        </div>
        
        <form method="POST" action="users.php?action=reset_password&id=<?php echo $user_id; ?>">
            <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
            
            <div class="space-y-6">
                <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>

                <div class="flex gap-4">
                    <button type="submit" 
                            class="flex-1 bg-green-600 hover:bg-green-700 text-white font-bold py-3 px-6 rounded-lg transition">
                        Şifreyi Sıfırla
                    </button>
                    <a href="users.php" 
                       class="flex-1 bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-3 px-6 rounded-lg transition text-center">
                        İptal
                    </a>
                </div>
            </div>
        </form>
    </div>
</div>
<?php endif; ?>

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