<?php
session_start();
include './inc/head.php';
include './inc/database.php';

// Kullanıcı giriş kontrolü
$user_logged_in = isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true;
$user_id = $user_logged_in ? $_SESSION['user_id'] : null;

// Aktif bonusları getir
try {
    $stmt = $pdo->query("
        SELECT * FROM dynamic_bonuses 
        WHERE status = 'active' 
        AND (valid_until IS NULL OR valid_until > NOW())
        ORDER BY bonus_amount DESC
    ");
    $bonuses = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $bonuses = [];
}

// Kullanıcının bonus geçmişini getir
$user_bonus_history = [];
if ($user_logged_in) {
    try {
        $stmt = $pdo->prepare("
            SELECT ubh.*, db.name as bonus_name, db.bonus_type
            FROM user_bonus_history ubh
            LEFT JOIN dynamic_bonuses db ON ubh.bonus_id = db.id
            WHERE ubh.user_id = ?
            ORDER BY ubh.created_at DESC
            LIMIT 20
        ");
        $stmt->execute([$user_id]);
        $user_bonus_history = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        $user_bonus_history = [];
    }
}

// Mevsimsel etkinlikleri getir
try {
    $stmt = $pdo->query("
        SELECT * FROM seasonal_events 
        WHERE status = 'active' 
        AND start_date <= NOW() 
        AND end_date >= NOW()
        ORDER BY bonus_amount DESC
    ");
    $seasonal_events = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $seasonal_events = [];
}

include './inc/header.php';
?>

<style>
.page-header { padding: 24px 0; margin-bottom: 20px; text-align: center; }
.page-title { color: #e6e9ef; font-size: 24px; font-weight: 800; margin-bottom: 6px; }
.page-subtitle { color: #9aa4b2; font-size: 13px; }
.nav-tabs .nav-link { background: transparent; border: 1px solid rgba(255,255,255,.12); color: #e6e9ef; border-radius: 12px; margin-right: 8px; padding: 8px 14px; font-size: 12px; font-weight: 700; }
.nav-tabs .nav-link.active { background: var(--primary); border-color: var(--primary); color: var(--btntText); }
.bonus-card { background: rgba(255,255,255,.03); border: 1px solid rgba(255,255,255,.12); border-radius: 12px; padding: 18px; margin-bottom: 16px; transition: transform .2s ease, box-shadow .2s ease; }
.bonus-card:hover { transform: translateY(-2px); box-shadow: 0 6px 18px rgba(0,0,0,.25); }
.bonus-type-badge { position: absolute; top: 12px; right: 12px; padding: 4px 10px; border-radius: 16px; font-size: 11px; font-weight: 700; text-transform: uppercase; background: var(--primary); color: var(--btntText); }
.bonus-title { color: #e6e9ef; font-size: 18px; font-weight: 800; margin-bottom: 8px; }
.bonus-amount { color: #f39c12; font-size: 26px; font-weight: 800; text-align: center; margin: 10px 0; }
.bonus-description { color: #9aa4b2; margin-bottom: 12px; line-height: 1.6; font-size: 13px; }
.requirements-list { background: rgba(255,255,255,.03); border: 1px solid rgba(255,255,255,.08); border-radius: 10px; padding: 12px; margin: 12px 0; }
.requirements-list strong { color: #f39c12; }
.requirements-list ul { margin: 0; padding-left: 18px; color: #9aa4b2; }
.requirements-list li { margin-bottom: 6px; }
.claim-btn { background: var(--primary); border: none; color: var(--btntText); padding: 10px 16px; border-radius: 10px; font-weight: 700; transition: all .2s ease; width: 100%; }
.claim-btn:hover { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(0,0,0,.3); }
.claimed-btn { background: #2ecc71; color: #fff; cursor: default; }
.bonus-history-card { background: rgba(255,255,255,.03); border-radius: 10px; padding: 16px; margin-bottom: 12px; border-left: 4px solid var(--primary); }
.status-badge { padding: 5px 12px; border-radius: 16px; font-weight: 700; font-size: 11px; text-transform: uppercase; }
.status-completed { background: #2ecc71; color: #fff; }
.status-pending { background: #f39c12; color: #000; }
.status-expired { background: #e74c3c; color: #fff; }
.seasonal-event-card { background: rgba(255,255,255,.03); border: 1px solid rgba(255,255,255,.12); border-radius: 12px; padding: 18px; margin-bottom: 16px; color: #e6e9ef; }
</style>

<div class="page-header">
    <div class="container">
        <h1 class="page-title">Bonuslar</h1>
        <p class="page-subtitle">Aktif bonuslar, özel etkinlikler ve geçmişiniz.</p>
    </div>
</div>

<div class="container">
    <ul class="nav nav-tabs mb-4" id="bonusTabs" role="tablist">
        <li class="nav-item" role="presentation">
            <button class="nav-link active" id="active-bonuses-tab" data-bs-toggle="tab" data-bs-target="#active-bonuses" type="button" role="tab">
                Aktif Bonuslar
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="seasonal-events-tab" data-bs-toggle="tab" data-bs-target="#seasonal-events" type="button" role="tab">
                Özel Etkinlikler
            </button>
        </li>
        <?php if ($user_logged_in): ?>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="bonus-history-tab" data-bs-toggle="tab" data-bs-target="#bonus-history" type="button" role="tab">
                Bonus Geçmişim
            </button>
        </li>
        <?php endif; ?>
    </ul>

    <div class="tab-content" id="bonusTabContent">
        <!-- Aktif Bonuslar -->
        <div class="tab-pane fade show active" id="active-bonuses" role="tabpanel">
            <div class="row">
                <?php if (empty($bonuses)): ?>
                    <div class="col-12">
                        <div class="bonus-card text-center">
                            <h3 style="color: #bdc3c7;">Şu anda aktif bonus bulunmuyor</h3>
                            <p style="color: #7f8c8d;">Yeni bonuslar için takipte kalın!</p>
                        </div>
                    </div>
                <?php else: ?>
                    <?php foreach ($bonuses as $bonus): ?>
                        <div class="col-md-6 col-lg-4">
                            <div class="bonus-card">
                                <div class="bonus-type-badge">
                                    <?php echo ucfirst($bonus['bonus_type']); ?>
                                </div>
                                
                                <h3 class="bonus-title"><?php echo htmlspecialchars($bonus['name']); ?></h3>
                                
                                <div class="bonus-amount">
                                    <?php if ($bonus['bonus_type'] == 'percentage'): ?>
                                        %<?php echo number_format($bonus['bonus_amount'], 0); ?>
                                    <?php else: ?>
                                        <?php echo number_format($bonus['bonus_amount'], 2); ?> TL
                                    <?php endif; ?>
                                </div>
                                
                                <div class="bonus-description">
                                    <?php echo htmlspecialchars($bonus['description']); ?>
                                </div>
                                
                                <?php if (!empty($bonus['requirements'])): ?>
                                    <div class="requirements-list">
                                        <strong style="color: #f39c12;">Şartlar:</strong>
                                        <ul>
                                            <?php 
                                            $requirements = explode(',', $bonus['requirements']);
                                            foreach ($requirements as $req): 
                                            ?>
                                                <li><?php echo htmlspecialchars(trim($req)); ?></li>
                                            <?php endforeach; ?>
                                        </ul>
                                    </div>
                                <?php endif; ?>
                                
                                <?php if ($bonus['valid_until']): ?>
                                    <p style="color: #f39c12; font-size: 14px; text-align: center;">
                                        <i class="fas fa-clock"></i> 
                                        Son tarih: <?php echo date('d.m.Y H:i', strtotime($bonus['valid_until'])); ?>
                                    </p>
                                <?php endif; ?>
                                
                                <?php if ($user_logged_in): ?>
                                    <button class="btn claim-btn" onclick="claimBonus(<?php echo $bonus['id']; ?>)">
                                        <i class="fas fa-gift"></i> Bonusu Al
                                    </button>
                                <?php else: ?>
                                    <button class="btn claim-btn" onclick="showLoginModal()">
                                        <i class="fas fa-sign-in-alt"></i> Giriş Yapın
                                    </button>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>

        <!-- Mevsimsel Etkinlikler -->
        <div class="tab-pane fade" id="seasonal-events" role="tabpanel">
            <div class="row">
                <?php if (empty($seasonal_events)): ?>
                    <div class="col-12">
                        <div class="bonus-card text-center">
                            <h3 style="color: #bdc3c7;">Şu anda aktif özel etkinlik bulunmuyor</h3>
                            <p style="color: #7f8c8d;">Özel günler ve etkinlikler için takipte kalın!</p>
                        </div>
                    </div>
                <?php else: ?>
                    <?php foreach ($seasonal_events as $event): ?>
                        <div class="col-md-6">
                            <div class="seasonal-event-card">
                                <h3 style="margin-bottom: 15px;"><?php echo htmlspecialchars($event['name']); ?></h3>
                                
                                <div style="font-size: 28px; font-weight: bold; text-align: center; margin: 15px 0;">
                                    💰 <?php echo number_format($event['bonus_amount'], 2); ?> TL
                                </div>
                                
                                <p style="margin-bottom: 15px; line-height: 1.6;">
                                    <?php echo htmlspecialchars($event['description']); ?>
                                </p>
                                
                                <div style="background: rgba(0,0,0,0.2); border-radius: 10px; padding: 15px; margin: 15px 0;">
                                    <p style="margin: 0; font-size: 14px;">
                                        <i class="fas fa-calendar"></i> 
                                        <?php echo date('d.m.Y', strtotime($event['start_date'])); ?> - 
                                        <?php echo date('d.m.Y', strtotime($event['end_date'])); ?>
                                    </p>
                                </div>
                                
                                <?php if ($user_logged_in): ?>
                                    <button class="btn claim-btn" onclick="claimSeasonalBonus(<?php echo $event['id']; ?>)">
                                        <i class="fas fa-star"></i> Etkinlik Bonusunu Al
                                    </button>
                                <?php else: ?>
                                    <button class="btn claim-btn" onclick="showLoginModal()">
                                        <i class="fas fa-sign-in-alt"></i> Giriş Yapın
                                    </button>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>

        <!-- Bonus Geçmişi -->
        <?php if ($user_logged_in): ?>
        <div class="tab-pane fade" id="bonus-history" role="tabpanel">
            <?php if (empty($user_bonus_history)): ?>
                <div class="bonus-card text-center">
                    <h3 style="color: #bdc3c7;">Henüz bonus geçmişiniz bulunmuyor</h3>
                    <p style="color: #7f8c8d;">Yukarıdaki bonusları alarak geçmişinizi oluşturun!</p>
                </div>
            <?php else: ?>
                <?php foreach ($user_bonus_history as $history): ?>
                    <div class="bonus-history-card">
                        <div class="row align-items-center">
                            <div class="col-md-6">
                                <h4 style="color: #e94560; margin-bottom: 5px;">
                                    <?php echo htmlspecialchars($history['bonus_name'] ?: 'Bonus'); ?>
                                </h4>
                                <p style="color: #bdc3c7; margin-bottom: 0; font-size: 14px;">
                                    <?php echo date('d.m.Y H:i', strtotime($history['created_at'])); ?>
                                </p>
                            </div>
                            <div class="col-md-3 text-center">
                                <div style="color: #f39c12; font-size: 20px; font-weight: bold;">
                                    <?php echo number_format($history['bonus_amount'], 2); ?> TL
                                </div>
                            </div>
                            <div class="col-md-3 text-center">
                                <span class="status-badge status-<?php echo $history['status']; ?>">
                                    <?php 
                                    switch($history['status']) {
                                        case 'completed': echo 'Tamamlandı'; break;
                                        case 'pending': echo 'Beklemede'; break;
                                        case 'expired': echo 'Süresi Doldu'; break;
                                        default: echo ucfirst($history['status']);
                                    }
                                    ?>
                                </span>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<script>
function claimBonus(bonusId) {
    <?php if (!$user_logged_in): ?>
        showLoginModal();
        return;
    <?php endif; ?>
    
    Swal.fire({
        title: 'Bonusu Al',
        text: 'Bu bonusu almak istediğinizden emin misiniz?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#e94560',
        cancelButtonColor: '#7f8c8d',
        confirmButtonText: 'Evet, Al',
        cancelButtonText: 'İptal'
    }).then((result) => {
        if (result.isConfirmed) {
            fetch('api/bonuses.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'claim',
                    bonus_id: bonusId
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire({
                        title: 'Başarılı!',
                        text: 'Bonus başarıyla hesabınıza eklendi!',
                        icon: 'success',
                        confirmButtonColor: '#e94560'
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        title: 'Hata!',
                        text: data.message || 'Bonus alınırken bir hata oluştu.',
                        icon: 'error',
                        confirmButtonColor: '#e94560'
                    });
                }
            })
            .catch(error => {
                Swal.fire({
                    title: 'Hata!',
                    text: 'Bir hata oluştu. Lütfen tekrar deneyin.',
                    icon: 'error',
                    confirmButtonColor: '#e94560'
                });
            });
        }
    });
}

function claimSeasonalBonus(eventId) {
    <?php if (!$user_logged_in): ?>
        showLoginModal();
        return;
    <?php endif; ?>
    
    Swal.fire({
        title: 'Etkinlik Bonusunu Al',
        text: 'Bu etkinlik bonusunu almak istediğinizden emin misiniz?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#e94560',
        cancelButtonColor: '#7f8c8d',
        confirmButtonText: 'Evet, Al',
        cancelButtonText: 'İptal'
    }).then((result) => {
        if (result.isConfirmed) {
            fetch('api/bonuses.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'claim_seasonal',
                    event_id: eventId
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire({
                        title: 'Başarılı!',
                        text: 'Etkinlik bonusu başarıyla hesabınıza eklendi!',
                        icon: 'success',
                        confirmButtonColor: '#e94560'
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        title: 'Hata!',
                        text: data.message || 'Bonus alınırken bir hata oluştu.',
                        icon: 'error',
                        confirmButtonColor: '#e94560'
                    });
                }
            })
            .catch(error => {
                Swal.fire({
                    title: 'Hata!',
                    text: 'Bir hata oluştu. Lütfen tekrar deneyin.',
                    icon: 'error',
                    confirmButtonColor: '#e94560'
                });
            });
        }
    });
}

function showLoginModal() {
    // Login modalını aç
    try {
        $('#login2').modal('show');
    } catch(e) {
        var modal = document.getElementById('login2');
        if (modal) {
            modal.classList.add('show');
            modal.style.display = 'block';
        }
    }
}
</script>

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