<?php
/**
 * SMM Paket Satış Scripti - Kullanıcı Yönetimi
 * @version 1.0.0
 */

require_once __DIR__ . '/../config.php';

if (!isLoggedIn() || !isAdmin()) {
    redirect(SITE_URL . '/admin/');
    exit;
}

// CSRF Token
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrfToken = $_SESSION['csrf_token'];

// POST İşlemleri
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if (!hash_equals($csrfToken, $_POST['csrf_token'] ?? '')) {
        setFlash('error', 'Güvenlik hatası.');
        redirect(SITE_URL . '/admin/kullanicilar.php');
        exit;
    }
    
    $action = $_POST['action'];
    
    try {
        switch ($action) {
            case 'add_user':
                $username = trim($_POST['username'] ?? '');
                $email = trim($_POST['email'] ?? '');
                $password = $_POST['password'] ?? '';
                $fullName = trim($_POST['full_name'] ?? '');
                $phone = trim($_POST['phone'] ?? '');
                $role = $_POST['role'] ?? 'user';
                $status = $_POST['status'] ?? 'active';
                
                // Validasyon
                if (empty($username) || empty($email) || empty($password)) {
                    throw new Exception('Kullanıcı adı, e-posta ve şifre zorunludur.');
                }
                
                if (strlen($username) < 3) {
                    throw new Exception('Kullanıcı adı en az 3 karakter olmalıdır.');
                }
                
                if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    throw new Exception('Geçerli bir e-posta adresi girin.');
                }
                
                if (strlen($password) < 6) {
                    throw new Exception('Şifre en az 6 karakter olmalıdır.');
                }
                
                // Kullanıcı adı ve e-posta kontrolü
                $checkStmt = $db->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
                $checkStmt->execute([$username, $email]);
                if ($checkStmt->fetch()) {
                    throw new Exception('Bu kullanıcı adı veya e-posta zaten kullanılıyor.');
                }
                
                $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
                
                $stmt = $db->prepare("
                    INSERT INTO users (username, email, password, full_name, phone, role, status, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
                ");
                $stmt->execute([$username, $email, $hashedPassword, $fullName, $phone, $role, $status]);
                
                setFlash('success', 'Kullanıcı başarıyla eklendi.');
                break;
                
            case 'update_user':
                $userId = (int)($_POST['user_id'] ?? 0);
                $username = trim($_POST['username'] ?? '');
                $email = trim($_POST['email'] ?? '');
                $fullName = trim($_POST['full_name'] ?? '');
                $phone = trim($_POST['phone'] ?? '');
                $role = $_POST['role'] ?? 'user';
                $status = $_POST['status'] ?? 'active';
                $newPassword = $_POST['new_password'] ?? '';
                
                if ($userId <= 0) {
                    throw new Exception('Geçersiz kullanıcı.');
                }
                
                // Validasyon
                if (empty($username) || empty($email)) {
                    throw new Exception('Kullanıcı adı ve e-posta zorunludur.');
                }
                
                if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    throw new Exception('Geçerli bir e-posta adresi girin.');
                }
                
                // Kullanıcı adı ve e-posta kontrolü (kendi hariç)
                $checkStmt = $db->prepare("SELECT id FROM users WHERE (username = ? OR email = ?) AND id != ?");
                $checkStmt->execute([$username, $email, $userId]);
                if ($checkStmt->fetch()) {
                    throw new Exception('Bu kullanıcı adı veya e-posta başka bir kullanıcı tarafından kullanılıyor.');
                }
                
                // Kendini admin'den düşürmeyi engelle
                if ($userId == $_SESSION['user_id'] && $role !== 'admin') {
                    throw new Exception('Kendi admin yetkinizi kaldıramazsınız.');
                }
                
                // Kendini banlamayı engelle
                if ($userId == $_SESSION['user_id'] && $status !== 'active') {
                    throw new Exception('Kendi hesabınızı pasif yapamazsınız.');
                }
                
                if (!empty($newPassword)) {
                    if (strlen($newPassword) < 6) {
                        throw new Exception('Şifre en az 6 karakter olmalıdır.');
                    }
                    $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
                    $stmt = $db->prepare("
                        UPDATE users SET username = ?, email = ?, password = ?, full_name = ?, phone = ?, role = ?, status = ?, updated_at = NOW()
                        WHERE id = ?
                    ");
                    $stmt->execute([$username, $email, $hashedPassword, $fullName, $phone, $role, $status, $userId]);
                } else {
                    $stmt = $db->prepare("
                        UPDATE users SET username = ?, email = ?, full_name = ?, phone = ?, role = ?, status = ?, updated_at = NOW()
                        WHERE id = ?
                    ");
                    $stmt->execute([$username, $email, $fullName, $phone, $role, $status, $userId]);
                }
                
                setFlash('success', 'Kullanıcı güncellendi.');
                break;
                
            case 'delete_user':
                $userId = (int)($_POST['user_id'] ?? 0);
                
                if ($userId <= 0) {
                    throw new Exception('Geçersiz kullanıcı.');
                }
                
                // Kendini silmeyi engelle
                if ($userId == $_SESSION['user_id']) {
                    throw new Exception('Kendi hesabınızı silemezsiniz.');
                }
                
                // Siparişleri kontrol et
                $orderCount = $db->prepare("SELECT COUNT(*) FROM orders WHERE user_id = ?");
                $orderCount->execute([$userId]);
                $orders = $orderCount->fetchColumn();
                
                if ($orders > 0) {
                    // Siparişleri NULL yap, kullanıcıyı sil
                    $db->prepare("UPDATE orders SET user_id = NULL WHERE user_id = ?")->execute([$userId]);
                }
                
                $db->prepare("DELETE FROM users WHERE id = ?")->execute([$userId]);
                
                setFlash('success', 'Kullanıcı silindi.' . ($orders > 0 ? " ($orders sipariş anonim yapıldı)" : ''));
                break;
                
            case 'change_status':
                $userId = (int)($_POST['user_id'] ?? 0);
                $status = $_POST['status'] ?? 'active';
                
                if ($userId == $_SESSION['user_id']) {
                    throw new Exception('Kendi durumunuzu değiştiremezsiniz.');
                }
                
                if (!in_array($status, ['active', 'inactive', 'banned'])) {
                    throw new Exception('Geçersiz durum.');
                }
                
                $db->prepare("UPDATE users SET status = ?, updated_at = NOW() WHERE id = ?")->execute([$status, $userId]);
                
                $statusLabels = ['active' => 'aktif', 'inactive' => 'pasif', 'banned' => 'yasaklı'];
                setFlash('success', 'Kullanıcı durumu ' . $statusLabels[$status] . ' yapıldı.');
                break;
                
            case 'change_role':
                $userId = (int)($_POST['user_id'] ?? 0);
                $role = $_POST['role'] ?? 'user';
                
                if ($userId == $_SESSION['user_id']) {
                    throw new Exception('Kendi rolünüzü değiştiremezsiniz.');
                }
                
                if (!in_array($role, ['user', 'admin'])) {
                    throw new Exception('Geçersiz rol.');
                }
                
                $db->prepare("UPDATE users SET role = ?, updated_at = NOW() WHERE id = ?")->execute([$role, $userId]);
                
                setFlash('success', 'Kullanıcı rolü ' . ($role === 'admin' ? 'yönetici' : 'kullanıcı') . ' yapıldı.');
                break;
                
            case 'reset_password':
                $userId = (int)($_POST['user_id'] ?? 0);
                
                if ($userId <= 0) {
                    throw new Exception('Geçersiz kullanıcı.');
                }
                
                // Rastgele şifre oluştur
                $newPassword = bin2hex(random_bytes(4)); // 8 karakter
                $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
                
                $db->prepare("UPDATE users SET password = ?, updated_at = NOW() WHERE id = ?")->execute([$hashedPassword, $userId]);
                
                // Kullanıcı bilgilerini al
                $userStmt = $db->prepare("SELECT email, full_name FROM users WHERE id = ?");
                $userStmt->execute([$userId]);
                $userData = $userStmt->fetch(PDO::FETCH_ASSOC);
                
                setFlash('success', 'Yeni şifre: <strong>' . $newPassword . '</strong> (Bu şifreyi kullanıcıya iletin: ' . $userData['email'] . ')');
                break;
        }
    } catch (Exception $e) {
        setFlash('error', $e->getMessage());
    }
    
    redirect(SITE_URL . '/admin/kullanicilar.php' . (!empty($_GET['page']) ? '?page=' . (int)$_GET['page'] : ''));
    exit;
}

// Filtreler
$roleFilter = $_GET['role'] ?? '';
$statusFilter = $_GET['status'] ?? '';
$search = trim($_GET['q'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));
$limit = 20;
$offset = ($page - 1) * $limit;

// WHERE koşulları
$where = "1=1";
$params = [];

if ($roleFilter && in_array($roleFilter, ['user', 'admin'])) {
    $where .= " AND role = ?";
    $params[] = $roleFilter;
}

if ($statusFilter && in_array($statusFilter, ['active', 'inactive', 'banned'])) {
    $where .= " AND status = ?";
    $params[] = $statusFilter;
}

if ($search) {
    $where .= " AND (username LIKE ? OR email LIKE ? OR full_name LIKE ? OR phone LIKE ?)";
    $searchTerm = "%$search%";
    $params = array_merge($params, [$searchTerm, $searchTerm, $searchTerm, $searchTerm]);
}

// Toplam kayıt
$totalStmt = $db->prepare("SELECT COUNT(*) FROM users WHERE $where");
$totalStmt->execute($params);
$totalUsers = $totalStmt->fetchColumn();
$totalPages = ceil($totalUsers / $limit);

// Kullanıcıları çek
$sql = "
    SELECT u.*, 
           (SELECT COUNT(*) FROM orders WHERE user_id = u.id) as order_count,
           (SELECT SUM(amount) FROM orders WHERE user_id = u.id AND status = 'completed') as total_spent
    FROM users u 
    WHERE $where 
    ORDER BY u.created_at DESC 
    LIMIT $limit OFFSET $offset
";
$stmt = $db->prepare($sql);
$stmt->execute($params);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

// İstatistikler
$stats = $db->query("
    SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN role = 'admin' THEN 1 ELSE 0 END) as admins,
        SUM(CASE WHEN role = 'user' THEN 1 ELSE 0 END) as users,
        SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active,
        SUM(CASE WHEN status = 'inactive' THEN 1 ELSE 0 END) as inactive,
        SUM(CASE WHEN status = 'banned' THEN 1 ELSE 0 END) as banned,
        SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) as today
    FROM users
