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

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

$page_title = "Mini Oyunlar";

// Mini oyunlar
try {
    $stmt = $pdo->query("
        SELECT mg.*, 
               COUNT(mgr.id) as play_count,
               SUM(mgr.bet_amount) as total_bets,
               SUM(mgr.win_amount) as total_wins
        FROM mini_games mg
        LEFT JOIN mini_game_results mgr ON mg.id = mgr.game_id
        GROUP BY mg.id
        ORDER BY mg.created_at DESC
    ");
    $mini_games = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $mini_games = [];
}

// Piyango çekilişleri
try {
    $stmt = $pdo->query("
        SELECT ld.*, 
               COUNT(lt.id) as ticket_count,
               SUM(lt.ticket_price) as total_sales
        FROM lottery_draws ld
        LEFT JOIN lottery_tickets lt ON ld.id = lt.draw_id
        GROUP BY ld.id
        ORDER BY ld.draw_date DESC
        LIMIT 10
    ");
    $lottery_draws = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $lottery_draws = [];
}

// İstatistikler
try {
    $stats = [];
    
    // Toplam oyun sayısı
    $stmt = $pdo->query("SELECT COUNT(*) as total FROM mini_games WHERE is_active = 1");
    $stats['active_games'] = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Günlük oyun sayısı
    $stmt = $pdo->query("SELECT COUNT(*) as daily FROM mini_game_results WHERE DATE(created_at) = CURDATE()");
    $stats['daily_plays'] = $stmt->fetch(PDO::FETCH_ASSOC)['daily'];
    
    // Günlük kazanç
    $stmt = $pdo->query("SELECT SUM(bet_amount - win_amount) as profit FROM mini_game_results WHERE DATE(created_at) = CURDATE()");
    $stats['daily_profit'] = $stmt->fetch(PDO::FETCH_ASSOC)['profit'] ?? 0;
    
    // Aktif piyango biletleri
    $stmt = $pdo->query("SELECT COUNT(*) as tickets FROM lottery_tickets lt JOIN lottery_draws ld ON lt.draw_id = ld.id WHERE ld.status = 'active'");
    $stats['active_tickets'] = $stmt->fetch(PDO::FETCH_ASSOC)['tickets'];
    
} catch (Exception $e) {
    $stats = ['active_games' => 0, 'daily_plays' => 0, 'daily_profit' => 0, 'active_tickets' => 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>
        .game-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 20px;
            transition: transform 0.3s ease;
        }
        
        .game-card:hover {
            transform: translateY(-5px);
        }
        
        .game-card.wheel {
            background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
        }
        
        .game-card.lottery {
            background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
            color: #333;
        }
        
        .game-card.scratch {
            background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
            color: #333;
        }
        
        .mini-game-item {
            border: 2px solid #ddd;
            border-radius: 10px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            transition: all 0.3s ease;
            background: white;
        }
        
        .mini-game-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            border-color: #007bff;
        }
        
        .mini-game-item.active {
            border-color: #28a745;
            background: #f8fff8;
        }
        
        .mini-game-item.inactive {
            border-color: #dc3545;
            background: #fff8f8;
        }
        
        .game-icon {
            font-size: 3rem;
            margin-bottom: 1rem;
        }
        
        .game-stats {
            background: rgba(0,0,0,0.1);
            padding: 1rem;
            border-radius: 8px;
            margin-top: 1rem;
        }
        
        .lottery-card {
            border-left: 4px solid #ffc107;
            background: #f8f9fa;
            padding: 1rem;
            margin-bottom: 1rem;
            border-radius: 0 8px 8px 0;
        }
        
        .lottery-card.completed {
            border-left-color: #28a745;
        }
        
        .lottery-card.cancelled {
            border-left-color: #dc3545;
        }
        
        .wheel-section {
            width: 300px;
            height: 300px;
            border-radius: 50%;
            border: 10px solid #333;
            position: relative;
            margin: 2rem auto;
            background: conic-gradient(
                #ff6b6b 0deg 45deg,
                #4ecdc4 45deg 90deg,
                #45b7d1 90deg 135deg,
                #96ceb4 135deg 180deg,
                #ffeaa7 180deg 225deg,
                #dda0dd 225deg 270deg,
                #98d8c8 270deg 315deg,
                #f7dc6f 315deg 360deg
            );
        }
        
        .wheel-pointer {
            position: absolute;
            top: -20px;
            left: 50%;
            transform: translateX(-50%);
            width: 0;
            height: 0;
            border-left: 15px solid transparent;
            border-right: 15px solid transparent;
            border-top: 30px solid #333;
        }
        
        .scratch-card-demo {
            width: 200px;
            height: 150px;
            background: linear-gradient(45deg, #silver, #gold);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 1.2rem;
            color: #333;
            margin: 1rem auto;
            position: relative;
            overflow: hidden;
        }
        
        .scratch-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: #c0c0c0;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #666;
        }
    </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-gamepad"></i> <?php echo $page_title; ?></h1>
                    <div>
                        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#newGameModal">
                            <i class="fas fa-plus"></i> Yeni Oyun
                        </button>
                        <button class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#newLotteryModal">
                            <i class="fas fa-ticket-alt"></i> Yeni Piyango
                        </button>
                    </div>
                </div>

                <!-- İstatistik Kartları -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="game-card">
                            <h5><i class="fas fa-gamepad"></i> Aktif Oyunlar</h5>
                            <h2><?php echo number_format($stats['active_games']); ?></h2>
                            <small>Çalışan mini oyunlar</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="game-card wheel">
                            <h5><i class="fas fa-play"></i> Günlük Oyun</h5>
                            <h2><?php echo number_format($stats['daily_plays']); ?></h2>
                            <small>Bugün oynanan</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="game-card lottery">
                            <h5><i class="fas fa-coins"></i> Günlük Kazanç</h5>
                            <h2>₺<?php echo number_format($stats['daily_profit'], 2); ?></h2>
                            <small>Net kar</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="game-card scratch">
                            <h5><i class="fas fa-ticket-alt"></i> Aktif Biletler</h5>
                            <h2><?php echo number_format($stats['active_tickets']); ?></h2>
                            <small>Piyango biletleri</small>
                        </div>
                    </div>
                </div>

                <!-- Tabs -->
                <ul class="nav nav-tabs" id="gamesTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="mini-games-tab" data-bs-toggle="tab" data-bs-target="#mini-games" type="button" role="tab">
                            <i class="fas fa-gamepad"></i> Mini Oyunlar
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="wheel-tab" data-bs-toggle="tab" data-bs-target="#wheel" type="button" role="tab">
                            <i class="fas fa-dharmachakra"></i> Şans Çarkı
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="lottery-tab" data-bs-toggle="tab" data-bs-target="#lottery" type="button" role="tab">
                            <i class="fas fa-ticket-alt"></i> Piyango Sistemi
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="scratch-tab" data-bs-toggle="tab" data-bs-target="#scratch" type="button" role="tab">
                            <i class="fas fa-hand-paper"></i> Kazı Kazan
                        </button>
                    </li>
                </ul>

                <div class="tab-content" id="gamesTabsContent">
                    <!-- Mini Oyunlar -->
                    <div class="tab-pane fade show active" id="mini-games" role="tabpanel">
                        <div class="card mt-3">
                            <div class="card-header">
                                <h5><i class="fas fa-gamepad"></i> Mini Oyunlar</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <?php foreach ($mini_games as $game): ?>
                                    <div class="col-md-6 col-lg-4">
                                        <div class="mini-game-item <?php echo $game['is_active'] ? 'active' : 'inactive'; ?>">
                                            <div class="text-center">
                                                <div class="game-icon">
                                                    <?php
                                                    $icons = [
                                                        'dice' => 'fas fa-dice',
                                                        'coin_flip' => 'fas fa-coins',
                                                        'number_guess' => 'fas fa-hashtag',
                                                        'memory' => 'fas fa-brain',
                                                        'slot' => 'fas fa-sliders-h'
                                                    ];
                                                    echo '<i class="' . ($icons[$game['game_type']] ?? 'fas fa-gamepad') . '"></i>';
                                                    ?>
                                                </div>
                                                <h5><?php echo htmlspecialchars($game['game_name']); ?></h5>
                                                <p class="text-muted"><?php echo htmlspecialchars($game['description']); ?></p>
                                            </div>
                                            
                                            <div class="game-stats">
                                                <div class="row text-center">
                                                    <div class="col-4">
                                                        <strong><?php echo $game['play_count'] ?? 0; ?></strong>
                                                        <br><small>Oynanma</small>
                                                    </div>
                                                    <div class="col-4">
                                                        <strong>₺<?php echo number_format($game['total_bets'] ?? 0, 2); ?></strong>
                                                        <br><small>Bahis</small>
                                                    </div>
                                                    <div class="col-4">
                                                        <strong>₺<?php echo number_format($game['total_wins'] ?? 0, 2); ?></strong>
                                                        <br><small>Kazanç</small>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="text-center mt-3">
                                                <div class="btn-group btn-group-sm">
                                                    <button class="btn btn-outline-primary" onclick="viewGame(<?php echo $game['id']; ?>)">
                                                        <i class="fas fa-eye"></i>
                                                    </button>
                                                    <button class="btn btn-outline-warning" onclick="editGame(<?php echo $game['id']; ?>)">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                    <button class="btn btn-outline-<?php echo $game['is_active'] ? 'secondary' : 'success'; ?>" 
                                                            onclick="toggleGame(<?php echo $game['id']; ?>, <?php echo $game['is_active'] ? 'false' : 'true'; ?>)">
                                                        <i class="fas fa-<?php echo $game['is_active'] ? 'pause' : 'play'; ?>"></i>
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Şans Çarkı -->
                    <div class="tab-pane fade" id="wheel" role="tabpanel">
                        <div class="card mt-3">
                            <div class="card-header">
                                <h5><i class="fas fa-dharmachakra"></i> Şans Çarkı</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <h6>Çark Önizlemesi</h6>
                                        <div class="wheel-section">
                                            <div class="wheel-pointer"></div>
                                        </div>
                                        <div class="text-center">
                                            <button class="btn btn-primary btn-lg" onclick="spinWheel()">
                                                <i class="fas fa-play"></i> Çarkı Çevir
                                            </button>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <h6>Çark Ayarları</h6>
                                        <form id="wheelSettings">
                                            <div class="mb-3">
                                                <label class="form-label">Çevirme Maliyeti (₺)</label>
                                                <input type="number" class="form-control" name="spin_cost" value="10" step="0.01">
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label">Günlük Çevirme Limiti</label>
                                                <input type="number" class="form-control" name="daily_limit" value="5">
                                            </div>
                                            
                                            <h6>Ödül Dilimleri</h6>
                                            <div class="table-responsive">
                                                <table class="table table-sm">
                                                    <thead>
                                                        <tr>
                                                            <th>Dilim</th>
                                                            <th>Ödül</th>
                                                            <th>Şans (%)</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <tr>
                                                            <td>1</td>
                                                            <td>₺100</td>
                                                            <td>5</td>
                                                        </tr>
                                                        <tr>
                                                            <td>2</td>
                                                            <td>₺50</td>
                                                            <td>10</td>
                                                        </tr>
                                                        <tr>
                                                            <td>3</td>
                                                            <td>₺25</td>
                                                            <td>15</td>
                                                        </tr>
                                                        <tr>
                                                            <td>4</td>
                                                            <td>₺10</td>
                                                            <td>20</td>
                                                        </tr>
                                                        <tr>
                                                            <td>5</td>
                                                            <td>₺5</td>
                                                            <td>25</td>
                                                        </tr>
                                                        <tr>
                                                            <td>6</td>
                                                            <td>Free Spin</td>
                                                            <td>15</td>
                                                        </tr>
                                                        <tr>
                                                            <td>7</td>
                                                            <td>Bonus</td>
                                                            <td>8</td>
                                                        </tr>
                                                        <tr>
                                                            <td>8</td>
                                                            <td>Tekrar Dene</td>
                                                            <td>2</td>
                                                        </tr>
                                                    </tbody>
                                                </table>
                                            </div>
                                            
                                            <button type="button" class="btn btn-success" onclick="updateWheelSettings()">
                                                Ayarları Kaydet
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Piyango Sistemi -->
                    <div class="tab-pane fade" id="lottery" role="tabpanel">
                        <div class="card mt-3">
                            <div class="card-header">
                                <h5><i class="fas fa-ticket-alt"></i> Piyango Çekilişleri</h5>
                            </div>
                            <div class="card-body">
                                <?php foreach ($lottery_draws as $draw): ?>
                                <div class="lottery-card <?php echo strtolower($draw['status']); ?>">
                                    <div class="row">
                                        <div class="col-md-8">
                                            <h5><?php echo htmlspecialchars($draw['draw_name']); ?></h5>
                                            <p class="mb-2"><?php echo htmlspecialchars($draw['description']); ?></p>
                                            <div class="d-flex gap-3">
                                                <span class="badge bg-primary">
                                                    Bilet: ₺<?php echo number_format($draw['ticket_price'], 2); ?>
                                                </span>
                                                <span class="badge bg-success">
                                                    Ödül: ₺<?php echo number_format($draw['prize_amount'], 2); ?>
                                                </span>
                                                <span class="badge bg-info">
                                                    <?php echo $draw['ticket_count'] ?? 0; ?> Bilet Satıldı
                                                </span>
                                            </div>
                                        </div>
                                        <div class="col-md-4 text-end">
                                            <h6>Çekiliş: <?php echo date('d.m.Y H:i', strtotime($draw['draw_date'])); ?></h6>
                                            <small class="text-muted">
                                                Satış: ₺<?php echo number_format($draw['total_sales'] ?? 0, 2); ?>
                                            </small>
                                            <br>
                                            <span class="badge bg-<?php echo $draw['status'] == 'active' ? 'success' : ($draw['status'] == 'completed' ? 'primary' : 'secondary'); ?>">
                                                <?php echo strtoupper($draw['status']); ?>
                                            </span>
                                            <br>
                                            <div class="btn-group btn-group-sm mt-2">
                                                <button class="btn btn-outline-primary" onclick="viewLottery(<?php echo $draw['id']; ?>)">
                                                    <i class="fas fa-eye"></i>
                                                </button>
                                                <?php if ($draw['status'] == 'active'): ?>
                                                <button class="btn btn-outline-success" onclick="drawLottery(<?php echo $draw['id']; ?>)">
                                                    <i class="fas fa-random"></i> Çek
                                                </button>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Kazı Kazan -->
                    <div class="tab-pane fade" id="scratch" role="tabpanel">
                        <div class="card mt-3">
                            <div class="card-header">
                                <h5><i class="fas fa-hand-paper"></i> Kazı Kazan Kartları</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <h6>Kart Önizlemesi</h6>
                                        <div class="scratch-card-demo">
                                            <div class="scratch-overlay">
                                                <i class="fas fa-hand-paper"></i> Kazı
                                            </div>
                                            <div>₺50 KAZANDIN!</div>
                                        </div>
                                        <div class="text-center">
                                            <button class="btn btn-warning btn-lg" onclick="scratchCard()">
                                                <i class="fas fa-hand-paper"></i> Kartı Kazı
                                            </button>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <h6>Kazı Kazan Ayarları</h6>
                                        <form id="scratchSettings">
                                            <div class="mb-3">
                                                <label class="form-label">Kart Fiyatı (₺)</label>
                                                <input type="number" class="form-control" name="card_price" value="5" step="0.01">
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label">Günlük Kart Limiti</label>
                                                <input type="number" class="form-control" name="daily_limit" value="10">
                                            </div>
                                            
                                            <h6>Ödül Dağılımı</h6>
                                            <div class="table-responsive">
                                                <table class="table table-sm">
                                                    <thead>
                                                        <tr>
                                                            <th>Ödül</th>
                                                            <th>Şans (%)</th>
                                                            <th>Adet/Gün</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <tr>
                                                            <td>₺100</td>
                                                            <td>1</td>
                                                            <td>2</td>
                                                        </tr>
                                                        <tr>
                                                            <td>₺50</td>
                                                            <td>3</td>
                                                            <td>5</td>
                                                        </tr>
                                                        <tr>
                                                            <td>₺25</td>
                                                            <td>5</td>
                                                            <td>10</td>
                                                        </tr>
                                                        <tr>
                                                            <td>₺10</td>
                                                            <td>10</td>
                                                            <td>20</td>
                                                        </tr>
                                                        <tr>
                                                            <td>₺5</td>
                                                            <td>15</td>
                                                            <td>30</td>
                                                        </tr>
                                                        <tr>
                                                            <td>Kaybetti</td>
                                                            <td>66</td>
                                                            <td>-</td>
                                                        </tr>
                                                    </tbody>
                                                </table>
                                            </div>
                                            
                                            <button type="button" class="btn btn-success" onclick="updateScratchSettings()">
                                                Ayarları Kaydet
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </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>
        function viewGame(id) {
            alert('Oyun detayları: ' + id);
        }

        function editGame(id) {
            alert('Oyun düzenleme: ' + id);
        }

        function toggleGame(id, status) {
            alert('Oyun durumu değiştiriliyor: ' + id + ' -> ' + status);
        }

        function spinWheel() {
            alert('Şans çarkı çevriliyor...');
        }

        function updateWheelSettings() {
            alert('Çark ayarları güncelleniyor...');
        }

        function viewLottery(id) {
            alert('Piyango detayları: ' + id);
        }

        function drawLottery(id) {
            if (confirm('Bu piyangoyu çekmek istediğinizden emin misiniz?')) {
                alert('Piyango çekiliyor: ' + id);
            }
        }

        function scratchCard() {
            alert('Kazı kazan kartı kazınıyor...');
        }

        function updateScratchSettings() {
            alert('Kazı kazan ayarları güncelleniyor...');
        }
    </script>
</body>
</html>