<?php
/**
 * Dua Kardeşliği Kullanıcı Yönetimi
 * Admin Panel
 */

session_start();
require_once __DIR__ . '/config/database.php';

$page_title = 'Dua Kullanıcıları';

// Admin session kontrolü
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit();
}

// Database bağlantısı
$database = new Database();
$db = $database->getConnection();

// Form işleme
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['action'])) {
            switch ($_POST['action']) {
                case 'toggle_user':
                    $userId = (int)($_POST['user_id'] ?? 0);
                    $isActive = (int)($_POST['is_active'] ?? 0);
                    
                    if ($userId <= 0) {
                        throw new Exception("Geçersiz kullanıcı ID");
                    }
                    
                    $stmt = $db->prepare("UPDATE dua_users SET is_active = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
                    
                    if ($stmt->execute([$isActive, $userId])) {
                        $status = $isActive ? 'aktif' : 'pasif';
                        $_SESSION['success_message'] = "Kullanıcı başarıyla $status yapıldı";
                    } else {
                        throw new Exception("Kullanıcı durumu değiştirilirken hata oluştu");
                    }
                    break;
                    
                case 'verify_user':
                    $userId = (int)($_POST['user_id'] ?? 0);
                    
                    if ($userId <= 0) {
                        throw new Exception("Geçersiz kullanıcı ID");
                    }
                    
                    $stmt = $db->prepare("UPDATE dua_users SET is_verified = 1, verification_token = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
                    
                    if ($stmt->execute([$userId])) {
                        $_SESSION['success_message'] = "Kullanıcı başarıyla doğrulandı";
                    } else {
                        throw new Exception("Kullanıcı doğrulanırken hata oluştu");
                    }
                    break;
                    
                case 'delete_user':
                    $userId = (int)($_POST['user_id'] ?? 0);
                    
                    if ($userId <= 0) {
                        throw new Exception("Geçersiz kullanıcı ID");
                    }
                    
                    // Kullanıcının dua isteklerini kontrol et
                    $stmt = $db->prepare("SELECT COUNT(*) as request_count FROM dua_requests WHERE user_id = ?");
                    $stmt->execute([$userId]);
                    $result = $stmt->fetch();
                    
                    if ($result['request_count'] > 0) {
                        throw new Exception("Bu kullanıcının dua istekleri bulunduğu için silinemez");
                    }
                    
                    $stmt = $db->prepare("DELETE FROM dua_users WHERE id = ?");
                    
                    if ($stmt->execute([$userId])) {
                        $_SESSION['success_message'] = "Kullanıcı başarıyla silindi";
                    } else {
                        throw new Exception("Kullanıcı silinirken hata oluştu");
                    }
                    break;
            }
        }
        
        header('Location: dua-users.php');
        exit();
        
    } catch (Exception $e) {
        $_SESSION['error_message'] = $e->getMessage();
    }
}

// Kullanıcıları getir
$users = [];
$totalUsers = 0;
$activeUsers = 0;
$verifiedUsers = 0;

