<?php
session_start();
header('Content-Type: application/json');
include '../inc/database.php';

// Kullanıcı giriş kontrolü
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    echo json_encode(['success' => false, 'message' => 'Giriş yapmanız gerekiyor.']);
    exit;
}

$user_id = $_SESSION['user_id'];
$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? '';

try {
    switch ($action) {
        case 'claim':
            $program_id = $input['program_id'] ?? 0;
            
            if (!$program_id) {
                echo json_encode(['success' => false, 'message' => 'Program ID gerekli.']);
                exit;
            }
            
            // Program bilgilerini al
            $stmt = $pdo->prepare("
                SELECT * FROM cashback_programs 
                WHERE id = ? AND status = 'active' 
                AND (valid_until IS NULL OR valid_until > NOW())
            ");
            $stmt->execute([$program_id]);
            $program = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$program) {
                echo json_encode(['success' => false, 'message' => 'Program bulunamadı veya aktif değil.']);
                exit;
            }
            
            // Kullanıcının toplam kaybını al
            $stmt = $pdo->prepare("SELECT total_loss, balance FROM users WHERE id = ?");
            $stmt->execute([$user_id]);
            $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
            $total_loss = $user_data['total_loss'] ?? 0;
            $current_balance = $user_data['balance'] ?? 0;
            
            // Minimum kayıp kontrolü
            if ($total_loss < $program['min_loss']) {
                echo json_encode([
                    'success' => false, 
                    'message' => 'Minimum kayıp şartını karşılamıyorsunuz. Gerekli: ' . number_format($program['min_loss'], 2) . ' TL'
                ]);
                exit;
            }
            
            // Bu programdan daha önce cashback alınmış mı kontrol et
            $stmt = $pdo->prepare("
                SELECT COUNT(*) FROM cashback_history 
                WHERE user_id = ? AND program_id = ? AND status IN ('completed', 'processing')
            ");
            $stmt->execute([$user_id, $program_id]);
            $already_claimed = $stmt->fetchColumn();
            
            if ($already_claimed > 0) {
                echo json_encode(['success' => false, 'message' => 'Bu programdan zaten cashback aldınız.']);
                exit;
            }
            
            // Cashback miktarını hesapla
            $cashback_amount = ($total_loss * $program['cashback_percentage']) / 100;
            
            // Maksimum cashback kontrolü
            if ($program['max_cashback'] > 0 && $cashback_amount > $program['max_cashback']) {
                $cashback_amount = $program['max_cashback'];
            }
            
            // Transaction başlat
            $pdo->beginTransaction();
            
            try {
                // Cashback geçmişine ekle
                $stmt = $pdo->prepare("
                    INSERT INTO cashback_history 
                    (user_id, program_id, loss_amount, cashback_percentage, cashback_amount, status, created_at) 
                    VALUES (?, ?, ?, ?, ?, 'completed', NOW())
                ");
                $stmt->execute([
                    $user_id, 
                    $program_id, 
                    $total_loss, 
                    $program['cashback_percentage'], 
                    $cashback_amount
                ]);
                
                // Kullanıcının bakiyesini güncelle
                $stmt = $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
                $stmt->execute([$cashback_amount, $user_id]);
                
                // Transaction'ı tamamla
                $pdo->commit();
                
                echo json_encode([
                    'success' => true, 
                    'message' => 'Cashback başarıyla hesabınıza eklendi!',
                    'cashback_amount' => number_format($cashback_amount, 2),
                    'new_balance' => number_format($current_balance + $cashback_amount, 2)
                ]);
                
            } catch (Exception $e) {
                $pdo->rollBack();
                echo json_encode(['success' => false, 'message' => 'Cashback işlemi sırasında hata oluştu.']);
            }
            break;
            
        case 'history':
            // Kullanıcının cashback geçmişini getir
            $page = $input['page'] ?? 1;
            $limit = 20;
            $offset = ($page - 1) * $limit;
            
            $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 ? OFFSET ?
            ");
            $stmt->execute([$user_id, $limit, $offset]);
            $history = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            // Toplam kayıt sayısı
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM cashback_history WHERE user_id = ?");
            $stmt->execute([$user_id]);
            $total_records = $stmt->fetchColumn();
            
            // 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 = $stmt->fetchColumn();
            
            echo json_encode([
                'success' => true,
                'history' => $history,
                'total_records' => $total_records,
                'total_pages' => ceil($total_records / $limit),
                'current_page' => $page,
                'total_cashback' => $total_cashback
            ]);
            break;
            
        case 'stats':
            // Kullanıcının cashback istatistiklerini getir
            $stmt = $pdo->prepare("
                SELECT 
                    COUNT(*) as total_claims,
                    COALESCE(SUM(cashback_amount), 0) as total_cashback,
                    COALESCE(AVG(cashback_amount), 0) as avg_cashback,
                    MAX(cashback_amount) as max_cashback
                FROM cashback_history 
                WHERE user_id = ? AND status = 'completed'
            ");
            $stmt->execute([$user_id]);
            $stats = $stmt->fetch(PDO::FETCH_ASSOC);
            
            // Bu ayki cashback
            $stmt = $pdo->prepare("
                SELECT COALESCE(SUM(cashback_amount), 0) as monthly_cashback
                FROM cashback_history 
                WHERE user_id = ? AND status = 'completed'
                AND MONTH(created_at) = MONTH(NOW()) 
                AND YEAR(created_at) = YEAR(NOW())
            ");
            $stmt->execute([$user_id]);
            $monthly_cashback = $stmt->fetchColumn();
            
            $stats['monthly_cashback'] = $monthly_cashback;
            
            echo json_encode([
                'success' => true,
                'stats' => $stats
            ]);
            break;
            
        case 'eligible_programs':
            // Kullanıcının uygun olduğu programları getir
            $stmt = $pdo->prepare("SELECT total_loss FROM users WHERE id = ?");
            $stmt->execute([$user_id]);
            $total_loss = $stmt->fetchColumn() ?: 0;
            
            $stmt = $pdo->query("
                SELECT cp.*, 
                       CASE WHEN ch.id IS NOT NULL THEN 1 ELSE 0 END as already_claimed
                FROM cashback_programs cp
                LEFT JOIN cashback_history ch ON cp.id = ch.program_id AND ch.user_id = ? AND ch.status IN ('completed', 'processing')
                WHERE cp.status = 'active' 
                AND (cp.valid_until IS NULL OR cp.valid_until > NOW())
                AND cp.min_loss <= ?
                ORDER BY cp.cashback_percentage DESC
            ");
            $stmt->execute([$user_id, $total_loss]);
            $eligible_programs = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'programs' => $eligible_programs,
                'user_total_loss' => $total_loss
            ]);
            break;
            
        default:
            echo json_encode(['success' => false, 'message' => 'Geçersiz işlem.']);
            break;
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Bir hata oluştu: ' . $e->getMessage()]);
}
?>