")->fetch(PDO::FETCH_ASSOC);

$adminPageTitle = 'Kullanıcılar';
require_once __DIR__ . '/header.php';
?>

<style>
/* Stats */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
    gap: 15px;
    margin-bottom: 25px;
}

.stat-card {
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 12px;
    padding: 20px;
    text-align: center;
    transition: all 0.3s;
}

.stat-card:hover {
    transform: translateY(-3px);
    border-color: rgba(var(--primary-rgb), 0.3);
}

.stat-value {
    font-size: 28px;
    font-weight: 800;
    margin-bottom: 5px;
}

.stat-label {
    font-size: 12px;
    color: var(--text-secondary);
}

/* Filters */
.filters-card {
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 20px;
}

.filters-row {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
    align-items: center;
}

.search-box {
    flex: 1;
    min-width: 200px;
    position: relative;
}

.search-box input {
    width: 100%;
    padding: 12px 15px 12px 45px;
    background: var(--bg-dark);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    color: var(--text-primary);
    font-size: 14px;
}

.search-box input::placeholder {
    color: var(--text-secondary);
}

.search-box i {
    position: absolute;
    left: 15px;
    top: 50%;
    transform: translateY(-50%);
    color: var(--text-secondary);
}

.filter-select {
    min-width: 150px;
    padding: 12px 15px;
    background: var(--bg-dark);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    color: var(--text-primary);
    font-size: 14px;
}

