<?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;

// Kullanıcı bilgilerini al
$user_balance = 0;
$total_losses = 0;
if ($user_logged_in) {
    try {
        $stmt = $pdo->prepare("SELECT balance, total_loss FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
        $user_balance = $user_data['balance'] ?? 0;
        $total_losses = $user_data['total_loss'] ?? 0;
    } catch (Exception $e) {
        $user_balance = 0;
        $total_losses = 0;
    }
}

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

// Kullanıcının cashback geçmişini getir
$user_cashback_history = [];
$total_cashback_received = 0;
if ($user_logged_in) {
    try {
        $stmt = $pdo->prepare("
            SELECT ch.*, cp.name as program_name
            FROM cashback_history ch
            LEFT JOIN cashback_programs cp ON ch.program_id = cp.id
            WHERE ch.user_id = ?
            ORDER BY ch.created_at DESC
            LIMIT 50
        ");
        $stmt->execute([$user_id]);
        $user_cashback_history = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Toplam alınan cashback
        $stmt = $pdo->prepare("
            SELECT COALESCE(SUM(cashback_amount), 0) as total
            FROM cashback_history 
            WHERE user_id = ? AND status = 'completed'
        ");
        $stmt->execute([$user_id]);
        $total_cashback_received = $stmt->fetchColumn() ?: 0;
        
    } catch (Exception $e) {
        $user_cashback_history = [];
        $total_cashback_received = 0;
    }
}

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

<style>
body{background:#000 !important;color:#fff}
.cashback-card {
    background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
    border: 1px solid #0f3460;
    border-radius: 20px;
    padding: 30px;
    margin-bottom: 25px;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.cashback-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 15px 40px rgba(15, 52, 96, 0.4);
    border-color: #e94560;
}

.cashback-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(90deg, #27ae60, #2ecc71);
}

.program-badge {
    position: absolute;
    top: 20px;
    right: 20px;
    background: linear-gradient(45deg, #27ae60, #2ecc71);
    color: white;
    padding: 8px 16px;
    border-radius: 25px;
    font-size: 12px;
    font-weight: bold;
    text-transform: uppercase;
}

.cashback-percentage {
    background: linear-gradient(45deg, #27ae60, #2ecc71);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    font-size: 48px;
    font-weight: bold;
    text-align: center;
    margin: 20px 0;
}

.program-title {
    color: #27ae60;
    font-size: 28px;
    font-weight: bold;
    margin-bottom: 15px;
    text-align: center;
}

.program-description {
    color: #bdc3c7;
    margin-bottom: 20px;
    line-height: 1.6;
    text-align: center;
}

.requirements-box {
    background: rgba(255, 255, 255, 0.07);
    border-radius: 15px;
    padding: 20px;
    margin: 20px 0;
    border-left: 4px solid #27ae60;
}

.requirements-title {
    color: #27ae60;
    font-weight: bold;
    margin-bottom: 10px;
    font-size: 16px;
}

.requirement-item {
    color: #bdc3c7;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
}

.requirement-item i {
    color: #27ae60;
    margin-right: 10px;
    width: 16px;
}

.page-header {
    background: #000;
    padding: 50px 0;
    margin-bottom: 40px;
    text-align: center;
    position: relative;
    overflow: hidden;
}

.page-header::before {
    content: '💰💸🔄';
    position: absolute;
    top: 20px;
    right: 20px;
    font-size: 48px;
    opacity: 0.1;
}

.page-title {
    color: #27ae60;
    font-size: 42px;
    font-weight: bold;
    margin-bottom: 15px;
}

.page-subtitle {
    color: #bdc3c7;
    font-size: 20px;
}

.stats-row {
    margin-bottom: 40px;
}

.stat-card {
    background: #000;
    border-radius: 15px;
    padding: 25px;
    text-align: center;
    color: white;
    margin-bottom: 20px;
    border: 1px solid rgba(255,255,255,0.12);
    transition: all 0.3s ease;
}

.stat-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 10px 25px rgba(44, 62, 80, 0.3);
}

.stat-card.balance {
    background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
}

.stat-card.losses {
    background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
}

.stat-card.cashback {
    background: linear-gradient(135deg, #27ae60 0%, #2ecc71 100%);
}

.stat-amount {
    font-size: 32px;
    font-weight: bold;
    margin-bottom: 10px;
}

.stat-label {
    font-size: 16px;
    opacity: 0.9;
}

.nav-tabs .nav-link {
    background: transparent;
    border: 2px solid rgba(255,255,255,0.12);
    color: #bdc3c7;
    border-radius: 25px;
    margin-right: 10px;
    padding: 12px 30px;
    transition: all 0.3s ease;
}

.nav-tabs .nav-link.active {
    background: linear-gradient(45deg, #27ae60, #2ecc71);
    border-color: #27ae60;
    color: white;
}

.history-card {
    background: #000;
    border-radius: 15px;
    padding: 25px;
    margin-bottom: 20px;
    border-left: 4px solid #27ae60;
    transition: all 0.3s ease;
}

.history-card:hover {
    transform: translateX(5px);
    box-shadow: 0 5px 20px rgba(39, 174, 96, 0.2);
}

.history-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.history-program {
    color: #27ae60;
    font-weight: bold;
    font-size: 18px;
}

.history-date {
    color: #7f8c8d;
    font-size: 14px;
}

.history-details {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.history-loss {
    color: #e74c3c;
    font-size: 16px;
}

.history-cashback {
    color: #27ae60;
    font-size: 20px;
    font-weight: bold;
}

.status-badge {
    padding: 6px 15px;
    border-radius: 20px;
    font-weight: bold;
    font-size: 12px;
    text-transform: uppercase;
}

.status-completed {
    background: linear-gradient(45deg, #27ae60, #2ecc71);
    color: white;
}

.status-pending {
    background: linear-gradient(45deg, #f39c12, #e67e22);
    color: white;
}

.status-processing {
    background: linear-gradient(45deg, #3498db, #2980b9);
    color: white;
}

.eligible-indicator {
    background: linear-gradient(45deg, #27ae60, #2ecc71);
    color: white;
    padding: 10px 20px;
    border-radius: 25px;
    font-weight: bold;
    text-align: center;
    margin: 20px 0;
}

.not-eligible-indicator {
    background: linear-gradient(45deg, #e74c3c, #c0392b);
    color: white;
    padding: 10px 20px;
    border-radius: 25px;
    font-weight: bold;
    text-align: center;
    margin: 20px 0;
}

.claim-btn {
    background: linear-gradient(45deg, #27ae60, #2ecc71);
    border: none;
    color: white;
    padding: 15px 30px;
    border-radius: 25px;
    font-weight: bold;
    transition: all 0.3s ease;
    width: 100%;
}

.claim-btn:hover {
    transform: scale(1.05);
    box-shadow: 0 5px 15px rgba(39, 174, 96, 0.4);
}

.claim-btn:disabled {
    background: linear-gradient(45deg, #7f8c8d, #95a5a6);
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
}
</style>

<div class="page-header">
    <div class="container">
        <h1 class="page-title">💰 Cashback</h1>
        <p class="page-subtitle">Kayıplarınızın bir kısmını geri alın!</p>
    </div>
</div>

<div class="container">
    <?php if ($user_logged_in): ?>
        <div class="row stats-row">
            <div class="col-md-4">
                <div class="stat-card balance">
                    <div class="stat-amount"><?php echo number_format($user_balance, 2); ?> TL</div>
                    <div class="stat-label">Mevcut Bakiye</div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stat-card losses">
                    <div class="stat-amount"><?php echo number_format($total_losses, 2); ?> TL</div>
                    <div class="stat-label">Toplam Kayıp</div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stat-card cashback">
                    <div class="stat-amount"><?php echo number_format($total_cashback_received, 2); ?> TL</div>
                    <div class="stat-label">Alınan Cashback</div>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <ul class="nav nav-tabs mb-4" id="cashbackTabs" role="tablist">
        <li class="nav-item" role="presentation">
            <button class="nav-link active" id="programs-tab" data-bs-toggle="tab" data-bs-target="#programs" type="button" role="tab">
                Cashback Programları
            </button>
        </li>
        <?php if ($user_logged_in): ?>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="history-tab" data-bs-toggle="tab" data-bs-target="#history" type="button" role="tab">
                Cashback Geçmişim
            </button>
        </li>
        <?php endif; ?>
    </ul>

    <div class="tab-content" id="cashbackTabContent">
        <!-- Cashback Programları -->
        <div class="tab-pane fade show active" id="programs" role="tabpanel">
            <div class="row">
                <?php if (empty($cashback_programs)): ?>
                    <div class="col-12">
                        <div class="cashback-card text-center">
                            <h3 style="color: #bdc3c7;">Şu anda aktif cashback programı bulunmuyor</h3>
                            <p style="color: #7f8c8d;">Yeni programlar için takipte kalın!</p>
                        </div>
                    </div>
                <?php else: ?>
                    <?php foreach ($cashback_programs as $program): ?>
                        <div class="col-md-6 col-lg-4">
                            <div class="cashback-card">
                                <div class="program-badge">Aktif</div>
                                
                                <h3 class="program-title"><?php echo htmlspecialchars($program['name']); ?></h3>
                                
                                <div class="cashback-percentage">
                                    %<?php echo number_format($program['cashback_percentage'], 1); ?>
                                </div>
                                
                                <div class="program-description">
                                    <?php echo htmlspecialchars($program['description']); ?>
                                </div>
                                
                                <div class="requirements-box">
                                    <div class="requirements-title">Program Şartları:</div>
                                    
                                    <?php if ($program['min_loss'] > 0): ?>
                                        <div class="requirement-item">
                                            <i class="fas fa-arrow-down"></i>
                                            Minimum kayıp: <?php echo number_format($program['min_loss'], 2); ?> TL
                                        </div>
                                    <?php endif; ?>
                                    
                                    <?php if ($program['max_cashback'] > 0): ?>
                                        <div class="requirement-item">
                                            <i class="fas fa-arrow-up"></i>
                                            Maksimum cashback: <?php echo number_format($program['max_cashback'], 2); ?> TL
                                        </div>
                                    <?php endif; ?>
                                    
                                    <?php if ($program['valid_until']): ?>
                                        <div class="requirement-item">
                                            <i class="fas fa-calendar"></i>
                                            Son tarih: <?php echo date('d.m.Y', strtotime($program['valid_until'])); ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                
                                <?php if ($user_logged_in): ?>
                                    <?php 
                                    $is_eligible = $total_losses >= $program['min_loss'];
                                    ?>
                                    
                                    <?php if ($is_eligible): ?>
                                        <div class="eligible-indicator">
                                            <i class="fas fa-check-circle"></i> Bu program için uygunsunuz!
                                        </div>
                                        <button class="btn claim-btn" onclick="claimCashback(<?php echo $program['id']; ?>)">
                                            <i class="fas fa-money-bill-wave"></i> Cashback Talep Et
                                        </button>
                                    <?php else: ?>
                                        <div class="not-eligible-indicator">
                                            <i class="fas fa-times-circle"></i> 
                                            Daha <?php echo number_format($program['min_loss'] - $total_losses, 2); ?> TL kayıp gerekli
                                        </div>
                                        <button class="btn claim-btn" disabled>
                                            <i class="fas fa-lock"></i> Şartları Karşılamıyor
                                        </button>
                                    <?php endif; ?>
                                <?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>

        <!-- Cashback Geçmişi -->
        <?php if ($user_logged_in): ?>
        <div class="tab-pane fade" id="history" role="tabpanel">
            <?php if (empty($user_cashback_history)): ?>
                <div class="cashback-card text-center">
                    <h3 style="color: #bdc3c7;">Henüz cashback geçmişiniz bulunmuyor</h3>
                    <p style="color: #7f8c8d;">Yukarıdaki programlardan cashback talep ederek geçmişinizi oluşturun!</p>
                </div>
            <?php else: ?>
                <?php foreach ($user_cashback_history as $history): ?>
                    <div class="history-card">
                        <div class="history-header">
                            <div class="history-program">
                                <?php echo htmlspecialchars($history['program_name'] ?: 'Cashback'); ?>
                            </div>
                            <div class="history-date">
                                <?php echo date('d.m.Y H:i', strtotime($history['created_at'])); ?>
                            </div>
                        </div>
                        
                        <div class="history-details">
                            <div>
                                <div class="history-loss">
                                    <i class="fas fa-arrow-down"></i> 
                                    Kayıp: <?php echo number_format($history['loss_amount'], 2); ?> TL
                                </div>
                                <div style="color: #bdc3c7; font-size: 14px; margin-top: 5px;">
                                    %<?php echo number_format($history['cashback_percentage'], 1); ?> cashback
                                </div>
                            </div>
                            
                            <div class="text-end">
                                <div class="history-cashback">
                                    +<?php echo number_format($history['cashback_amount'], 2); ?> TL
                                </div>
                                <div style="margin-top: 5px;">
                                    <span class="status-badge status-<?php echo $history['status']; ?>">
                                        <?php 
                                        switch($history['status']) {
                                            case 'completed': echo 'Tamamlandı'; break;
                                            case 'pending': echo 'Beklemede'; break;
                                            case 'processing': echo 'İşleniyor'; break;
                                            default: echo ucfirst($history['status']);
                                        }
                                        ?>
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<script>
function claimCashback(programId) {
    <?php if (!$user_logged_in): ?>
        showLoginModal();
        return;
    <?php endif; ?>
    
    Swal.fire({
        title: 'Cashback Talep Et',
        text: 'Bu cashback programından faydalanmak istediğinizden emin misiniz?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#27ae60',
        cancelButtonColor: '#7f8c8d',
        confirmButtonText: 'Evet, Talep Et',
        cancelButtonText: 'İptal'
    }).then((result) => {
        if (result.isConfirmed) {
            fetch('api/cashback.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'claim',
                    program_id: programId
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire({
                        title: 'Başarılı!',
                        text: `${data.cashback_amount} TL cashback hesabınıza eklendi!`,
                        icon: 'success',
                        confirmButtonColor: '#27ae60'
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        title: 'Hata!',
                        text: data.message || 'Cashback talep edilirken bir hata oluştu.',
                        icon: 'error',
                        confirmButtonColor: '#e74c3c'
                    });
                }
            })
            .catch(error => {
                Swal.fire({
                    title: 'Hata!',
                    text: 'Bir hata oluştu. Lütfen tekrar deneyin.',
                    icon: 'error',
                    confirmButtonColor: '#e74c3c'
                });
            });
        }
    });
}

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'; ?>