try {
    // İstatistikler
    $stmt = $db->prepare("SELECT 
        COUNT(*) as total,
        SUM(is_active) as active,
        SUM(is_verified) as verified
        FROM dua_users");
    $stmt->execute();
    $stats = $stmt->fetch();
    
    $totalUsers = $stats['total'];
    $activeUsers = $stats['active'];
    $verifiedUsers = $stats['verified'];
    
    // Kullanıcı listesi
    $stmt = $db->prepare("
        SELECT u.*, 
               COUNT(dr.id) as request_count,
               MAX(dr.created_at) as last_request_date
        FROM dua_users u
        LEFT JOIN dua_requests dr ON u.id = dr.user_id
        GROUP BY u.id
        ORDER BY u.created_at DESC
    ");
    $stmt->execute();
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (Exception $e) {
    error_log("Kullanıcı listesi getirme hatası: " . $e->getMessage());
}

include 'includes/header.php';
?>

<div class="page-header">
    <h2>Dua Kardeşliği Kullanıcıları</h2>
    <p>Dua kardeşliği sistemine kayıtlı kullanıcıları yönetin</p>
</div>

<!-- İstatistikler -->
<div class="stats-container">
    <div class="stat-card">
        <div class="stat-icon">
            <i class="fas fa-users"></i>
        </div>
        <div class="stat-content">
            <h3><?php echo $totalUsers; ?></h3>
            <p>Toplam Kullanıcı</p>
        </div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon active">
            <i class="fas fa-user-check"></i>
        </div>
        <div class="stat-content">
            <h3><?php echo $activeUsers; ?></h3>
            <p>Aktif Kullanıcı</p>
        </div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon verified">
            <i class="fas fa-user-shield"></i>
        </div>
        <div class="stat-content">
            <h3><?php echo $verifiedUsers; ?></h3>
            <p>Doğrulanmış</p>
        </div>
    </div>
</div>

<!-- Kullanıcı Listesi -->
<div class="content-card">
    <div class="card-header">
        <h3>
            <i class="fas fa-list"></i>
            Kullanıcı Listesi
        </h3>
    </div>
    
    <div class="table-container">
        <?php if (count($users) > 0): ?>
            <table class="data-table">
                <thead>
                    <tr>
                        <th>Kullanıcı</th>
                        <th>İletişim</th>
                        <th>Durum</th>
                        <th>İstatistikler</th>
                        <th>Kayıt Tarihi</th>
                        <th>İşlemler</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users as $user): ?>
                        <tr>
                            <td>
                                <div class="user-info">
                                    <div class="user-avatar">
                                        <?php echo strtoupper(substr($user['full_name'], 0, 2)); ?>
                                    </div>
                                    <div class="user-details">
                                        <div class="user-name"><?php echo htmlspecialchars($user['full_name']); ?></div>
                                        <div class="username">@<?php echo htmlspecialchars($user['username']); ?></div>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <div class="contact-info">
                                    <div class="email">
                                        <i class="fas fa-envelope"></i>
                                        <?php echo htmlspecialchars($user['email']); ?>
                                    </div>
                                    <?php if (!empty($user['phone'])): ?>
                                        <div class="phone">
                                            <i class="fas fa-phone"></i>
                                            <?php echo htmlspecialchars($user['phone']); ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td>
                                <div class="status-badges">
                                    <span class="badge <?php echo $user['is_active'] ? 'badge-success' : 'badge-danger'; ?>">
                                        <?php echo $user['is_active'] ? 'Aktif' : 'Pasif'; ?>
                                    </span>
                                    <span class="badge <?php echo $user['is_verified'] ? 'badge-info' : 'badge-warning'; ?>">
                                        <?php echo $user['is_verified'] ? 'Doğrulanmış' : 'Beklemede'; ?>
                                    </span>
                                </div>
                            </td>
                            <td>
                                <div class="user-stats">
                                    <div class="stat-item">
                                        <span class="stat-value"><?php echo $user['request_count']; ?></span>
                                        <span class="stat-label">Dua İsteği</span>
                                    </div>
                                    <?php if ($user['last_request_date']): ?>
                                        <div class="last-activity">
                                            Son: <?php echo date('d.m.Y', strtotime($user['last_request_date'])); ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td>
                                <div class="date-info">
                                    <div class="date"><?php echo date('d.m.Y', strtotime($user['created_at'])); ?></div>
                                    <div class="time"><?php echo date('H:i', strtotime($user['created_at'])); ?></div>
                                </div>
                            </td>
                            <td>
                                <div class="action-buttons">
                                    <!-- Aktif/Pasif Toggle -->
                                    <form method="POST" style="display: inline;">
                                        <input type="hidden" name="action" value="toggle_user">
                                        <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                        <input type="hidden" name="is_active" value="<?php echo $user['is_active'] ? 0 : 1; ?>">
                                        <button type="submit" class="btn btn-sm <?php echo $user['is_active'] ? 'btn-warning' : 'btn-success'; ?>" 
                                                title="<?php echo $user['is_active'] ? 'Pasif Yap' : 'Aktif Yap'; ?>">
                                            <i class="fas <?php echo $user['is_active'] ? 'fa-pause' : 'fa-play'; ?>"></i>
                                        </button>
                                    </form>
                                    
                                    <!-- Doğrulama -->
                                    <?php if (!$user['is_verified']): ?>
                                        <form method="POST" style="display: inline;">
                                            <input type="hidden" name="action" value="verify_user">
                                            <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-info" title="Doğrula">
                                                <i class="fas fa-check-circle"></i>
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                    
                                    <!-- Silme -->
                                    <?php if ($user['request_count'] == 0): ?>
                                        <form method="POST" style="display: inline;" 
                                              onsubmit="return confirm('Bu kullanıcıyı silmek istediğinizden emin misiniz?')">
                                            <input type="hidden" name="action" value="delete_user">
                                            <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-danger" title="Sil">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php else: ?>
            <div class="empty-state">
                <i class="fas fa-users"></i>
                <h3>Henüz kullanıcı bulunmuyor</h3>
                <p>Dua kardeşliği sistemine henüz kimse kayıt olmamış</p>
            </div>
        <?php endif; ?>
    </div>
</div>

<style>
.stats-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 1.5rem;
    margin-bottom: 2rem;
}

.stat-card {
    background: white;
    border-radius: 12px;
    padding: 1.5rem;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    display: flex;
    align-items: center;
    gap: 1rem;
}

.stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #e3f2fd;
    color: #1976d2;
    font-size: 1.5rem;
}

