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

// 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;
        case 'DELETE':
            handleDeleteRequest($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 'limits':
            // Kullanıcının limitlerini getir
            $stmt = $conn->prepare("
                SELECT * FROM user_limits 
                WHERE user_id = ? AND is_active = 1 
                ORDER BY created_at DESC
            ");
            $stmt->bind_param("i", $userId);
            $stmt->execute();
            $result = $stmt->get_result();
            $limits = $result->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            
            echo json_encode(['success' => true, 'data' => $limits]);
            break;
            
        case 'limit_usage':
            // Limit kullanım geçmişi
            $page = intval($_GET['page'] ?? 1);
            $limit = 20;
            $offset = ($page - 1) * $limit;
            
            $stmt = $conn->prepare("
                SELECT lut.*, ul.limit_type, ul.limit_amount, ul.limit_duration
                FROM limit_usage_tracking lut
                JOIN user_limits ul ON lut.user_id = ul.user_id AND lut.limit_type = ul.limit_type
                WHERE ul.user_id = ?
                ORDER BY lut.last_updated DESC
                LIMIT ? OFFSET ?
            ");
            $stmt->bind_param("iii", $userId, $limit, $offset);
            $stmt->execute();
            $result = $stmt->get_result();
            $usage = $result->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            
            // Toplam sayı
            $countStmt = $conn->prepare("
                SELECT COUNT(*) as total 
                FROM limit_usage_tracking lut
                JOIN user_limits ul ON lut.user_id = ul.user_id AND lut.limit_type = ul.limit_type
                WHERE ul.user_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' => $usage,
                'pagination' => [
                    'current_page' => $page,
                    'total_pages' => ceil($total / $limit),
                    'total_items' => $total
                ]
            ]);
            break;
            
        case 'self_exclusions':
            // Kendini dışlama geçmişi
            $stmt = $conn->prepare("
                SELECT * FROM self_exclusions 
                WHERE user_id = ? 
                ORDER BY created_at DESC
            ");
            $stmt->bind_param("i", $userId);
            $stmt->execute();
            $result = $stmt->get_result();
            $exclusions = $result->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            
            echo json_encode(['success' => true, 'data' => $exclusions]);
            break;
            
        case 'gaming_sessions':
            // Oyun oturumları
            $page = intval($_GET['page'] ?? 1);
            $limit = 20;
            $offset = ($page - 1) * $limit;
            
            $stmt = $conn->prepare("
                SELECT * FROM gaming_sessions 
                WHERE user_id = ? 
                ORDER BY start_time DESC 
                LIMIT ? OFFSET ?
            ");
            $stmt->bind_param("iii", $userId, $limit, $offset);
            $stmt->execute();
            $result = $stmt->get_result();
            $sessions = $result->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            
            // Toplam sayı
            $countStmt = $conn->prepare("SELECT COUNT(*) as total FROM gaming_sessions WHERE user_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' => $sessions,
                'pagination' => [
                    'current_page' => $page,
                    'total_pages' => ceil($total / $limit),
                    'total_items' => $total
                ]
            ]);
            break;
            
        case 'alerts':
            // Sorumlu oyun uyarıları
            $stmt = $conn->prepare("
                SELECT * FROM responsible_gaming_alerts 
                WHERE user_id = ? 
                ORDER BY created_at DESC 
                LIMIT 50
            ");
            $stmt->bind_param("i", $userId);
            $stmt->execute();
            $result = $stmt->get_result();
            $alerts = $result->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            
            echo json_encode(['success' => true, 'data' => $alerts]);
            break;
            
        case 'statistics':
            // Oyun istatistikleri
            $period = $_GET['period'] ?? 'week'; // week, month, year
            
            $dateCondition = '';
            switch ($period) {
                case 'week':
                    $dateCondition = 'AND start_time >= DATE_SUB(NOW(), INTERVAL 1 WEEK)';
                    break;
                case 'month':
                    $dateCondition = 'AND start_time >= DATE_SUB(NOW(), INTERVAL 1 MONTH)';
                    break;
                case 'year':
                    $dateCondition = 'AND start_time >= DATE_SUB(NOW(), INTERVAL 1 YEAR)';
                    break;
            }
            
            $stmt = $conn->prepare("
                SELECT 
                    COUNT(*) as total_sessions,
                    SUM(TIMESTAMPDIFF(MINUTE, start_time, end_time)) as total_minutes,
                    AVG(TIMESTAMPDIFF(MINUTE, start_time, end_time)) as avg_session_minutes,
                    SUM(total_bet) as total_bet_amount,
                    SUM(total_win) as total_win_amount,
                    (SUM(total_bet) - SUM(total_win)) as net_loss
                FROM gaming_sessions 
                WHERE user_id = ? AND end_time IS NOT NULL $dateCondition
            ");
            $stmt->bind_param("i", $userId);
            $stmt->execute();
            $result = $stmt->get_result();
            $stats = $result->fetch_assoc();
            $stmt->close();
            
            echo json_encode(['success' => true, 'data' => $stats]);
            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 'set_limit':
            $limitType = $input['limit_type'] ?? '';
            $limitAmount = floatval($input['limit_amount'] ?? 0);
            $limitDuration = intval($input['limit_duration'] ?? 0);
            
            if (empty($limitType) || ($limitAmount <= 0 && $limitDuration <= 0)) {
                echo json_encode(['success' => false, 'message' => 'Geçerli limit bilgileri giriniz.']);
                return;
            }
            
            // Mevcut aktif limiti pasif yap
            $stmt = $conn->prepare("UPDATE user_limits SET is_active = 0 WHERE user_id = ? AND limit_type = ?");
            $stmt->bind_param("is", $userId, $limitType);
            $stmt->execute();
            $stmt->close();
            
            // Yeni limit ekle
            $stmt = $conn->prepare("
                INSERT INTO user_limits (user_id, limit_type, limit_amount, limit_duration) 
                VALUES (?, ?, ?, ?)
            ");
            $stmt->bind_param("isdi", $userId, $limitType, $limitAmount, $limitDuration);
            
            if ($stmt->execute()) {
                $stmt->close();
                echo json_encode(['success' => true, 'message' => 'Limit başarıyla ayarlandı.']);
            } else {
                $stmt->close();
                echo json_encode(['success' => false, 'message' => 'Limit ayarlanırken hata oluştu.']);
            }
            break;
            
        case 'self_exclude':
            $exclusionType = $input['exclusion_type'] ?? '';
            $duration = intval($input['duration'] ?? 0);
            $reason = $input['reason'] ?? '';
            
            if (empty($exclusionType) || $duration <= 0) {
                echo json_encode(['success' => false, 'message' => 'Geçerli dışlama bilgileri giriniz.']);
                return;
            }
            
            // Bitiş tarihini hesapla
            $endDate = date('Y-m-d H:i:s', strtotime("+$duration days"));
            
            $stmt = $conn->prepare("
                INSERT INTO self_exclusions (user_id, exclusion_type, start_date, end_date, reason, status) 
                VALUES (?, ?, NOW(), ?, ?, 'active')
            ");
            $stmt->bind_param("isss", $userId, $exclusionType, $endDate, $reason);
            
            if ($stmt->execute()) {
                $stmt->close();
                echo json_encode(['success' => true, 'message' => 'Kendini dışlama başarıyla ayarlandı.']);
            } else {
                $stmt->close();
                echo json_encode(['success' => false, 'message' => 'Dışlama ayarlanırken hata oluştu.']);
            }
            break;
            
        case 'start_session':
            // Oyun oturumu başlat
            $gameType = $input['game_type'] ?? '';
            
            if (empty($gameType)) {
                echo json_encode(['success' => false, 'message' => 'Oyun türü gerekli.']);
                return;
            }
            
            $stmt = $conn->prepare("
                INSERT INTO gaming_sessions (user_id, game_type, start_time) 
                VALUES (?, ?, NOW())
            ");
            $stmt->bind_param("is", $userId, $gameType);
            
            if ($stmt->execute()) {
                $sessionId = $conn->insert_id;
                $stmt->close();
                echo json_encode(['success' => true, 'session_id' => $sessionId]);
            } else {
                $stmt->close();
                echo json_encode(['success' => false, 'message' => 'Oturum başlatılırken 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 'end_session':
            $sessionId = intval($input['session_id'] ?? 0);
            $totalBet = floatval($input['total_bet'] ?? 0);
            $totalWin = floatval($input['total_win'] ?? 0);
            
            if ($sessionId <= 0) {
                echo json_encode(['success' => false, 'message' => 'Geçerli oturum ID gerekli.']);
                return;
            }
            
            $stmt = $conn->prepare("
                UPDATE gaming_sessions 
                SET end_time = NOW(), total_bet = ?, total_win = ? 
                WHERE id = ? AND user_id = ?
            ");
            $stmt->bind_param("ddii", $totalBet, $totalWin, $sessionId, $userId);
            
            if ($stmt->execute()) {
                $stmt->close();
                echo json_encode(['success' => true, 'message' => 'Oturum sonlandırıldı.']);
            } else {
                $stmt->close();
                echo json_encode(['success' => false, 'message' => 'Oturum sonlandırılırken hata oluştu.']);
            }
            break;
            
        case 'update_limit':
            $limitId = intval($input['limit_id'] ?? 0);
            $limitValue = floatval($input['limit_value'] ?? 0);
            
            if ($limitId <= 0 || $limitValue <= 0) {
                echo json_encode(['success' => false, 'message' => 'Geçerli limit bilgileri giriniz.']);
                return;
            }
            
            $stmt = $conn->prepare("
                UPDATE user_limits 
                SET limit_value = ?, updated_at = NOW() 
                WHERE id = ? AND user_id = ?
            ");
            $stmt->bind_param("dii", $limitValue, $limitId, $userId);
            
            if ($stmt->execute()) {
                $stmt->close();
                echo json_encode(['success' => true, 'message' => 'Limit güncellendi.']);
            } else {
                $stmt->close();
                echo json_encode(['success' => false, 'message' => 'Limit güncellenirken hata oluştu.']);
            }
            break;
            
        default:
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Geçersiz endpoint.']);
    }
}

function handleDeleteRequest($action) {
    global $conn;
    $userId = checkUserSession();
    $input = json_decode(file_get_contents('php://input'), true);
    
    switch ($action) {
        case 'remove_limit':
            $limitId = intval($input['limit_id'] ?? 0);
            
            if ($limitId <= 0) {
                echo json_encode(['success' => false, 'message' => 'Geçerli limit ID gerekli.']);
                return;
            }
            
            $stmt = $conn->prepare("
                UPDATE user_limits 
                SET is_active = 0 
                WHERE id = ? AND user_id = ?
            ");
            $stmt->bind_param("ii", $limitId, $userId);
            
            if ($stmt->execute()) {
                $stmt->close();
                echo json_encode(['success' => true, 'message' => 'Limit kaldırıldı.']);
            } else {
                $stmt->close();
                echo json_encode(['success' => false, 'message' => 'Limit kaldırılırken hata oluştu.']);
            }
            break;
            
        default:
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Geçersiz endpoint.']);
    }
}
?>