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

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// Kullanıcı oturum kontrolü
function checkUserSession() {
    if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Oturum açmanız gerekiyor.']);
        exit();
    }
    
    global $conn;
    $username = $_SESSION['username'];
    $sql = "SELECT id FROM kullanicilar WHERE username = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();
    $stmt->close();
    
    return $user['id'];
}

// Referans kodu oluşturma
function generateReferralCode($userId) {
    return 'REF' . strtoupper(substr(md5($userId . time()), 0, 8));
}

// API endpoint'leri
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

try {
    switch ($method) {
        case 'GET':
            handleGetRequest($action);
            break;
        case 'POST':
            handlePostRequest($action);
            break;
        case 'PUT':
            handlePutRequest($action);
            break;
        default:
            http_response_code(405);
            echo json_encode(['success' => false, 'message' => 'Desteklenmeyen HTTP metodu.']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Sunucu hatası: ' . $e->getMessage()]);
}

function handleGetRequest($action) {
    global $conn;
    $userId = checkUserSession();
    
    switch ($action) {
        case 'my_code':
            // Kullanıcının referans kodunu getir
            $stmt = $conn->prepare("SELECT code, is_active, created_at FROM referral_codes WHERE user_id = ?");
            $stmt->bind_param("i", $userId);
            $stmt->execute();
            $result = $stmt->get_result();
            $code = $result->fetch_assoc();
            $stmt->close();
            
            if (!$code) {
                // Referans kodu yoksa oluştur
                $newCode = generateReferralCode($userId);
                $stmt = $conn->prepare("INSERT INTO referral_codes (user_id, code) VALUES (?, ?)");
                $stmt->bind_param("is", $userId, $newCode);
                $stmt->execute();
                $stmt->close();
                
                $code = [
                    'code' => $newCode,
                    'is_active' => 1,
                    'created_at' => date('Y-m-d H:i:s')
                ];
            }
            
            echo json_encode(['success' => true, 'data' => $code]);
            break;
            
        case 'statistics':
            // İstatistikleri getir
            $stmt = $conn->prepare("SELECT * FROM referral_statistics WHERE user_id = ?");
            $stmt->bind_param("i", $userId);
            $stmt->execute();
            $result = $stmt->get_result();
            $stats = $result->fetch_assoc();
            $stmt->close();
            
            if (!$stats) {
                // İstatistik kaydı yoksa oluştur
                $stmt = $conn->prepare("INSERT INTO referral_statistics (user_id) VALUES (?)");
                $stmt->bind_param("i", $userId);
                $stmt->execute();
                $stmt->close();
                
                $stats = [
                    'user_id' => $userId,
                    'total_referrals' => 0,
                    'active_referrals' => 0,
                    'total_commission' => 0.00,
                    'pending_commission' => 0.00,
                    'paid_commission' => 0.00
                ];
            }
            
            echo json_encode(['success' => true, 'data' => $stats]);
            break;
            
        case 'referrals':
            // Referans edilen kullanıcıları getir
            $page = intval($_GET['page'] ?? 1);
            $limit = 10;
            $offset = ($page - 1) * $limit;
            
            $stmt = $conn->prepare("
                SELECT rr.*, k.username, k.first_name, k.surname, rr.created_at as referral_date
                FROM referral_relationships rr 
                JOIN kullanicilar k ON rr.referred_id = k.id 
                WHERE rr.referrer_id = ? 
                ORDER BY rr.created_at DESC 
                LIMIT ? OFFSET ?
            ");
            $stmt->bind_param("iii", $userId, $limit, $offset);
            $stmt->execute();
            $result = $stmt->get_result();
            $referrals = $result->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            
            // Toplam sayı
            $countStmt = $conn->prepare("SELECT COUNT(*) as total FROM referral_relationships WHERE referrer_id = ?");
            $countStmt->bind_param("i", $userId);
            $countStmt->execute();
            $countResult = $countStmt->get_result();
            $total = $countResult->fetch_assoc()['total'];
            $countStmt->close();
            
            echo json_encode([
                'success' => true, 
                'data' => $referrals,
                'pagination' => [
                    'current_page' => $page,
                    'total_pages' => ceil($total / $limit),
                    'total_items' => $total
                ]
            ]);
            break;
            
        case 'commissions':
            // Komisyon geçmişini getir
            $page = intval($_GET['page'] ?? 1);
            $limit = 10;
            $offset = ($page - 1) * $limit;
            
            $stmt = $conn->prepare("
                SELECT rc.*, k.username 
                FROM referral_commissions rc 
                JOIN kullanicilar k ON rc.referred_id = k.id 
                WHERE rc.referrer_id = ? 
                ORDER BY rc.created_at DESC 
                LIMIT ? OFFSET ?
            ");
            $stmt->bind_param("iii", $userId, $limit, $offset);
            $stmt->execute();
            $result = $stmt->get_result();
            $commissions = $result->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            
            // Toplam sayı
            $countStmt = $conn->prepare("SELECT COUNT(*) as total FROM referral_commissions WHERE referrer_id = ?");
            $countStmt->bind_param("i", $userId);
            $countStmt->execute();
            $countResult = $countStmt->get_result();
            $total = $countResult->fetch_assoc()['total'];
            $countStmt->close();
            
            echo json_encode([
                'success' => true, 
                'data' => $commissions,
                'pagination' => [
                    'current_page' => $page,
                    'total_pages' => ceil($total / $limit),
                    'total_items' => $total
                ]
            ]);
            break;
            
        default:
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Geçersiz endpoint.']);
    }
}

function handlePostRequest($action) {
    global $conn;
    $userId = checkUserSession();
    $input = json_decode(file_get_contents('php://input'), true);
    
    switch ($action) {
        case 'use_code':
            $referralCode = $input['code'] ?? '';
            
            if (empty($referralCode)) {
                echo json_encode(['success' => false, 'message' => 'Referans kodu gerekli.']);
                return;
            }
            
            // Referans kodunu kontrol et
            $stmt = $conn->prepare("SELECT user_id FROM referral_codes WHERE code = ? AND is_active = 1");
            $stmt->bind_param("s", $referralCode);
            $stmt->execute();
            $result = $stmt->get_result();
            $referrer = $result->fetch_assoc();
            $stmt->close();
            
            if (!$referrer) {
                echo json_encode(['success' => false, 'message' => 'Geçersiz referans kodu.']);
                return;
            }
            
            if ($referrer['user_id'] == $userId) {
                echo json_encode(['success' => false, 'message' => 'Kendi referans kodunuzu kullanamazsınız.']);
                return;
            }
            
            // Referans ilişkisi oluştur
            $stmt = $conn->prepare("
                INSERT INTO referral_relationships (referrer_id, referred_id, referral_code, status) 
                VALUES (?, ?, ?, 'active')
            ");
            $stmt->bind_param("iis", $referrer['user_id'], $userId, $referralCode);
            
            if ($stmt->execute()) {
                $stmt->close();
                echo json_encode(['success' => true, 'message' => 'Referans kodu başarıyla kullanıldı.']);
            } else {
                $stmt->close();
                echo json_encode(['success' => false, 'message' => 'Referans kodu kullanılırken hata oluştu.']);
            }
            break;
            
        case 'withdraw':
            $amount = floatval($input['amount'] ?? 0);
            
            if ($amount <= 0) {
                echo json_encode(['success' => false, 'message' => 'Geçerli bir miktar giriniz.']);
                return;
            }
            
            // Bekleyen komisyon kontrolü
            $stmt = $conn->prepare("SELECT pending_commission FROM referral_statistics WHERE user_id = ?");
            $stmt->bind_param("i", $userId);
            $stmt->execute();
            $result = $stmt->get_result();
            $stats = $result->fetch_assoc();
            $stmt->close();
            
            if (!$stats || $stats['pending_commission'] < $amount) {
                echo json_encode(['success' => false, 'message' => 'Yetersiz komisyon bakiyesi.']);
                return;
            }
            
            // Komisyon çekme işlemi
            $conn->begin_transaction();
            
            try {
                // İstatistikleri güncelle
                $stmt = $conn->prepare("
                    UPDATE referral_statistics 
                    SET pending_commission = pending_commission - ?, 
                        paid_commission = paid_commission + ? 
                    WHERE user_id = ?
                ");
                $stmt->bind_param("ddi", $amount, $amount, $userId);
                $stmt->execute();
                $stmt->close();
                
                // Komisyon kaydını güncelle
                $stmt = $conn->prepare("
                    UPDATE referral_commissions 
                    SET status = 'paid', paid_at = NOW() 
                    WHERE referrer_id = ? AND status = 'pending' 
                    ORDER BY created_at ASC 
                    LIMIT 1
                ");
                $stmt->bind_param("i", $userId);
                $stmt->execute();
                $stmt->close();
                
                $conn->commit();
                echo json_encode(['success' => true, 'message' => 'Komisyon çekme talebi oluşturuldu.']);
                
            } catch (Exception $e) {
                $conn->rollback();
                echo json_encode(['success' => false, 'message' => 'İşlem sırasında hata oluştu.']);
            }
            break;
            
        default:
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Geçersiz endpoint.']);
    }
}

function handlePutRequest($action) {
    global $conn;
    $userId = checkUserSession();
    $input = json_decode(file_get_contents('php://input'), true);
    
    switch ($action) {
        case 'toggle_code':
            $isActive = $input['is_active'] ? 1 : 0;
            
            $stmt = $conn->prepare("UPDATE referral_codes SET is_active = ? WHERE user_id = ?");
            $stmt->bind_param("ii", $isActive, $userId);
            
            if ($stmt->execute()) {
                $stmt->close();
                echo json_encode(['success' => true, 'message' => 'Referans kodu durumu güncellendi.']);
            } else {
                $stmt->close();
                echo json_encode(['success' => false, 'message' => 'Güncelleme sırasında hata oluştu.']);
            }
            break;
            
        default:
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Geçersiz endpoint.']);
    }
}
?>