<?php
session_start();
require_once 'config.php';
require_once 'auth.php';

// Admin kontrolü
if (!isset($_SESSION['admin_logged_in']) || !has_permission('tournaments_manage')) {
    header('Location: index.php');
    exit;
}

$page_title = "Turnuva Yönetimi";

// Aktif turnuvalar
try {
    $stmt = $pdo->query("
        SELECT t.*, 
               COUNT(tp.id) as participant_count,
               CASE 
                   WHEN NOW() < t.start_date THEN 'Yaklaşan'
                   WHEN NOW() BETWEEN t.start_date AND t.end_date THEN 'Aktif'
                   WHEN NOW() > t.end_date THEN 'Tamamlandı'
               END as status_text
        FROM tournaments t
        LEFT JOIN tournament_participants tp ON t.id = tp.tournament_id
        GROUP BY t.id
        ORDER BY t.start_date DESC
        LIMIT 20
    ");
    $tournaments = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $tournaments = [];
}

// Mevsimsel etkinlikler
try {
    $stmt = $pdo->query("
        SELECT * FROM seasonal_events 
        WHERE end_date >= NOW() 
        ORDER BY start_date ASC
        LIMIT 10
    ");
    $seasonal_events = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $seasonal_events = [];
}

// İstatistikler
try {
    $stats = [];
    
    // Toplam turnuva sayısı
    $stmt = $pdo->query("SELECT COUNT(*) as total FROM tournaments");
    $stats['total_tournaments'] = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Aktif turnuvalar
    $stmt = $pdo->query("SELECT COUNT(*) as active FROM tournaments WHERE status = 'active'");
    $stats['active_tournaments'] = $stmt->fetch(PDO::FETCH_ASSOC)['active'];
    
    // Toplam katılımcı
    $stmt = $pdo->query("SELECT COUNT(*) as participants FROM tournament_participants");
    $stats['total_participants'] = $stmt->fetch(PDO::FETCH_ASSOC)['participants'];
    
    // Toplam ödül havuzu
    $stmt = $pdo->query("SELECT SUM(prize_pool) as total_prizes FROM tournaments WHERE status IN ('active', 'upcoming')");
    $stats['total_prize_pool'] = $stmt->fetch(PDO::FETCH_ASSOC)['total_prizes'] ?? 0;
    
} catch (Exception $e) {
    $stats = ['total_tournaments' => 0, 'active_tournaments' => 0, 'total_participants' => 0, 'total_prize_pool' => 0];
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?> - Admin Panel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link rel="stylesheet" href="styles.css">
    <style>
        .tournament-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 20px;
            transition: transform 0.3s ease;
        }
        
        .tournament-card:hover {
            transform: translateY(-5px);
        }
        
        .tournament-card.active {
            background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
        }
        
        .tournament-card.finished {
            background: linear-gradient(135deg, #bdc3c7 0%, #2c3e50 100%);
        }
        
        .tournament-card.upcoming {
            background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
            color: #333;
        }
        
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 50px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .status-active { background: #28a745; color: white; }
        .status-upcoming { background: #ffc107; color: #333; }
        .status-finished { background: #6c757d; color: white; }
        
        .prize-amount {
            font-size: 1.5rem;
            font-weight: bold;
            color: #ffd700;
        }
        
        .participant-count {
            background: rgba(255,255,255,0.2);
            padding: 0.5rem 1rem;
            border-radius: 25px;
            display: inline-block;
        }
        
        .event-card {
            border-left: 4px solid #007bff;
            background: #f8f9fa;
            padding: 1rem;
            margin-bottom: 1rem;
            border-radius: 0 8px 8px 0;
        }
        
        .event-card.holiday { border-left-color: #dc3545; }
        .event-card.special { border-left-color: #28a745; }
        .event-card.anniversary { border-left-color: #ffc107; }
        .event-card.seasonal { border-left-color: #17a2b8; }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <?php include 'sidebar.php'; ?>
            
            <div class="col-md-10 p-4">
                <?php include 'topbar.php'; ?>
                
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h1><i class="fas fa-trophy"></i> <?php echo $page_title; ?></h1>
                    <div>
                        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#newTournamentModal">
                            <i class="fas fa-plus"></i> Yeni Turnuva
                        </button>
                        <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#newEventModal">
                            <i class="fas fa-calendar-plus"></i> Yeni Etkinlik
                        </button>
                    </div>
                </div>

                <!-- İstatistik Kartları -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="tournament-card">
                            <h5><i class="fas fa-trophy"></i> Toplam Turnuva</h5>
                            <h2><?php echo number_format($stats['total_tournaments']); ?></h2>
                            <small>Tüm zamanlar</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="tournament-card active">
                            <h5><i class="fas fa-play"></i> Aktif Turnuvalar</h5>
                            <h2><?php echo number_format($stats['active_tournaments']); ?></h2>
                            <small>Şu anda devam eden</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="tournament-card upcoming">
                            <h5><i class="fas fa-users"></i> Toplam Katılımcı</h5>
                            <h2><?php echo number_format($stats['total_participants']); ?></h2>
                            <small>Tüm turnuvalarda</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="tournament-card finished">
                            <h5><i class="fas fa-coins"></i> Ödül Havuzu</h5>
                            <h2><?php echo number_format($stats['total_prize_pool'], 2); ?> ₺</h2>
                            <small>Aktif turnuvalar</small>
                        </div>
                    </div>
                </div>

                <!-- Tabs -->
                <ul class="nav nav-tabs" id="tournamentTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="tournaments-tab" data-bs-toggle="tab" data-bs-target="#tournaments" type="button" role="tab">
                            <i class="fas fa-trophy"></i> Turnuvalar
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="events-tab" data-bs-toggle="tab" data-bs-target="#events" type="button" role="tab">
                            <i class="fas fa-calendar-alt"></i> Mevsimsel Etkinlikler
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="leaderboard-tab" data-bs-toggle="tab" data-bs-target="#leaderboard" type="button" role="tab">
                            <i class="fas fa-medal"></i> Liderlik Tablosu
                        </button>
                    </li>
                </ul>

                <div class="tab-content" id="tournamentTabsContent">
                    <!-- Turnuvalar -->
                    <div class="tab-pane fade show active" id="tournaments" role="tabpanel">
                        <div class="card mt-3">
                            <div class="card-header">
                                <h5><i class="fas fa-trophy"></i> Turnuvalar</h5>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped" id="tournamentsTable">
                                        <thead>
                                            <tr>
                                                <th>Turnuva Adı</th>
                                                <th>Tür</th>
                                                <th>Ödül Havuzu</th>
                                                <th>Katılımcı</th>
                                                <th>Başlangıç</th>
                                                <th>Bitiş</th>
                                                <th>Durum</th>
                                                <th>İşlemler</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($tournaments as $tournament): ?>
                                            <tr>
                                                <td>
                                                    <strong><?php echo htmlspecialchars($tournament['name']); ?></strong>
                                                    <br><small class="text-muted"><?php echo htmlspecialchars(substr($tournament['description'], 0, 50)) . '...'; ?></small>
                                                </td>
                                                <td>
                                                    <span class="badge bg-info">
                                                        <?php echo strtoupper($tournament['tournament_type']); ?>
                                                    </span>
                                                </td>
                                                <td class="prize-amount">₺<?php echo number_format($tournament['prize_pool'], 2); ?></td>
                                                <td>
                                                    <span class="participant-count">
                                                        <?php echo $tournament['participant_count']; ?>/<?php echo $tournament['max_participants']; ?>
                                                    </span>
                                                </td>
                                                <td><?php echo date('d.m.Y H:i', strtotime($tournament['start_date'])); ?></td>
                                                <td><?php echo date('d.m.Y H:i', strtotime($tournament['end_date'])); ?></td>
                                                <td>
                                                    <span class="status-badge status-<?php echo strtolower($tournament['status']); ?>">
                                                        <?php echo $tournament['status_text']; ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <div class="btn-group btn-group-sm">
                                                        <button class="btn btn-outline-primary" onclick="viewTournament(<?php echo $tournament['id']; ?>)">
                                                            <i class="fas fa-eye"></i>
                                                        </button>
                                                        <button class="btn btn-outline-warning" onclick="editTournament(<?php echo $tournament['id']; ?>)">
                                                            <i class="fas fa-edit"></i>
                                                        </button>
                                                        <?php if ($tournament['status'] == 'upcoming'): ?>
                                                        <button class="btn btn-outline-danger" onclick="cancelTournament(<?php echo $tournament['id']; ?>)">
                                                            <i class="fas fa-times"></i>
                                                        </button>
                                                        <?php endif; ?>
                                                    </div>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Mevsimsel Etkinlikler -->
                    <div class="tab-pane fade" id="events" role="tabpanel">
                        <div class="card mt-3">
                            <div class="card-header">
                                <h5><i class="fas fa-calendar-alt"></i> Mevsimsel Etkinlikler</h5>
                            </div>
                            <div class="card-body">
                                <?php foreach ($seasonal_events as $event): ?>
                                <div class="event-card <?php echo $event['event_type']; ?>">
                                    <div class="row">
                                        <div class="col-md-8">
                                            <h5><?php echo htmlspecialchars($event['event_name']); ?></h5>
                                            <p class="mb-2"><?php echo htmlspecialchars($event['description']); ?></p>
                                            <div class="d-flex gap-3">
                                                <?php if ($event['bonus_multiplier'] > 1): ?>
                                                <span class="badge bg-success">
                                                    %<?php echo ($event['bonus_multiplier'] - 1) * 100; ?> Bonus
                                                </span>
                                                <?php endif; ?>
                                                <?php if ($event['free_spins'] > 0): ?>
                                                <span class="badge bg-primary">
                                                    <?php echo $event['free_spins']; ?> Free Spin
                                                </span>
                                                <?php endif; ?>
                                                <?php if ($event['cashback_percentage'] > 0): ?>
                                                <span class="badge bg-warning">
                                                    %<?php echo $event['cashback_percentage']; ?> Cashback
                                                </span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <div class="col-md-4 text-end">
                                            <small class="text-muted">
                                                <?php echo date('d.m.Y H:i', strtotime($event['start_date'])); ?> - 
                                                <?php echo date('d.m.Y H:i', strtotime($event['end_date'])); ?>
                                            </small>
                                            <br>
                                            <div class="btn-group btn-group-sm mt-2">
                                                <button class="btn btn-outline-warning" onclick="editEvent(<?php echo $event['id']; ?>)">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button class="btn btn-outline-danger" onclick="deleteEvent(<?php echo $event['id']; ?>)">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Liderlik Tablosu -->
                    <div class="tab-pane fade" id="leaderboard" role="tabpanel">
                        <div class="card mt-3">
                            <div class="card-header">
                                <h5><i class="fas fa-medal"></i> Genel Liderlik Tablosu</h5>
                            </div>
                            <div class="card-body">
                                <p class="text-muted">Tüm turnuvalardaki en başarılı oyuncular</p>
                                <!-- Liderlik tablosu buraya eklenecek -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Yeni Turnuva Modal -->
    <div class="modal fade" id="newTournamentModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Yeni Turnuva Oluştur</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="newTournamentForm">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Turnuva Adı</label>
                                    <input type="text" class="form-control" name="name" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Turnuva Türü</label>
                                    <select class="form-select" name="tournament_type" required>
                                        <option value="slot">Slot</option>
                                        <option value="casino">Casino</option>
                                        <option value="sports">Spor</option>
                                        <option value="mixed">Karışık</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Açıklama</label>
                            <textarea class="form-control" name="description" rows="3"></textarea>
                        </div>
                        <div class="row">
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label">Giriş Ücreti (₺)</label>
                                    <input type="number" class="form-control" name="entry_fee" step="0.01" value="0">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label">Ödül Havuzu (₺)</label>
                                    <input type="number" class="form-control" name="prize_pool" step="0.01" required>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label">Max Katılımcı</label>
                                    <input type="number" class="form-control" name="max_participants" value="1000">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Başlangıç Tarihi</label>
                                    <input type="datetime-local" class="form-control" name="start_date" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Bitiş Tarihi</label>
                                    <input type="datetime-local" class="form-control" name="end_date" required>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">İptal</button>
                    <button type="button" class="btn btn-primary" onclick="createTournament()">Turnuva Oluştur</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
    
    <script>
        $(document).ready(function() {
            $('#tournamentsTable').DataTable({
                "language": {
                    "url": "//cdn.datatables.net/plug-ins/1.11.5/i18n/tr.json"
                },
                "order": [[ 4, "desc" ]]
            });
        });

        function createTournament() {
            // Turnuva oluşturma fonksiyonu
            alert('Turnuva oluşturma özelliği yakında eklenecek!');
        }

        function viewTournament(id) {
            // Turnuva görüntüleme
            alert('Turnuva detayları: ' + id);
        }

        function editTournament(id) {
            // Turnuva düzenleme
            alert('Turnuva düzenleme: ' + id);
        }

        function cancelTournament(id) {
            if (confirm('Bu turnuvayı iptal etmek istediğinizden emin misiniz?')) {
                // Turnuva iptal etme
                alert('Turnuva iptal edildi: ' + id);
            }
        }
    </script>
</body>
</html>