.filter-tabs {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    margin-top: 15px;
    padding-top: 15px;
    border-top: 1px solid var(--border-color);
}

.filter-tab {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 8px 14px;
    background: var(--bg-hover);
    border-radius: 8px;
    font-size: 12px;
    color: var(--text-secondary);
    text-decoration: none;
    transition: all 0.2s;
}

.filter-tab:hover {
    color: var(--text-primary);
}

.filter-tab.active {
    background: rgba(var(--primary-rgb), 0.15);
    color: var(--primary);
}

.filter-tab .count {
    background: rgba(255,255,255,0.1);
    padding: 2px 8px;
    border-radius: 10px;
    font-size: 11px;
}

/* Users Table */
.users-card {
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 12px;
    overflow: hidden;
}

.users-table {
    width: 100%;
    border-collapse: collapse;
}

.users-table th {
    background: var(--bg-hover);
    padding: 14px 16px;
    text-align: left;
    font-size: 11px;
    font-weight: 600;
    color: var(--text-secondary);
    text-transform: uppercase;
    letter-spacing: 0.5px;
    border-bottom: 1px solid var(--border-color);
}

.users-table td {
    padding: 16px;
    border-bottom: 1px solid var(--border-color);
    font-size: 14px;
    vertical-align: middle;
}

.users-table tr:last-child td {
    border-bottom: none;
}

.users-table tr:hover td {
    background: var(--bg-hover);
}

/* User Info */
.user-info {
    display: flex;
    align-items: center;
    gap: 12px;
}

.user-avatar {
    width: 42px;
    height: 42px;
    background: var(--gradient);
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 700;
    color: #fff;
    font-size: 16px;
    flex-shrink: 0;
}

.user-avatar.admin {
    background: linear-gradient(135deg, #f59e0b, #ef4444);
}

.user-details h4 {
    font-size: 14px;
    font-weight: 600;
    margin: 0 0 3px;
    display: flex;
    align-items: center;
    gap: 6px;
}

.user-details h4 .badge {
    font-size: 9px;
    padding: 2px 6px;
    border-radius: 4px;
}

.user-details span {
    font-size: 12px;
    color: var(--text-secondary);
}

/* Contact */
.user-contact {
    font-size: 13px;
}

.user-contact a {
    color: var(--primary);
}

.user-contact .phone {
    display: block;
    font-size: 12px;
    color: var(--text-secondary);
    margin-top: 3px;
}

/* Stats */
.user-stats {
    text-align: center;
}

.user-stats .value {
    font-size: 16px;
    font-weight: 700;
}

.user-stats .label {
    font-size: 10px;
    color: var(--text-secondary);
    display: block;
}

.user-stats .spent {
    color: #10b981;
    font-size: 12px;
    margin-top: 2px;
}

/* Badges */
.role-badge {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 5px 10px;
    border-radius: 6px;
    font-size: 11px;
    font-weight: 600;
}

.role-badge.admin {
    background: rgba(245, 158, 11, 0.15);
    color: #f59e0b;
}

.role-badge.user {
    background: rgba(59, 130, 246, 0.15);
    color: #3b82f6;
}

.status-badge {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 5px 10px;
    border-radius: 6px;
    font-size: 11px;
    font-weight: 600;
}

.status-badge.active {
    background: rgba(16, 185, 129, 0.15);
    color: #10b981;
}

.status-badge.inactive {
    background: rgba(107, 114, 128, 0.15);
    color: #6b7280;
}

.status-badge.banned {
    background: rgba(239, 68, 68, 0.15);
    color: #ef4444;
}

/* Date */
.user-date {
    font-size: 12px;
    color: var(--text-secondary);
}

.user-date .time {
    display: block;
    font-size: 11px;
    opacity: 0.7;
}

/* Actions */
.user-actions {
    display: flex;
    gap: 6px;
}

.action-btn {
    width: 32px;
    height: 32px;
    border: none;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    font-size: 12px;
    transition: all 0.2s;
}

.action-btn:hover {
    transform: scale(1.1);
}

.action-btn.view {
    background: rgba(59, 130, 246, 0.15);
    color: #3b82f6;
}

.action-btn.edit {
    background: rgba(245, 158, 11, 0.15);
    color: #f59e0b;
}

.action-btn.password {
    background: rgba(139, 92, 246, 0.15);
    color: #8b5cf6;
}

.action-btn.delete {
    background: rgba(239, 68, 68, 0.15);
    color: #ef4444;
}

.action-btn.success {
    background: rgba(16, 185, 129, 0.15);
    color: #10b981;
}

.action-btn.warning {
    background: rgba(245, 158, 11, 0.15);
    color: #f59e0b;
}

.action-btn.danger {
    background: rgba(239, 68, 68, 0.15);
    color: #ef4444;
}

/* Dropdown */
.action-dropdown {
    position: relative;
}

.action-dropdown-menu {
    position: absolute;
    right: 0;
    top: 100%;
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    padding: 8px;
    min-width: 180px;
    box-shadow: 0 10px 40px rgba(0,0,0,0.3);
    z-index: 100;
    display: none;
}

.action-dropdown-menu.show {
    display: block;
}

.action-dropdown-item {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 12px;
    border-radius: 6px;
    font-size: 13px;
    color: var(--text-secondary);
    cursor: pointer;
    transition: all 0.2s;
    border: none;
    background: none;
    width: 100%;
    text-align: left;
}

.action-dropdown-item:hover {
    background: var(--bg-hover);
    color: var(--text-primary);
}

.action-dropdown-item.danger {
    color: #ef4444;
}

.action-dropdown-item.danger:hover {
    background: rgba(239, 68, 68, 0.1);
}

.action-dropdown-divider {
    height: 1px;
    background: var(--border-color);
    margin: 8px 0;
}

/* Pagination */
.pagination-wrapper {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 20px;
    border-top: 1px solid var(--border-color);
    flex-wrap: wrap;
    gap: 15px;
}

.pagination-info {
    font-size: 13px;
    color: var(--text-secondary);
}

.pagination-links {
    display: flex;
    gap: 6px;
}

.pagination-links a {
    display: flex;
    align-items: center;
    justify-content: center;
    min-width: 36px;
    height: 36px;
    padding: 0 12px;
    background: var(--bg-hover);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    color: var(--text-secondary);
    font-size: 13px;
    text-decoration: none;
    transition: all 0.2s;
}

.pagination-links a:hover {
    border-color: var(--primary);
    color: var(--primary);
}

.pagination-links a.active {
    background: var(--primary);
    border-color: var(--primary);
    color: #fff;
}

/* Empty */
.empty-state {
    text-align: center;
    padding: 60px 20px;
}

.empty-state i {
    font-size: 50px;
    color: var(--text-secondary);
    opacity: 0.3;
    margin-bottom: 15px;
}

.empty-state h4 {
    font-size: 18px;
    margin-bottom: 10px;
}

.empty-state p {
    color: var(--text-secondary);
    font-size: 14px;
}

/* Modal */
.modal-content {
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 16px;
    color: var(--text-primary);
}

.modal-header {
    border-bottom: 1px solid var(--border-color);
    padding: 20px 24px;
}

.modal-title {
    font-size: 18px;
    font-weight: 700;
    display: flex;
    align-items: center;
    gap: 10px;
}

.modal-title i {
    color: var(--primary);
}

.modal-body {
    padding: 24px;
}

.modal-footer {
    border-top: 1px solid var(--border-color);
    padding: 16px 24px;
    gap: 10px;
}

.form-group {
    margin-bottom: 20px;
}

.form-group:last-child {
    margin-bottom: 0;
}

.form-row {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
}

.form-hint {
    font-size: 12px;
    color: var(--text-secondary);
    margin-top: 6px;
}

.password-toggle {
    position: relative;
}

.password-toggle input {
    padding-right: 45px;
}

.password-toggle button {
    position: absolute;
    right: 12px;
    top: 50%;
    transform: translateY(-50%);
    background: none;
    border: none;
    color: var(--text-secondary);
    cursor: pointer;
    padding: 5px;
}

/* User Detail Modal */
.user-detail-header {
    display: flex;
    align-items: center;
    gap: 20px;
    padding: 20px;
    background: var(--bg-hover);
    border-radius: 12px;
    margin-bottom: 24px;
}

.user-detail-avatar {
    width: 80px;
    height: 80px;
    background: var(--gradient);
    border-radius: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32px;
    font-weight: 700;
    color: #fff;
}

.user-detail-info h3 {
    font-size: 20px;
    font-weight: 700;
    margin: 0 0 5px;
}

.user-detail-info p {
    color: var(--text-secondary);
    margin: 0 0 10px;
    font-size: 14px;
}

.user-detail-badges {
    display: flex;
    gap: 8px;
}

.detail-section {
    margin-bottom: 24px;
}

.detail-section:last-child {
    margin-bottom: 0;
}

.detail-section-title {
    font-size: 12px;
    font-weight: 600;
    color: var(--primary);
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid var(--border-color);
}

.detail-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
}