.stat-icon.active {
    background: #e8f5e8;
    color: #2e7d32;
}

.stat-icon.verified {
    background: #fff3e0;
    color: #f57c00;
}

.stat-content h3 {
    margin: 0;
    font-size: 2rem;
    font-weight: bold;
    color: #1f2937;
}

.stat-content p {
    margin: 0;
    color: #6b7280;
    font-size: 0.9rem;
}

.user-info {
    display: flex;
    align-items: center;
    gap: 0.75rem;
}

.user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    font-size: 0.8rem;
}

.user-details {
    flex: 1;
}

.user-name {
    font-weight: 600;
    color: #1f2937;
    margin-bottom: 0.25rem;
}

.username {
    font-size: 0.8rem;
    color: #6b7280;
}

.contact-info {
    font-size: 0.85rem;
}

.contact-info .email,
.contact-info .phone {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    margin-bottom: 0.25rem;
    color: #4b5563;
}

.contact-info i {
    width: 12px;
    color: #9ca3af;
}

.status-badges {
    display: flex;
    flex-direction: column;
    gap: 0.25rem;
}

.badge {
    padding: 0.25rem 0.5rem;
    border-radius: 6px;
    font-size: 0.75rem;
    font-weight: 600;
    text-align: center;
}

.badge-success {
    background: #dcfce7;
    color: #166534;
}

.badge-danger {
    background: #fee2e2;
    color: #991b1b;
}

.badge-info {
    background: #dbeafe;
    color: #1e40af;
}

.badge-warning {
    background: #fef3c7;
    color: #92400e;
}

.user-stats {
    text-align: center;
}

.stat-item {
    margin-bottom: 0.5rem;
}

.stat-value {
    display: block;
    font-size: 1.2rem;
    font-weight: bold;
    color: #1f2937;
}

.stat-label {
    font-size: 0.75rem;
    color: #6b7280;
}

.last-activity {
    font-size: 0.75rem;
    color: #9ca3af;
}

.date-info {
    text-align: center;
}

.date-info .date {
    font-weight: 600;
    color: #1f2937;
    margin-bottom: 0.25rem;
}

.date-info .time {
    font-size: 0.8rem;
    color: #6b7280;
}

.action-buttons {
    display: flex;
    gap: 0.25rem;
    justify-content: center;
}

.btn-sm {
    padding: 0.375rem 0.5rem;
    font-size: 0.8rem;
    border-radius: 6px;
}

.empty-state {
    text-align: center;
    padding: 3rem;
    color: #6b7280;
}

.empty-state i {
    font-size: 3rem;
    margin-bottom: 1rem;
    color: #d1d5db;
}

.empty-state h3 {
    margin-bottom: 0.5rem;
    color: #374151;
}

@media (max-width: 768px) {
    .stats-container {
        grid-template-columns: 1fr;
    }
    
    .table-container {
        overflow-x: auto;
    }
    
    .action-buttons {
        flex-direction: column;
    }
}
</style>

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