<?php
session_start();
require_once 'inc/config.php';
require_once 'inc/functions.php';

// Check if user is logged in and has permission
if (!isset($_SESSION['user_id']) || !has_permission('events_manage')) {
    header('Location: login.php');
    exit();
}

// Get current date for filtering
$current_date = date('Y-m-d');
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-d', strtotime('-30 days'));
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d', strtotime('+30 days'));

// Get statistics
try {
    // Active seasonal events
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM seasonal_events WHERE status = 'active' AND start_date <= ? AND end_date >= ?");
    $stmt->execute([$current_date, $current_date]);
    $active_events = $stmt->fetch()['count'];

    // Total participants today
    $stmt = $pdo->prepare("SELECT COUNT(DISTINCT user_id) as count FROM tournament_participants tp 
                          JOIN tournaments t ON tp.tournament_id = t.id 
                          WHERE DATE(tp.joined_at) = ?");
    $stmt->execute([$current_date]);
    $daily_participants = $stmt->fetch()['count'];

    // Total bonus distributed today
    $stmt = $pdo->prepare("SELECT COALESCE(SUM(bonus_amount), 0) as total FROM user_bonus_history 
                          WHERE DATE(created_at) = ? AND bonus_type LIKE '%seasonal%'");
    $stmt->execute([$current_date]);
    $daily_bonus = $stmt->fetch()['total'];

    // Upcoming events
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM seasonal_events WHERE start_date > ?");
    $stmt->execute([$current_date]);
    $upcoming_events = $stmt->fetch()['count'];

    // Get seasonal events
    $stmt = $pdo->prepare("SELECT * FROM seasonal_events WHERE start_date BETWEEN ? AND ? ORDER BY start_date DESC");
    $stmt->execute([$start_date, $end_date]);
    $events = $stmt->fetchAll();

    // Get recent bonus history
    $stmt = $pdo->prepare("SELECT ubh.*, u.username FROM user_bonus_history ubh 
                          JOIN users u ON ubh.user_id = u.id 
                          WHERE ubh.bonus_type LIKE '%seasonal%' 
                          ORDER BY ubh.created_at DESC LIMIT 50");
    $stmt->execute();
    $recent_bonuses = $stmt->fetchAll();

} catch (PDOException $e) {
    error_log("Seasonal Events Error: " . $e->getMessage());
    $active_events = $daily_participants = $daily_bonus = $upcoming_events = 0;
    $events = $recent_bonuses = [];
}

include 'inc/header.php';
?>

<div class="container-fluid">
    <div class="row">
        <div class="col-md-2">
            <?php include 'sidebar.php'; ?>
        </div>
        <div class="col-md-10">
            <div class="main-content">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2><i class="fas fa-calendar-alt"></i> Mevsimsel Etkinlikler & Bayram Bonusları</h2>
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addEventModal">
                        <i class="fas fa-plus"></i> Yeni Etkinlik Ekle
                    </button>
                </div>

                <!-- Statistics Cards -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="card bg-success text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4><?php echo number_format($active_events); ?></h4>
                                        <p class="mb-0">Aktif Etkinlikler</p>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-calendar-check fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-info text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4><?php echo number_format($daily_participants); ?></h4>
                                        <p class="mb-0">Günlük Katılımcı</p>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-users fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-warning text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4>₺<?php echo number_format($daily_bonus, 2); ?></h4>
                                        <p class="mb-0">Günlük Bonus</p>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-gift fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-primary text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4><?php echo number_format($upcoming_events); ?></h4>
                                        <p class="mb-0">Yaklaşan Etkinlikler</p>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-clock fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Date Filter -->
                <div class="card mb-4">
                    <div class="card-body">
                        <form method="GET" class="row g-3">
                            <div class="col-md-4">
                                <label class="form-label">Başlangıç Tarihi</label>
                                <input type="date" class="form-control" name="start_date" value="<?php echo $start_date; ?>">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Bitiş Tarihi</label>
                                <input type="date" class="form-control" name="end_date" value="<?php echo $end_date; ?>">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">&nbsp;</label>
                                <button type="submit" class="btn btn-primary d-block">
                                    <i class="fas fa-filter"></i> Filtrele
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Tabs -->
                <ul class="nav nav-tabs" id="eventTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="events-tab" data-bs-toggle="tab" data-bs-target="#events" type="button">
                            <i class="fas fa-calendar-alt"></i> Mevsimsel Etkinlikler
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="bonuses-tab" data-bs-toggle="tab" data-bs-target="#bonuses" type="button">
                            <i class="fas fa-gift"></i> Bonus Geçmişi
                        </button>
                    </li>
                </ul>

                <div class="tab-content" id="eventTabsContent">
                    <!-- Seasonal Events Tab -->
                    <div class="tab-pane fade show active" id="events" role="tabpanel">
                        <div class="card">
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped" id="eventsTable">
                                        <thead>
                                            <tr>
                                                <th>ID</th>
                                                <th>Etkinlik Adı</th>
                                                <th>Tür</th>
                                                <th>Başlangıç</th>
                                                <th>Bitiş</th>
                                                <th>Bonus Miktarı</th>
                                                <th>Durum</th>
                                                <th>İşlemler</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($events as $event): ?>
                                            <tr>
                                                <td><?php echo $event['id']; ?></td>
                                                <td><?php echo htmlspecialchars($event['event_name']); ?></td>
                                                <td>
                                                    <span class="badge bg-info"><?php echo ucfirst($event['event_type']); ?></span>
                                                </td>
                                                <td><?php echo date('d.m.Y H:i', strtotime($event['start_date'])); ?></td>
                                                <td><?php echo date('d.m.Y H:i', strtotime($event['end_date'])); ?></td>
                                                <td>₺<?php echo number_format($event['bonus_amount'], 2); ?></td>
                                                <td>
                                                    <?php
                                                    $status_class = '';
                                                    switch($event['status']) {
                                                        case 'active': $status_class = 'bg-success'; break;
                                                        case 'inactive': $status_class = 'bg-secondary'; break;
                                                        case 'completed': $status_class = 'bg-primary'; break;
                                                        default: $status_class = 'bg-warning';
                                                    }
                                                    ?>
                                                    <span class="badge <?php echo $status_class; ?>">
                                                        <?php echo ucfirst($event['status']); ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <button class="btn btn-sm btn-warning" onclick="editEvent(<?php echo $event['id']; ?>)">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                    <button class="btn btn-sm btn-danger" onclick="deleteEvent(<?php echo $event['id']; ?>)">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Bonus History Tab -->
                    <div class="tab-pane fade" id="bonuses" role="tabpanel">
                        <div class="card">
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped" id="bonusesTable">
                                        <thead>
                                            <tr>
                                                <th>ID</th>
                                                <th>Kullanıcı</th>
                                                <th>Bonus Türü</th>
                                                <th>Miktar</th>
                                                <th>Açıklama</th>
                                                <th>Tarih</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($recent_bonuses as $bonus): ?>
                                            <tr>
                                                <td><?php echo $bonus['id']; ?></td>
                                                <td><?php echo htmlspecialchars($bonus['username']); ?></td>
                                                <td>
                                                    <span class="badge bg-success"><?php echo ucfirst($bonus['bonus_type']); ?></span>
                                                </td>
                                                <td>₺<?php echo number_format($bonus['bonus_amount'], 2); ?></td>
                                                <td><?php echo htmlspecialchars($bonus['description']); ?></td>
                                                <td><?php echo date('d.m.Y H:i', strtotime($bonus['created_at'])); ?></td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Event Modal -->
<div class="modal fade" id="addEventModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Yeni Mevsimsel Etkinlik Ekle</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="addEventForm">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Etkinlik Adı</label>
                                <input type="text" class="form-control" name="event_name" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Etkinlik Türü</label>
                                <select class="form-control" name="event_type" required>
                                    <option value="holiday">Bayram</option>
                                    <option value="seasonal">Mevsimsel</option>
                                    <option value="special">Özel Gün</option>
                                    <option value="weekend">Hafta Sonu</option>
                                </select>
                            </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>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Bonus Miktarı (₺)</label>
                                <input type="number" step="0.01" class="form-control" name="bonus_amount" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Durum</label>
                                <select class="form-control" name="status" required>
                                    <option value="active">Aktif</option>
                                    <option value="inactive">Pasif</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>
                </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="saveEvent()">Kaydet</button>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    $('#eventsTable').DataTable({
        "language": {
            "url": "//cdn.datatables.net/plug-ins/1.10.24/i18n/Turkish.json"
        },
        "order": [[ 0, "desc" ]]
    });
    
    $('#bonusesTable').DataTable({
        "language": {
            "url": "//cdn.datatables.net/plug-ins/1.10.24/i18n/Turkish.json"
        },
        "order": [[ 0, "desc" ]]
    });
});

function saveEvent() {
    const formData = new FormData(document.getElementById('addEventForm'));
    
    fetch('api/seasonal_events.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('Etkinlik başarıyla eklendi!');
            location.reload();
        } else {
            alert('Hata: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Bir hata oluştu!');
    });
}

function editEvent(id) {
    // Edit functionality can be implemented here
    alert('Düzenleme özelliği yakında eklenecek!');
}

function deleteEvent(id) {
    if (confirm('Bu etkinliği silmek istediğinizden emin misiniz?')) {
        fetch('api/seasonal_events.php', {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({id: id})
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Etkinlik başarıyla silindi!');
                location.reload();
            } else {
                alert('Hata: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Bir hata oluştu!');
        });
    }
}
</script>

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