.detail-item {
    background: var(--bg-hover);
    padding: 12px 15px;
    border-radius: 8px;
}

.detail-item.full {
    grid-column: span 2;
}

.detail-item label {
    display: block;
    font-size: 10px;
    color: var(--text-secondary);
    text-transform: uppercase;
    margin-bottom: 4px;
}

.detail-item p {
    margin: 0;
    font-size: 14px;
    font-weight: 500;
}

.detail-item p a {
    color: var(--primary);
}

/* Orders List */
.mini-orders {
    max-height: 200px;
    overflow-y: auto;
}

.mini-order {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 12px;
    background: var(--bg-hover);
    border-radius: 8px;
    margin-bottom: 8px;
    font-size: 13px;
}

.mini-order:last-child {
    margin-bottom: 0;
}

.mini-order-no {
    font-family: monospace;
    color: var(--primary);
    font-weight: 600;
}

.mini-order-amount {
    color: #10b981;
    font-weight: 600;
}

/* Responsive */
@media (max-width: 1200px) {
    .users-table th:nth-child(5),
    .users-table td:nth-child(5) {
        display: none;
    }
}

@media (max-width: 992px) {
    .users-table th:nth-child(4),
    .users-table td:nth-child(4) {
        display: none;
    }
    
    .form-row {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 768px) {
    .stats-grid {
        grid-template-columns: repeat(2, 1fr);
    }
    
    .users-table th:nth-child(3),
    .users-table td:nth-child(3),
    .users-table th:nth-child(6),
    .users-table td:nth-child(6) {
        display: none;
    }
    
    .detail-grid {
        grid-template-columns: 1fr;
    }
    
    .detail-item.full {
        grid-column: span 1;
    }
    
    .user-detail-header {
        flex-direction: column;
        text-align: center;
    }
}

@media (max-width: 576px) {
    .filters-row {
        flex-direction: column;
    }
    
    .search-box, .filter-select {
        width: 100%;
    }
    
    .filter-tabs {
        overflow-x: auto;
        flex-wrap: nowrap;
        padding-bottom: 10px;
    }
    
    .filter-tab {
        white-space: nowrap;
        flex-shrink: 0;
    }
}
</style>

<!-- Stats -->
<div class="stats-grid">
    <div class="stat-card">
        <div class="stat-value" style="color: var(--primary)"><?php echo $stats['total']; ?></div>
        <div class="stat-label">Toplam Kullanıcı</div>
    </div>
    <div class="stat-card">
        <div class="stat-value" style="color: #f59e0b"><?php echo $stats['admins']; ?></div>
        <div class="stat-label">Yönetici</div>
    </div>
    <div class="stat-card">
        <div class="stat-value" style="color: #3b82f6"><?php echo $stats['users']; ?></div>
        <div class="stat-label">Kullanıcı</div>
    </div>
    <div class="stat-card">
        <div class="stat-value" style="color: #10b981"><?php echo $stats['active']; ?></div>
        <div class="stat-label">Aktif</div>
    </div>
    <div class="stat-card">
        <div class="stat-value" style="color: #ef4444"><?php echo $stats['banned']; ?></div>
        <div class="stat-label">Yasaklı</div>
    </div>
    <div class="stat-card">
        <div class="stat-value" style="color: #8b5cf6"><?php echo $stats['today']; ?></div>
        <div class="stat-label">Bugün Kayıt</div>
    </div>
</div>

<!-- Filters -->
<div class="filters-card">
    <form class="filters-row" method="GET">
        <div class="search-box">
            <i class="fas fa-search"></i>
            <input type="text" name="q" placeholder="Kullanıcı adı, e-posta, isim veya telefon..." value="<?php echo clean($search); ?>">
        </div>
        <select name="role" class="filter-select" onchange="this.form.submit()">
            <option value="">Tüm Roller</option>
            <option value="admin" <?php echo $roleFilter === 'admin' ? 'selected' : ''; ?>>Yönetici</option>
            <option value="user" <?php echo $roleFilter === 'user' ? 'selected' : ''; ?>>Kullanıcı</option>
        </select>
        <select name="status" class="filter-select" onchange="this.form.submit()">
            <option value="">Tüm Durumlar</option>
            <option value="active" <?php echo $statusFilter === 'active' ? 'selected' : ''; ?>>Aktif</option>
            <option value="inactive" <?php echo $statusFilter === 'inactive' ? 'selected' : ''; ?>>Pasif</option>
            <option value="banned" <?php echo $statusFilter === 'banned' ? 'selected' : ''; ?>>Yasaklı</option>
        </select>
        <button type="submit" class="btn-primary-custom">
            <i class="fas fa-search"></i> Ara
        </button>
        <?php if ($search || $roleFilter || $statusFilter): ?>
        <a href="<?php echo SITE_URL; ?>/admin/kullanicilar.php" class="btn-secondary-custom">
            <i class="fas fa-times"></i> Temizle
        </a>
        <?php endif; ?>
        <button type="button" class="btn-primary-custom" data-bs-toggle="modal" data-bs-target="#addUserModal">
            <i class="fas fa-plus"></i> Yeni Kullanıcı
        </button>
    </form>
    
    <div class="filter-tabs">
        <a href="<?php echo SITE_URL; ?>/admin/kullanicilar.php" class="filter-tab <?php echo !$roleFilter && !$statusFilter ? 'active' : ''; ?>">
            <i class="fas fa-users"></i> Tümü <span class="count"><?php echo $stats['total']; ?></span>
        </a>
        <a href="?role=admin" class="filter-tab <?php echo $roleFilter === 'admin' ? 'active' : ''; ?>">
            <i class="fas fa-user-shield"></i> Yöneticiler <span class="count"><?php echo $stats['admins']; ?></span>
        </a>
        <a href="?role=user" class="filter-tab <?php echo $roleFilter === 'user' ? 'active' : ''; ?>">
            <i class="fas fa-user"></i> Kullanıcılar <span class="count"><?php echo $stats['users']; ?></span>
        </a>
        <a href="?status=active" class="filter-tab <?php echo $statusFilter === 'active' ? 'active' : ''; ?>">
            <i class="fas fa-check-circle"></i> Aktif <span class="count"><?php echo $stats['active']; ?></span>
        </a>
        <a href="?status=inactive" class="filter-tab <?php echo $statusFilter === 'inactive' ? 'active' : ''; ?>">
            <i class="fas fa-pause-circle"></i> Pasif <span class="count"><?php echo $stats['inactive']; ?></span>
        </a>
        <a href="?status=banned" class="filter-tab <?php echo $statusFilter === 'banned' ? 'active' : ''; ?>">
            <i class="fas fa-ban"></i> Yasaklı <span class="count"><?php echo $stats['banned']; ?></span>
        </a>
    </div>
</div>

<!-- Users Table -->
<div class="users-card">
    <?php if (empty($users)): ?>
    <div class="empty-state">
        <i class="fas fa-users"></i>
        <h4>Kullanıcı Bulunamadı</h4>
        <p>Arama kriterlerinize uygun kullanıcı bulunmuyor.</p>
    </div>
    <?php else: ?>
    <div class="table-responsive">
        <table class="users-table">
            <thead>
                <tr>
                    <th>Kullanıcı</th>
                    <th>İletişim</th>
                    <th>Sipariş</th>
                    <th>Rol</th>
                    <th>Durum</th>
                    <th>Kayıt Tarihi</th>
                    <th style="width: 120px;">İşlemler</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($users as $user): ?>
                <tr>
                    <td>
                        <div class="user-info">
                            <div class="user-avatar <?php echo $user['role'] === 'admin' ? 'admin' : ''; ?>">
                                <?php echo strtoupper(substr($user['username'] ?? $user['email'], 0, 1)); ?>
                            </div>
                            <div class="user-details">
                                <h4>
                                    <?php echo clean($user['full_name'] ?: $user['username']); ?>
                                    <?php if ($user['id'] == $_SESSION['user_id']): ?>
                                    <span class="badge" style="background: var(--primary); color: #fff;">Sen</span>
                                    <?php endif; ?>
                                </h4>
                                <span>@<?php echo clean($user['username']); ?></span>
                            </div>
                        </div>
                    </td>
                    <td>
                        <div class="user-contact">
                            <a href="mailto:<?php echo clean($user['email']); ?>"><?php echo clean($user['email']); ?></a>
                            <?php if ($user['phone']): ?>
                            <span class="phone"><i class="fas fa-phone"></i> <?php echo clean($user['phone']); ?></span>
                            <?php endif; ?>
                        </div>
                    </td>
                    <td>
                        <div class="user-stats">
                            <div class="value"><?php echo $user['order_count'] ?? 0; ?></div>
                            <span class="label">Sipariş</span>
                            <?php if ($user['total_spent'] > 0): ?>
                            <div class="spent"><?php echo formatMoney($user['total_spent']); ?></div>
                            <?php endif; ?>
                        </div>
                    </td>
                    <td>
                        <span class="role-badge <?php echo $user['role']; ?>">
                            <i class="fas fa-<?php echo $user['role'] === 'admin' ? 'user-shield' : 'user'; ?>"></i>
                            <?php echo $user['role'] === 'admin' ? 'Yönetici' : 'Kullanıcı'; ?>
                        </span>
                    </td>
                    <td>
                        <span class="status-badge <?php echo $user['status']; ?>">
                            <i class="fas fa-<?php echo $user['status'] === 'active' ? 'check-circle' : ($user['status'] === 'banned' ? 'ban' : 'pause-circle'); ?>"></i>
                            <?php 
                            $statusLabels = ['active' => 'Aktif', 'inactive' => 'Pasif', 'banned' => 'Yasaklı'];
                            echo $statusLabels[$user['status']] ?? $user['status']; 
                            ?>
                        </span>
                    </td>
                    <td>
                        <div class="user-date">
                            <?php echo date('d.m.Y', strtotime($user['created_at'])); ?>
                            <span class="time"><?php echo date('H:i', strtotime($user['created_at'])); ?></span>
                        </div>
                    </td>
                    <td>
                        <div class="user-actions">
                            <button class="action-btn view" onclick="viewUser(<?php echo $user['id']; ?>)" title="Detay">
                                <i class="fas fa-eye"></i>
                            </button>
                            <button class="action-btn edit" onclick="editUser(<?php echo $user['id']; ?>)" title="Düzenle">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="action-btn password" onclick="resetPassword(<?php echo $user['id']; ?>, '<?php echo clean($user['username']); ?>')" title="Şifre Sıfırla">
                                <i class="fas fa-key"></i>
                            </button>
                            <?php if ($user['id'] != $_SESSION['user_id']): ?>
                            <button class="action-btn delete" onclick="deleteUser(<?php echo $user['id']; ?>, '<?php echo clean($user['username']); ?>')" title="Sil">
                                <i class="fas fa-trash"></i>
                            </button>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    
    <?php if ($totalPages > 1): ?>
    <div class="pagination-wrapper">
        <div class="pagination-info">
            Toplam <?php echo number_format($totalUsers); ?> kullanıcı
        </div>
        <div class="pagination-links">
            <?php if ($page > 1): ?>
            <a href="?page=<?php echo $page - 1; ?><?php echo $roleFilter ? '&role='.$roleFilter : ''; ?><?php echo $statusFilter ? '&status='.$statusFilter : ''; ?><?php echo $search ? '&q='.urlencode($search) : ''; ?>">
                <i class="fas fa-chevron-left"></i>
            </a>
            <?php endif; ?>
            
            <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
            <a href="?page=<?php echo $i; ?><?php echo $roleFilter ? '&role='.$roleFilter : ''; ?><?php echo $statusFilter ? '&status='.$statusFilter : ''; ?><?php echo $search ? '&q='.urlencode($search) : ''; ?>" class="<?php echo $i === $page ? 'active' : ''; ?>">
                <?php echo $i; ?>
            </a>
            <?php endfor; ?>
            
            <?php if ($page < $totalPages): ?>
            <a href="?page=<?php echo $page + 1; ?><?php echo $roleFilter ? '&role='.$roleFilter : ''; ?><?php echo $statusFilter ? '&status='.$statusFilter : ''; ?><?php echo $search ? '&q='.urlencode($search) : ''; ?>">
                <i class="fas fa-chevron-right"></i>
            </a>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>
    <?php endif; ?>
</div>

<!-- Add User Modal -->
<div class="modal fade" id="addUserModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                <input type="hidden" name="action" value="add_user">
                
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-user-plus"></i> Yeni Kullanıcı Ekle</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" style="filter: invert(1);"></button>
                </div>
                
                <div class="modal-body">
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Kullanıcı Adı *</label>
                            <input type="text" name="username" class="form-control" placeholder="kullaniciadi" required minlength="3">
                            <div class="form-hint">En az 3 karakter, boşluk olmadan</div>
                        </div>
                        <div class="form-group">
                            <label class="form-label">E-posta *</label>
                            <input type="email" name="email" class="form-control" placeholder="ornek@mail.com" required>
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Ad Soyad</label>
                            <input type="text" name="full_name" class="form-control" placeholder="Ad Soyad">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Telefon</label>
                            <input type="text" name="phone" class="form-control" placeholder="05XX XXX XX XX">
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Şifre *</label>
                        <div class="password-toggle">
                            <input type="password" name="password" id="addPassword" class="form-control" placeholder="••••••••" required minlength="6">
                            <button type="button" onclick="togglePassword('addPassword', this)">
                                <i class="fas fa-eye"></i>
                            </button>
                        </div>
                        <div class="form-hint">En az 6 karakter</div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Rol</label>
                            <select name="role" class="form-control">
                                <option value="user">Kullanıcı</option>
                                <option value="admin">Yönetici</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Durum</label>
                            <select name="status" class="form-control">
                                <option value="active">Aktif</option>
                                <option value="inactive">Pasif</option>
                                <option value="banned">Yasaklı</option>
                            </select>
                        </div>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn-secondary-custom" data-bs-dismiss="modal">İptal</button>
                    <button type="submit" class="btn-primary-custom">
                        <i class="fas fa-plus"></i> Kullanıcı Ekle
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit User Modal -->
<div class="modal fade" id="editUserModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                <input type="hidden" name="action" value="update_user">
                <input type="hidden" name="user_id" id="editUserId">
                
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-user-edit"></i> Kullanıcı Düzenle</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" style="filter: invert(1);"></button>
                </div>
                
                <div class="modal-body">
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Kullanıcı Adı *</label>
                            <input type="text" name="username" id="editUsername" class="form-control" required minlength="3">
                        </div>
                        <div class="form-group">
                            <label class="form-label">E-posta *</label>
                            <input type="email" name="email" id="editEmail" class="form-control" required>
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Ad Soyad</label>
                            <input type="text" name="full_name" id="editFullName" class="form-control">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Telefon</label>
                            <input type="text" name="phone" id="editPhone" class="form-control">
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Yeni Şifre</label>
                        <div class="password-toggle">
                            <input type="password" name="new_password" id="editPassword" class="form-control" placeholder="Değiştirmek istemiyorsanız boş bırakın" minlength="6">
                            <button type="button" onclick="togglePassword('editPassword', this)">
                                <i class="fas fa-eye"></i>
                            </button>
                        </div>
                        <div class="form-hint">Boş bırakırsanız şifre değişmez</div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Rol</label>
                            <select name="role" id="editRole" class="form-control">
                                <option value="user">Kullanıcı</option>
                                <option value="admin">Yönetici</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Durum</label>
                            <select name="status" id="editStatus" class="form-control">
                                <option value="active">Aktif</option>
                                <option value="inactive">Pasif</option>
                                <option value="banned">Yasaklı</option>
                            </select>
                        </div>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn-secondary-custom" data-bs-dismiss="modal">İptal</button>
                    <button type="submit" class="btn-primary-custom">
                        <i class="fas fa-save"></i> Kaydet
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- View User Modal -->
<div class="modal fade" id="viewUserModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-user"></i> Kullanıcı Detayı</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" style="filter: invert(1);"></button>
            </div>
            <div class="modal-body" id="viewUserContent">
                <!-- AJAX ile doldurulacak -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn-secondary-custom" data-bs-dismiss="modal">Kapat</button>
            </div>
        </div>
    </div>
</div>

<script>
var csrfToken = '<?php echo $csrfToken; ?>';
var usersData = <?php echo json_encode(array_map(function($u) {
    return [
        'id' => (int)$u['id'],
        'username' => $u['username'],
        'email' => $u['email'],
        'full_name' => $u['full_name'],
        'phone' => $u['phone'],
        'role' => $u['role'],
        'status' => $u['status'],
        'order_count' => (int)($u['order_count'] ?? 0),
        'total_spent' => (float)($u['total_spent'] ?? 0),
        'created_at' => date('d.m.Y H:i', strtotime($u['created_at'])),
        'updated_at' => $u['updated_at'] ? date('d.m.Y H:i', strtotime($u['updated_at'])) : null
    ];
}, $users), JSON_UNESCAPED_UNICODE); ?>;

function togglePassword(inputId, btn) {
    var input = document.getElementById(inputId);
    var icon = btn.querySelector('i');
    if (input.type === 'password') {
        input.type = 'text';
        icon.classList.remove('fa-eye');
        icon.classList.add('fa-eye-slash');
    } else {
        input.type = 'password';
        icon.classList.remove('fa-eye-slash');
        icon.classList.add('fa-eye');
    }
}

function editUser(userId) {
    var user = usersData.find(function(u) { return u.id === userId; });
    if (!user) return;
    
    document.getElementById('editUserId').value = user.id;
    document.getElementById('editUsername').value = user.username;
    document.getElementById('editEmail').value = user.email;
    document.getElementById('editFullName').value = user.full_name || '';
    document.getElementById('editPhone').value = user.phone || '';
    document.getElementById('editRole').value = user.role;
    document.getElementById('editStatus').value = user.status;
    document.getElementById('editPassword').value = '';
    
    new bootstrap.Modal(document.getElementById('editUserModal')).show();
}

function viewUser(userId) {
    var user = usersData.find(function(u) { return u.id === userId; });
    if (!user) return;
    
    var roleLabels = { admin: 'Yönetici', user: 'Kullanıcı' };
    var statusLabels = { active: 'Aktif', inactive: 'Pasif', banned: 'Yasaklı' };
    var roleColors = { admin: 'f59e0b', user: '3b82f6' };
    var statusColors = { active: '10b981', inactive: '6b7280', banned: 'ef4444' };
    
    var html = '<div class="user-detail-header">';
    html += '<div class="user-detail-avatar" style="' + (user.role === 'admin' ? 'background: linear-gradient(135deg, #f59e0b, #ef4444)' : '') + '">' + user.username.charAt(0).toUpperCase() + '</div>';
    html += '<div class="user-detail-info">';
    html += '<h3>' + (user.full_name || user.username) + '</h3>';
    html += '<p>@' + user.username + '</p>';
    html += '<div class="user-detail-badges">';
    html += '<span class="role-badge ' + user.role + '"><i class="fas fa-' + (user.role === 'admin' ? 'user-shield' : 'user') + '"></i> ' + roleLabels[user.role] + '</span>';
    html += '<span class="status-badge ' + user.status + '"><i class="fas fa-' + (user.status === 'active' ? 'check-circle' : (user.status === 'banned' ? 'ban' : 'pause-circle')) + '"></i> ' + statusLabels[user.status] + '</span>';
    html += '</div></div></div>';
    
    html += '<div class="detail-section"><div class="detail-section-title"><i class="fas fa-info-circle me-2"></i>Genel Bilgiler</div>';
    html += '<div class="detail-grid">';
    html += '<div class="detail-item"><label>Kullanıcı Adı</label><p>@' + user.username + '</p></div>';
    html += '<div class="detail-item"><label>E-posta</label><p><a href="mailto:' + user.email + '">' + user.email + '</a></p></div>';
    html += '<div class="detail-item"><label>Ad Soyad</label><p>' + (user.full_name || '-') + '</p></div>';
    html += '<div class="detail-item"><label>Telefon</label><p>' + (user.phone || '-') + '</p></div>';
    html += '</div></div>';
    
    html += '<div class="detail-section"><div class="detail-section-title"><i class="fas fa-shopping-cart me-2"></i>Sipariş Bilgileri</div>';
    html += '<div class="detail-grid">';
    html += '<div class="detail-item"><label>Toplam Sipariş</label><p style="font-size: 20px; font-weight: 700; color: var(--primary)">' + user.order_count + '</p></div>';
    html += '<div class="detail-item"><label>Toplam Harcama</label><p style="font-size: 20px; font-weight: 700; color: #10b981">' + formatMoney(user.total_spent) + '</p></div>';
    html += '</div></div>';
    
    html += '<div class="detail-section"><div class="detail-section-title"><i class="fas fa-clock me-2"></i>Tarih Bilgileri</div>';
    html += '<div class="detail-grid">';
    html += '<div class="detail-item"><label>Kayıt Tarihi</label><p>' + user.created_at + '</p></div>';
    html += '<div class="detail-item"><label>Son Güncelleme</label><p>' + (user.updated_at || '-') + '</p></div>';
    html += '</div></div>';
    
    document.getElementById('viewUserContent').innerHTML = html;
    new bootstrap.Modal(document.getElementById('viewUserModal')).show();
}

function resetPassword(userId, username) {
    Swal.fire({
        title: 'Şifre Sıfırla',
        html: '<strong>@' + username + '</strong> için yeni şifre oluşturulacak.<br><small class="text-muted">Yeni şifre ekranda gösterilecek.</small>',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#8b5cf6',
        cancelButtonColor: '#64748b',
        confirmButtonText: '<i class="fas fa-key me-1"></i> Şifre Oluştur',
        cancelButtonText: 'İptal',
        background: '#1e293b',
        color: '#f8fafc'
    }).then(function(result) {
        if (result.isConfirmed) {
            var form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = '<input type="hidden" name="csrf_token" value="' + csrfToken + '">' +
                '<input type="hidden" name="action" value="reset_password">' +
                '<input type="hidden" name="user_id" value="' + userId + '">';
            document.body.appendChild(form);
            form.submit();
        }
    });
}

function deleteUser(userId, username) {
    Swal.fire({
        title: 'Kullanıcıyı Sil',
        html: '<strong>@' + username + '</strong> silinecek.<br><small class="text-muted">Bu işlem geri alınamaz!</small>',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ef4444',
        cancelButtonColor: '#64748b',
        confirmButtonText: '<i class="fas fa-trash me-1"></i> Evet, Sil',
        cancelButtonText: 'İptal',
        background: '#1e293b',
        color: '#f8fafc'
    }).then(function(result) {
        if (result.isConfirmed) {
            var form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = '<input type="hidden" name="csrf_token" value="' + csrfToken + '">' +
                '<input type="hidden" name="action" value="delete_user">' +
                '<input type="hidden" name="user_id" value="' + userId + '">';
            document.body.appendChild(form);
            form.submit();
        }
    });
}

function changeStatus(userId, status) {
    var statusLabels = { active: 'aktif', inactive: 'pasif', banned: 'yasaklı' };
    
    Swal.fire({
        title: 'Durum Değiştir',
        text: 'Kullanıcı durumu "' + statusLabels[status] + '" yapılacak.',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#8b5cf6',
        cancelButtonColor: '#64748b',
        confirmButtonText: 'Evet, Değiştir',
        cancelButtonText: 'İptal',
        background: '#1e293b',
        color: '#f8fafc'
    }).then(function(result) {
        if (result.isConfirmed) {
            var form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = '<input type="hidden" name="csrf_token" value="' + csrfToken + '">' +
                '<input type="hidden" name="action" value="change_status">' +
                '<input type="hidden" name="user_id" value="' + userId + '">' +
                '<input type="hidden" name="status" value="' + status + '">';
            document.body.appendChild(form);
            form.submit();
        }
    });
}

function changeRole(userId, role) {
    var roleLabels = { admin: 'yönetici', user: 'kullanıcı' };
    
    Swal.fire({
        title: 'Rol Değiştir',
        text: 'Kullanıcı rolü "' + roleLabels[role] + '" yapılacak.',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#8b5cf6',
        cancelButtonColor: '#64748b',
        confirmButtonText: 'Evet, Değiştir',
        cancelButtonText: 'İptal',
        background: '#1e293b',
        color: '#f8fafc'
    }).then(function(result) {
        if (result.isConfirmed) {
            var form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = '<input type="hidden" name="csrf_token" value="' + csrfToken + '">' +
                '<input type="hidden" name="action" value="change_role">' +
                '<input type="hidden" name="user_id" value="' + userId + '">' +
                '<input type="hidden" name="role" value="' + role + '">';
            document.body.appendChild(form);
            form.submit();
        }
    });
}

function formatMoney(amount) {
    return '₺' + parseFloat(amount).toFixed(2).replace('.', ',').replace(/\B(?=(\d{3})+(?!\d))/g, '.');
}

// Flash mesajlarını otomatik kapat
document.addEventListener('DOMContentLoaded', function() {
    var alerts = document.querySelectorAll('.flash-container .alert');
    alerts.forEach(function(alert) {
        setTimeout(function() {
            var bsAlert = new bootstrap.Alert(alert);
            bsAlert.close();
        }, 8000);
    });
});
</script>

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