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

require_permission('tournaments_manage');

$current_page = 'tournament_management';
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Turnuva Yönetimi - Admin Panel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
    <link rel="stylesheet" href="../inc/styles.09e2c710755c8867a460.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .admin-container {
            padding: 20px;
            max-width: 1400px;
            margin: 0 auto;
        }
        
        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid #333;
        }
        
        .page-title {
            font-size: 28px;
            font-weight: bold;
            color: #ffd700;
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #ffd700, #ffed4e);
            color: #000;
            border: none;
            padding: 12px 24px;
            border-radius: 8px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(255, 215, 0, 0.3);
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: linear-gradient(135deg, #1a1a1a, #2a2a2a);
            border: 1px solid #333;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
        }
        
        .stat-icon {
            font-size: 32px;
            color: #ffd700;
            margin-bottom: 10px;
        }
        
        .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: #fff;
            margin-bottom: 5px;
        }
        
        .stat-label {
            color: #ccc;
            font-size: 14px;
        }
        
        .content-tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            border-bottom: 1px solid #333;
        }
        
        .tab-btn {
            padding: 12px 24px;
            background: transparent;
            border: none;
            color: #ccc;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            transition: all 0.3s;
            font-weight: 500;
        }
        
        .tab-btn.active {
            color: #ffd700;
            border-bottom-color: #ffd700;
        }
        
        .tab-content {
            display: none;
        }
        
        .tab-content.active {
            display: block;
        }
        
        .tournaments-table {
            background: #1a1a1a;
            border: 1px solid #333;
            border-radius: 10px;
            overflow: hidden;
        }
        
        .table-header {
            background: #2a2a2a;
            padding: 15px 20px;
            display: grid;
            grid-template-columns: 2fr 1fr 1fr 1fr 1fr 1fr 150px;
            gap: 15px;
            font-weight: bold;
            color: #ffd700;
            border-bottom: 1px solid #333;
        }
        
        .tournament-row {
            padding: 15px 20px;
            display: grid;
            grid-template-columns: 2fr 1fr 1fr 1fr 1fr 1fr 150px;
            gap: 15px;
            align-items: center;
            border-bottom: 1px solid #333;
            transition: background 0.3s;
        }
        
        .tournament-row:hover {
            background: #2a2a2a;
        }
        
        .tournament-name {
            font-weight: bold;
            color: #fff;
        }
        
        .tournament-description {
            font-size: 12px;
            color: #ccc;
            margin-top: 5px;
        }
        
        .status-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
            text-align: center;
        }
        
        .status-upcoming { background: #4a90e2; color: white; }
        .status-registration_open { background: #7ed321; color: white; }
        .status-active { background: #f5a623; color: white; }
        .status-finished { background: #666; color: white; }
        .status-cancelled { background: #d0021b; color: white; }
        
        .action-buttons {
            display: flex;
            gap: 5px;
        }
        
        .btn-small {
            padding: 6px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.3s;
        }
        
        .btn-edit {
            background: #4a90e2;
            color: white;
        }
        
        .btn-delete {
            background: #d0021b;
            color: white;
        }
        
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            z-index: 1000;
        }
        
        .modal-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: #1a1a1a;
            border: 1px solid #333;
            border-radius: 10px;
            padding: 30px;
            width: 90%;
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #333;
        }
        
        .modal-title {
            font-size: 20px;
            font-weight: bold;
            color: #ffd700;
        }
        
        .close-btn {
            background: none;
            border: none;
            color: #ccc;
            font-size: 24px;
            cursor: pointer;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-label {
            display: block;
            margin-bottom: 8px;
            color: #ccc;
            font-weight: 500;
        }
        
        .form-input, .form-select, .form-textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #333;
            background: #2a2a2a;
            color: #fff;
            border-radius: 5px;
            font-size: 14px;
        }
        
        .form-textarea {
            resize: vertical;
            min-height: 80px;
        }
        
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
        }
        
        .prize-distribution {
            background: #2a2a2a;
            border: 1px solid #333;
            border-radius: 5px;
            padding: 15px;
        }
        
        .prize-item {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 10px;
        }
        
        .prize-position {
            min-width: 60px;
            color: #ffd700;
            font-weight: bold;
        }
        
        .prize-percentage {
            flex: 1;
        }
        
        .loading {
            text-align: center;
            padding: 40px;
            color: #ccc;
        }
        
        @media (max-width: 1200px) {
            .table-header, .tournament-row {
                grid-template-columns: 2fr 1fr 1fr 1fr 120px;
            }
            
            .participants-col, .entry-fee-col {
                display: none;
            }
        }
        
        @media (max-width: 768px) {
            .stats-grid {
                grid-template-columns: 1fr 1fr;
            }
            
            .table-header, .tournament-row {
                grid-template-columns: 1fr 80px 100px;
            }
            
            .category-col, .prize-col, .participants-col, .entry-fee-col {
                display: none;
            }
            
            .form-row {
                grid-template-columns: 1fr;
            }
        }
    </style>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <?php include 'topbar.php'; ?>
    <div class="container-fluid">
        <div class="row">
            <?php include 'sidebar.php'; ?>
            <main class="col-md-10 ms-sm-auto col-lg-10 px-md-4">
                <div class="admin-container">
                <div class="page-header">
                    <h1 class="page-title">
                        <i class="fas fa-trophy"></i>
                        Turnuva Yönetimi
                    </h1>
                    <button class="btn-primary" onclick="openCreateModal()">
                        <i class="fas fa-plus"></i> Yeni Turnuva
                    </button>
                </div>
                
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-icon"><i class="fas fa-trophy"></i></div>
                        <div class="stat-value" id="totalTournaments">-</div>
                        <div class="stat-label">Toplam Turnuva</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon"><i class="fas fa-play"></i></div>
                        <div class="stat-value" id="activeTournaments">-</div>
                        <div class="stat-label">Aktif Turnuva</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon"><i class="fas fa-users"></i></div>
                        <div class="stat-value" id="totalParticipants">-</div>
                        <div class="stat-label">Toplam Katılımcı</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon"><i class="fas fa-coins"></i></div>
                        <div class="stat-value" id="totalPrizePool">-</div>
                        <div class="stat-label">Toplam Ödül Havuzu</div>
                    </div>
                </div>
                
                <div class="content-tabs">
                    <button class="tab-btn active" data-tab="tournaments">Turnuvalar</button>
                    <button class="tab-btn" data-tab="types">Turnuva Türleri</button>
                </div>
                
                <div id="tournamentsTab" class="tab-content active">
                    <div class="tournaments-table">
                        <div class="table-header">
                            <div>Turnuva Adı</div>
                            <div class="category-col">Kategori</div>
                            <div class="participants-col">Katılımcı</div>
                            <div class="entry-fee-col">Giriş Ücreti</div>
                            <div class="prize-col">Ödül Havuzu</div>
                            <div>Durum</div>
                            <div>İşlemler</div>
                        </div>
                        <div id="tournamentsContainer">
                            <div class="loading">
                                <i class="fas fa-spinner fa-spin"></i>
                                <p>Turnuvalar yükleniyor...</p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div id="typesTab" class="tab-content">
                    <div class="tournaments-table">
                        <div class="table-header">
                            <div>Tür Adı</div>
                            <div>Açıklama</div>
                            <div>Durum</div>
                            <div>İşlemler</div>
                        </div>
                        <div id="typesContainer">
                            <div class="loading">
                                <i class="fas fa-spinner fa-spin"></i>
                                <p>Turnuva türleri yükleniyor...</p>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- Tournament Modal -->
    <div id="tournamentModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title" id="modalTitle">Yeni Turnuva</h2>
                <button class="close-btn" onclick="closeModal()">&times;</button>
            </div>
            
            <form id="tournamentForm">
                <input type="hidden" id="tournamentId" name="tournament_id">
                
                <div class="form-group">
                    <label class="form-label">Turnuva Adı</label>
                    <input type="text" id="tournamentName" name="tournament_name" class="form-input" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Açıklama</label>
                    <textarea id="description" name="description" class="form-textarea"></textarea>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Turnuva Türü</label>
                        <select id="tournamentType" name="tournament_type_id" class="form-select" required>
                            <option value="">Seçiniz</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Oyun Kategorisi</label>
                        <select id="gameCategory" name="game_category" class="form-select" required>
                            <option value="">Seçiniz</option>
                            <option value="slots">Slot Oyunları</option>
                            <option value="table_games">Masa Oyunları</option>
                            <option value="live_casino">Canlı Casino</option>
                            <option value="sports">Spor Bahisleri</option>
                        </select>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Giriş Ücreti (₺)</label>
                        <input type="number" id="entryFee" name="entry_fee" class="form-input" min="0" step="0.01" value="0">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Ödül Havuzu (₺)</label>
                        <input type="number" id="prizePool" name="prize_pool" class="form-input" min="0" step="0.01" required>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Min Katılımcı</label>
                        <input type="number" id="minParticipants" name="min_participants" class="form-input" min="2" value="2">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Max Katılımcı</label>
                        <input type="number" id="maxParticipants" name="max_participants" class="form-input" min="2" value="100">
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Kayıt Başlangıç</label>
                        <input type="datetime-local" id="registrationStart" name="registration_start" class="form-input" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Kayıt Bitiş</label>
                        <input type="datetime-local" id="registrationEnd" name="registration_end" class="form-input" required>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Turnuva Başlangıç</label>
                        <input type="datetime-local" id="startDate" name="start_date" class="form-input" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Turnuva Bitiş</label>
                        <input type="datetime-local" id="endDate" name="end_date" class="form-input" required>
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Durum</label>
                    <select id="status" name="status" class="form-select" required>
                        <option value="upcoming">Yaklaşan</option>
                        <option value="registration_open">Kayıt Açık</option>
                        <option value="active">Aktif</option>
                        <option value="finished">Tamamlandı</option>
                        <option value="cancelled">İptal Edildi</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Ödül Dağılımı (%)</label>
                    <div class="prize-distribution">
                        <div class="prize-item">
                            <span class="prize-position">1. Sıra:</span>
                            <input type="number" id="prize1" class="form-input prize-percentage" min="0" max="100" value="50">
                            <span>%</span>
                        </div>
                        <div class="prize-item">
                            <span class="prize-position">2. Sıra:</span>
                            <input type="number" id="prize2" class="form-input prize-percentage" min="0" max="100" value="30">
                            <span>%</span>
                        </div>
                        <div class="prize-item">
                            <span class="prize-position">3. Sıra:</span>
                            <input type="number" id="prize3" class="form-input prize-percentage" min="0" max="100" value="20">
                            <span>%</span>
                        </div>
                    </div>
                </div>
                
                <div class="form-group">
                    <label>
                        <input type="checkbox" id="isFeatured" name="is_featured"> Öne Çıkarılsın
                    </label>
                </div>
                
                <div style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 30px;">
                    <button type="button" class="btn-small" onclick="closeModal()" style="background: #666; color: white; padding: 10px 20px;">İptal</button>
                    <button type="submit" class="btn-primary" style="padding: 10px 20px;">Kaydet</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        let tournaments = [];
        let tournamentTypes = [];
        
        document.addEventListener('DOMContentLoaded', function() {
            loadTournaments();
            loadTournamentTypes();
            
            // Tab değiştirme
            document.querySelectorAll('.tab-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const tab = this.dataset.tab;
                    switchTab(tab);
                });
            });
            
            // Form submit
            document.getElementById('tournamentForm').addEventListener('submit', saveTournament);
        });
        
        function switchTab(tab) {
            document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
            document.querySelector(`[data-tab="${tab}"]`).classList.add('active');
            
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            document.getElementById(tab + 'Tab').classList.add('active');
        }
        
        function loadTournaments() {
            fetch('../api/tournament_system.php?action=admin_get_tournaments')
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        tournaments = data.tournaments;
                        displayTournaments();
                        updateStats();
                    } else {
                        showError('Turnuvalar yüklenirken hata oluştu');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showError('Bağlantı hatası');
                });
        }
        
        function loadTournamentTypes() {
            fetch('../api/tournament_system.php?action=get_tournament_types')
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        tournamentTypes = data.types;
                        populateTypeSelect();
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                });
        }
        
        function populateTypeSelect() {
            const select = document.getElementById('tournamentType');
            select.innerHTML = '<option value="">Seçiniz</option>';
            
            tournamentTypes.forEach(type => {
                const option = document.createElement('option');
                option.value = type.id;
                option.textContent = type.type_name;
                select.appendChild(option);
            });
        }
        
        function displayTournaments() {
            const container = document.getElementById('tournamentsContainer');
            
            if (tournaments.length === 0) {
                container.innerHTML = '<div class="loading">Henüz turnuva bulunmuyor</div>';
                return;
            }
            
            container.innerHTML = tournaments.map(tournament => `
                <div class="tournament-row">
                    <div>
                        <div class="tournament-name">${tournament.tournament_name}</div>
                        <div class="tournament-description">${tournament.description || ''}</div>
                    </div>
                    <div class="category-col">${tournament.game_category}</div>
                    <div class="participants-col">${tournament.participant_count}/${tournament.max_participants}</div>
                    <div class="entry-fee-col">${tournament.entry_fee} ₺</div>
                    <div class="prize-col">${tournament.prize_pool} ₺</div>
                    <div>
                        <span class="status-badge status-${tournament.status}">
                            ${getStatusText(tournament.status)}
                        </span>
                    </div>
                    <div class="action-buttons">
                        <button class="btn-small btn-edit" onclick="editTournament(${tournament.id})">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn-small btn-delete" onclick="deleteTournament(${tournament.id})">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            `).join('');
        }
        
        function updateStats() {
            const total = tournaments.length;
            const active = tournaments.filter(t => t.status === 'active' || t.status === 'registration_open').length;
            const totalParticipants = tournaments.reduce((sum, t) => sum + parseInt(t.participant_count), 0);
            const totalPrizePool = tournaments.reduce((sum, t) => sum + parseFloat(t.prize_pool), 0);
            
            document.getElementById('totalTournaments').textContent = total;
            document.getElementById('activeTournaments').textContent = active;
            document.getElementById('totalParticipants').textContent = totalParticipants;
            document.getElementById('totalPrizePool').textContent = totalPrizePool.toLocaleString('tr-TR') + ' ₺';
        }
        
        function openCreateModal() {
            document.getElementById('modalTitle').textContent = 'Yeni Turnuva';
            document.getElementById('tournamentForm').reset();
            document.getElementById('tournamentId').value = '';
            document.getElementById('tournamentModal').style.display = 'block';
        }
        
        function editTournament(id) {
            const tournament = tournaments.find(t => t.id == id);
            if (!tournament) return;
            
            document.getElementById('modalTitle').textContent = 'Turnuva Düzenle';
            document.getElementById('tournamentId').value = tournament.id;
            document.getElementById('tournamentName').value = tournament.tournament_name;
            document.getElementById('description').value = tournament.description || '';
            document.getElementById('tournamentType').value = tournament.tournament_type_id;
            document.getElementById('gameCategory').value = tournament.game_category;
            document.getElementById('entryFee').value = tournament.entry_fee;
            document.getElementById('prizePool').value = tournament.prize_pool;
            document.getElementById('minParticipants').value = tournament.min_participants;
            document.getElementById('maxParticipants').value = tournament.max_participants;
            document.getElementById('registrationStart').value = formatDateForInput(tournament.registration_start);
            document.getElementById('registrationEnd').value = formatDateForInput(tournament.registration_end);
            document.getElementById('startDate').value = formatDateForInput(tournament.start_date);
            document.getElementById('endDate').value = formatDateForInput(tournament.end_date);
            document.getElementById('status').value = tournament.status;
            document.getElementById('isFeatured').checked = tournament.is_featured == 1;
            
            document.getElementById('tournamentModal').style.display = 'block';
        }
        
        function deleteTournament(id) {
            if (!confirm('Bu turnuvayı silmek istediğinizden emin misiniz?')) {
                return;
            }
            
            const formData = new FormData();
            formData.append('action', 'admin_delete_tournament');
            formData.append('tournament_id', id);
            
            fetch('../api/tournament_system.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    alert('Turnuva başarıyla silindi');
                    loadTournaments();
                } else {
                    alert('Hata: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Bağlantı hatası oluştu');
            });
        }
        
        function saveTournament(e) {
            e.preventDefault();
            
            const formData = new FormData();
            const tournamentId = document.getElementById('tournamentId').value;
            
            const data = {
                tournament_name: document.getElementById('tournamentName').value,
                description: document.getElementById('description').value,
                tournament_type_id: document.getElementById('tournamentType').value,
                game_category: document.getElementById('gameCategory').value,
                entry_fee: document.getElementById('entryFee').value,
                prize_pool: document.getElementById('prizePool').value,
                min_participants: document.getElementById('minParticipants').value,
                max_participants: document.getElementById('maxParticipants').value,
                registration_start: document.getElementById('registrationStart').value,
                registration_end: document.getElementById('registrationEnd').value,
                start_date: document.getElementById('startDate').value,
                end_date: document.getElementById('endDate').value,
                status: document.getElementById('status').value,
                is_featured: document.getElementById('isFeatured').checked,
                prize_distribution: {
                    "1": parseInt(document.getElementById('prize1').value),
                    "2": parseInt(document.getElementById('prize2').value),
                    "3": parseInt(document.getElementById('prize3').value)
                }
            };
            
            if (tournamentId) {
                data.tournament_id = tournamentId;
                data.action = 'admin_update_tournament';
            } else {
                data.action = 'admin_create_tournament';
            }
            
            fetch('../api/tournament_system.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    alert(tournamentId ? 'Turnuva başarıyla güncellendi' : 'Turnuva başarıyla oluşturuldu');
                    closeModal();
                    loadTournaments();
                } else {
                    alert('Hata: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Bağlantı hatası oluştu');
            });
        }
        
        function closeModal() {
            document.getElementById('tournamentModal').style.display = 'none';
        }
        
        function getStatusText(status) {
            const statusTexts = {
                'upcoming': 'Yaklaşan',
                'registration_open': 'Kayıt Açık',
                'active': 'Aktif',
                'finished': 'Tamamlandı',
                'cancelled': 'İptal Edildi'
            };
            return statusTexts[status] || status;
        }
        
        function formatDateForInput(dateString) {
            const date = new Date(dateString);
            return date.toISOString().slice(0, 16);
        }
        
        function showError(message) {
            document.getElementById('tournamentsContainer').innerHTML = `
                <div class="loading">
                    <i class="fas fa-exclamation-triangle"></i>
                    <p>${message}</p>
                </div>
            `;
        }
        
        // Modal dışına tıklayınca kapat
        window.onclick = function(event) {
            const modal = document.getElementById('tournamentModal');
            if (event.target === modal) {
                closeModal();
            }
        }
    </script>
</body>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</html>