<?php
session_start();
require_once __DIR__ . '/../config.php';
// functions.php dosyası yok, bu satırı kaldırıyoruz
// require_once '../inc/functions.php';

// MySQLi bağlantısı oluştur (API dosyaları için)
$conn = new mysqli('localhost', 'blacrhdy_bet1', 'blacrhdy_bet1', 'blacrhdy_bet1');
if ($conn->connect_error) {
    die(json_encode(['success' => false, 'message' => 'Veritabanı bağlantı hatası']));
}
$conn->set_charset("utf8mb4");

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

// Oturum kontrolü - hem kullanıcı hem admin için
$is_admin_request = isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true;
$is_user_request = isset($_SESSION['user_id']);

// Debug için
error_log("Session debug: admin_logged_in = " . (isset($_SESSION['admin_logged_in']) ? $_SESSION['admin_logged_in'] : 'not set'));
error_log("Session debug: user_id = " . (isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 'not set'));

if (!$is_admin_request && !$is_user_request) {
    echo json_encode(['success' => false, 'message' => 'Oturum gerekli', 'debug' => [
        'admin_logged_in' => isset($_SESSION['admin_logged_in']) ? $_SESSION['admin_logged_in'] : 'not set',
        'user_id' => isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 'not set'
    ]]);
    exit;
}

$user_id = $is_admin_request ? ($_SESSION['admin_user_id'] ?? 0) : $_SESSION['user_id'];
$action = $_GET['action'] ?? $_POST['action'] ?? '';

try {
    switch ($action) {
        // Kullanıcı fonksiyonları
        case 'get_my_sessions':
            echo json_encode(getMyActiveSessions($user_id));
            break;
            
        case 'terminate_my_session':
            $session_id = $_POST['session_id'] ?? '';
            echo json_encode(terminateMySession($user_id, $session_id));
            break;
            
        case 'get_my_session_activity':
            $limit = $_GET['limit'] ?? 50;
            echo json_encode(getMySessionActivity($user_id, $limit));
            break;
            
        // Admin fonksiyonları
        case 'get_all_sessions':
            if (!$is_admin_request) {
                echo json_encode(['success' => false, 'message' => 'Yetki gerekli']);
                exit;
            }
            $page = $_GET['page'] ?? 1;
            $limit = $_GET['limit'] ?? 20;
            $filter = $_GET['filter'] ?? 'all';
            echo json_encode(getAllActiveSessions($page, $limit, $filter));
            break;
            
        case 'terminate_session':
            if (!$is_admin_request) {
                echo json_encode(['success' => false, 'message' => 'Yetki gerekli']);
                exit;
            }
            $session_id = $_POST['session_id'] ?? '';
            $reason = $_POST['reason'] ?? '';
            echo json_encode(terminateSession($session_id, $user_id, $reason));
            break;
            
        case 'get_session_details':
            if (!$is_admin_request) {
                echo json_encode(['success' => false, 'message' => 'Yetki gerekli']);
                exit;
            }
            $session_id = $_GET['session_id'] ?? '';
            echo json_encode(getSessionDetails($session_id));
            break;
            
        case 'get_suspicious_sessions':
            if (!$is_admin_request) {
                echo json_encode(['success' => false, 'message' => 'Yetki gerekli']);
                exit;
            }
            $page = $_GET['page'] ?? 1;
            $limit = $_GET['limit'] ?? 20;
            echo json_encode(getSuspiciousSessions($page, $limit));
            break;
            
        case 'review_suspicious_session':
            if (!$is_admin_request) {
                echo json_encode(['success' => false, 'message' => 'Yetki gerekli']);
                exit;
            }
            $suspicious_id = $_POST['suspicious_id'] ?? '';
            $status = $_POST['status'] ?? '';
            $notes = $_POST['notes'] ?? '';
            $action_taken = $_POST['action_taken'] ?? 'none';
            echo json_encode(reviewSuspiciousSession($suspicious_id, $user_id, $status, $notes, $action_taken));
            break;
            
        case 'get_session_statistics':
            if (!$is_admin_request) {
                echo json_encode(['success' => false, 'message' => 'Yetki gerekli']);
                exit;
            }
            $days = $_GET['days'] ?? 7;
            echo json_encode(getSessionStatistics($days));
            break;
            
        case 'search_sessions':
            if (!$is_admin_request) {
                echo json_encode(['success' => false, 'message' => 'Yetki gerekli']);
                exit;
            }
            $query = $_GET['query'] ?? '';
            $type = $_GET['type'] ?? 'username';
            echo json_encode(searchSessions($query, $type));
            break;
            
        default:
            echo json_encode(['success' => false, 'message' => 'Geçersiz işlem']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Hata: ' . $e->getMessage()]);
}

// Kullanıcı fonksiyonları
function getMyActiveSessions($user_id) {
    global $conn;
    
    $stmt = $conn->prepare("
        SELECT 
            session_id,
            ip_address,
            user_agent,
            device_info,
            location_info,
            login_time,
            last_activity,
            is_mobile,
            login_method,
            security_level
        FROM user_sessions 
        WHERE user_id = ? AND is_active = TRUE 
        ORDER BY last_activity DESC
    ");
    
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $sessions = [];
    while ($row = $result->fetch_assoc()) {
        $row['device_info'] = json_decode($row['device_info'], true);
        $row['location_info'] = json_decode($row['location_info'], true);
        $row['is_current'] = $row['session_id'] === session_id();
        $sessions[] = $row;
    }
    
    return ['success' => true, 'sessions' => $sessions];
}

function terminateMySession($user_id, $session_id) {
    global $conn;
    
    // Kendi oturumunu sonlandıramaz
    if ($session_id === session_id()) {
        return ['success' => false, 'message' => 'Aktif oturumunuzu sonlandıramazsınız'];
    }
    
    $stmt = $conn->prepare("
        UPDATE user_sessions 
        SET is_active = FALSE, terminated_at = NOW(), termination_reason = 'Kullanıcı tarafından sonlandırıldı'
        WHERE user_id = ? AND session_id = ? AND is_active = TRUE
    ");
    
    $stmt->bind_param("is", $user_id, $session_id);
    
    if ($stmt->execute() && $stmt->affected_rows > 0) {
        return ['success' => true, 'message' => 'Oturum başarıyla sonlandırıldı'];
    }
    
    return ['success' => false, 'message' => 'Oturum bulunamadı veya zaten sonlandırılmış'];
}

function getMySessionActivity($user_id, $limit) {
    global $conn;
    
    $stmt = $conn->prepare("
        SELECT 
            activity_type,
            page_url,
            action_details,
            ip_address,
            activity_time
        FROM session_activities 
        WHERE user_id = ? 
        ORDER BY activity_time DESC 
        LIMIT ?
    ");
    
    $stmt->bind_param("ii", $user_id, $limit);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $activities = [];
    while ($row = $result->fetch_assoc()) {
        $row['action_details'] = json_decode($row['action_details'], true);
        $activities[] = $row;
    }
    
    return ['success' => true, 'activities' => $activities];
}

// Admin fonksiyonları
function getAllActiveSessions($page, $limit, $filter) {
    global $conn;
    
    $offset = ($page - 1) * $limit;
    $where_clause = "WHERE s.is_active = TRUE";
    
    if ($filter === 'suspicious') {
        $where_clause .= " AND EXISTS (SELECT 1 FROM suspicious_sessions ss WHERE ss.session_id = s.session_id AND ss.status = 'pending')";
    } elseif ($filter === 'mobile') {
        $where_clause .= " AND s.is_mobile = TRUE";
    } elseif ($filter === 'desktop') {
        $where_clause .= " AND s.is_mobile = FALSE";
    }
    
    $stmt = $conn->prepare("
        SELECT 
            s.session_id,
            s.user_id,
            u.username,
            u.email,
            s.ip_address,
            s.user_agent,
            s.device_info,
            s.location_info,
            s.login_time,
            s.last_activity,
            s.is_mobile,
            s.login_method,
            s.security_level,
            (SELECT COUNT(*) FROM suspicious_sessions ss WHERE ss.session_id = s.session_id AND ss.status = 'pending') as suspicious_count
        FROM user_sessions s
        JOIN kullanicilar u ON s.user_id = u.id
        $where_clause
        ORDER BY s.last_activity DESC
        LIMIT ? OFFSET ?
    ");
    
    $stmt->bind_param("ii", $limit, $offset);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $sessions = [];
    while ($row = $result->fetch_assoc()) {
        $row['device_info'] = json_decode($row['device_info'], true);
        $row['location_info'] = json_decode($row['location_info'], true);
        $row['is_suspicious'] = $row['suspicious_count'] > 0;
        $sessions[] = $row;
    }
    
    // Toplam sayı
    $count_stmt = $conn->prepare("
        SELECT COUNT(*) as total
        FROM user_sessions s
        JOIN kullanicilar u ON s.user_id = u.id
        $where_clause
    ");
    $count_stmt->execute();
    $total = $count_stmt->get_result()->fetch_assoc()['total'];
    
    return [
        'success' => true, 
        'sessions' => $sessions,
        'pagination' => [
            'current_page' => $page,
            'total_pages' => ceil($total / $limit),
            'total_records' => $total
        ]
    ];
}

function terminateSession($session_id, $admin_id, $reason) {
    global $conn;
    
    // Admin ID'si geçerli değilse NULL kullan
    $terminated_by = ($admin_id > 0) ? $admin_id : null;
    
    // Önce sonlandırılacak oturumun user_id'sini al
    $stmt = $conn->prepare("SELECT user_id FROM user_sessions WHERE session_id = ? AND is_active = TRUE");
    $stmt->bind_param("s", $session_id);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();
    
    if (!$result) {
        return ['success' => false, 'message' => 'Oturum bulunamadı veya zaten sonlandırılmış'];
    }
    
    $session_user_id = $result['user_id'];
    
    $stmt = $conn->prepare("
        UPDATE user_sessions 
        SET is_active = FALSE, terminated_at = NOW(), terminated_by = ?, termination_reason = ?
        WHERE session_id = ? AND is_active = TRUE
    ");
    
    $stmt->bind_param("iss", $terminated_by, $reason, $session_id);
    
    if ($stmt->execute() && $stmt->affected_rows > 0) {
        // Aktivite kaydı ekle - sonlandırılan oturumun user_id'sini kullan
        logSessionActivityWithUserId($session_id, $session_user_id, 'logout', null, json_encode(['terminated_by_admin' => true, 'reason' => $reason]));
        
        return ['success' => true, 'message' => 'Oturum başarıyla sonlandırıldı'];
    }
    
    return ['success' => false, 'message' => 'Oturum sonlandırılamadı'];
}

function getSessionDetails($session_id) {
    global $conn;
    
    // Oturum detayları
    $stmt = $conn->prepare("
        SELECT 
            s.*,
            u.username,
            u.email,
            u.first_name,
            u.surname
        FROM user_sessions s
        JOIN kullanicilar u ON s.user_id = u.id
        WHERE s.session_id = ?
    ");
    
    $stmt->bind_param("s", $session_id);
    $stmt->execute();
    $session = $stmt->get_result()->fetch_assoc();
    
    if (!$session) {
        return ['success' => false, 'message' => 'Oturum bulunamadı'];
    }
    
    $session['device_info'] = json_decode($session['device_info'], true);
    $session['location_info'] = json_decode($session['location_info'], true);
    
    // Son aktiviteler
    $activity_stmt = $conn->prepare("
        SELECT * FROM session_activities 
        WHERE session_id = ? 
        ORDER BY activity_time DESC 
        LIMIT 20
    ");
    
    $activity_stmt->bind_param("s", $session_id);
    $activity_stmt->execute();
    $activities = $activity_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    
    foreach ($activities as &$activity) {
        $activity['action_details'] = json_decode($activity['action_details'], true);
    }
    
    // Şüpheli aktiviteler
    $suspicious_stmt = $conn->prepare("
        SELECT * FROM suspicious_sessions 
        WHERE session_id = ? 
        ORDER BY created_at DESC
    ");
    
    $suspicious_stmt->bind_param("s", $session_id);
    $suspicious_stmt->execute();
    $suspicious = $suspicious_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    
    return [
        'success' => true,
        'session' => $session,
        'activities' => $activities,
        'suspicious_activities' => $suspicious
    ];
}

function getSuspiciousSessions($page, $limit) {
    global $conn;
    
    $offset = ($page - 1) * $limit;
    
    $stmt = $conn->prepare("
        SELECT 
            ss.*,
            u.username,
            u.email,
            s.ip_address,
            s.last_activity
        FROM suspicious_sessions ss
        JOIN kullanicilar u ON ss.user_id = u.id
        LEFT JOIN user_sessions s ON ss.session_id = s.session_id
        ORDER BY ss.created_at DESC
        LIMIT ? OFFSET ?
    ");
    
    $stmt->bind_param("ii", $limit, $offset);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $suspicious = [];
    while ($row = $result->fetch_assoc()) {
        $row['evidence_data'] = json_decode($row['evidence_data'], true);
        $suspicious[] = $row;
    }
    
    // Toplam sayı
    $count_stmt = $conn->prepare("SELECT COUNT(*) as total FROM suspicious_sessions");
    $count_stmt->execute();
    $total = $count_stmt->get_result()->fetch_assoc()['total'];
    
    return [
        'success' => true,
        'suspicious_sessions' => $suspicious,
        'pagination' => [
            'current_page' => $page,
            'total_pages' => ceil($total / $limit),
            'total_records' => $total
        ]
    ];
}

function reviewSuspiciousSession($suspicious_id, $admin_id, $status, $notes, $action_taken) {
    global $conn;
    
    $stmt = $conn->prepare("
        UPDATE suspicious_sessions 
        SET status = ?, reviewed_by = ?, reviewed_at = NOW(), review_notes = ?, action_taken = ?
        WHERE id = ?
    ");
    
    $stmt->bind_param("sissi", $status, $admin_id, $notes, $action_taken, $suspicious_id);
    
    if ($stmt->execute() && $stmt->affected_rows > 0) {
        // Eğer oturum sonlandırılması gerekiyorsa
        if ($action_taken === 'session_terminated') {
            $session_stmt = $conn->prepare("SELECT session_id FROM suspicious_sessions WHERE id = ?");
            $session_stmt->bind_param("i", $suspicious_id);
            $session_stmt->execute();
            $session_id = $session_stmt->get_result()->fetch_assoc()['session_id'];
            
            if ($session_id) {
                terminateSession($session_id, $admin_id, 'Şüpheli aktivite nedeniyle sonlandırıldı');
            }
        }
        
        return ['success' => true, 'message' => 'İnceleme başarıyla kaydedildi'];
    }
    
    return ['success' => false, 'message' => 'İnceleme kaydedilemedi'];
}

function getSessionStatistics($days) {
    global $conn;
    
    $stmt = $conn->prepare("
        SELECT * FROM session_statistics 
        WHERE date_recorded >= DATE_SUB(CURDATE(), INTERVAL ? DAY)
        ORDER BY date_recorded DESC
    ");
    
    $stmt->bind_param("i", $days);
    $stmt->execute();
    $stats = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    
    // Güncel istatistikler
    $current_stmt = $conn->prepare("
        SELECT 
            COUNT(*) as active_sessions,
            COUNT(CASE WHEN is_mobile = TRUE THEN 1 END) as mobile_sessions,
            COUNT(CASE WHEN is_mobile = FALSE THEN 1 END) as desktop_sessions,
            AVG(TIMESTAMPDIFF(MINUTE, login_time, COALESCE(terminated_at, NOW()))) as avg_duration
        FROM user_sessions 
        WHERE is_active = TRUE
    ");
    
    $current_stmt->execute();
    $current = $current_stmt->get_result()->fetch_assoc();
    
    // Şüpheli oturum sayısı
    $suspicious_stmt = $conn->prepare("
        SELECT COUNT(*) as pending_suspicious
        FROM suspicious_sessions 
        WHERE status = 'pending'
    ");
    
    $suspicious_stmt->execute();
    $suspicious_count = $suspicious_stmt->get_result()->fetch_assoc()['pending_suspicious'];
    
    return [
        'success' => true,
        'historical_stats' => $stats,
        'current_stats' => $current,
        'pending_suspicious' => $suspicious_count
    ];
}

function searchSessions($query, $type) {
    global $conn;
    
    $where_clause = "";
    $params = [];
    $param_types = "";
    
    switch ($type) {
        case 'username':
            $where_clause = "WHERE u.username LIKE ?";
            $params[] = "%$query%";
            $param_types = "s";
            break;
        case 'email':
            $where_clause = "WHERE u.email LIKE ?";
            $params[] = "%$query%";
            $param_types = "s";
            break;
        case 'ip':
            $where_clause = "WHERE s.ip_address LIKE ?";
            $params[] = "%$query%";
            $param_types = "s";
            break;
        case 'session_id':
            $where_clause = "WHERE s.session_id = ?";
            $params[] = $query;
            $param_types = "s";
            break;
    }
    
    $stmt = $conn->prepare("
        SELECT 
            s.session_id,
            s.user_id,
            u.username,
            u.email,
            s.ip_address,
            s.login_time,
            s.last_activity,
            s.is_active,
            s.is_mobile
        FROM user_sessions s
        JOIN kullanicilar u ON s.user_id = u.id
        $where_clause
        ORDER BY s.last_activity DESC
        LIMIT 50
    ");
    
    if (!empty($params)) {
        $stmt->bind_param($param_types, ...$params);
    }
    
    $stmt->execute();
    $result = $stmt->get_result();
    
    $sessions = [];
    while ($row = $result->fetch_assoc()) {
        $sessions[] = $row;
    }
    
    return ['success' => true, 'sessions' => $sessions];
}

// Yardımcı fonksiyonlar
function logSessionActivity($session_id, $activity_type, $page_url = null, $action_details = null) {
    global $conn;
    
    $user_id = $_SESSION['user_id'] ?? null;
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? '';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    
    $stmt = $conn->prepare("
        INSERT INTO session_activities (session_id, user_id, activity_type, page_url, action_details, ip_address, user_agent)
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ");
    
    $stmt->bind_param("sisssss", $session_id, $user_id, $activity_type, $page_url, $action_details, $ip_address, $user_agent);
    $stmt->execute();
}

function logSessionActivityWithUserId($session_id, $user_id, $activity_type, $page_url = null, $action_details = null) {
    global $conn;
    
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? '';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    
    $stmt = $conn->prepare("
        INSERT INTO session_activities (session_id, user_id, activity_type, page_url, action_details, ip_address, user_agent)
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ");
    
    $stmt->bind_param("sisssss", $session_id, $user_id, $activity_type, $page_url, $action_details, $ip_address, $user_agent);
    $stmt->execute();
}

function createUserSession($user_id, $login_method = 'web') {
    global $conn;
    
    error_log("createUserSession called for user_id: $user_id, login_method: $login_method");
    
    // Session ID oluştur
    $session_id = session_id();
    if (empty($session_id)) {
        $session_id = bin2hex(random_bytes(16));
    }
    
    error_log("Generated session_id: $session_id");
    
    // IP adresi ve user agent bilgilerini al
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
    
    // Cihaz bilgilerini tespit et
    $is_mobile = isMobileDevice($user_agent);
    
    // Device info JSON
    $device_info = json_encode([
        'browser' => getBrowserInfo($user_agent),
        'os' => getOSInfo($user_agent),
        'device_type' => $is_mobile ? 'mobile' : 'desktop'
    ]);
    
    // Location info (basit IP tabanlı)
    $location_info = json_encode([
        'ip' => $ip_address,
        'country' => 'Unknown', // Gerçek uygulamada IP geolocation servisi kullanılabilir
        'city' => 'Unknown'
    ]);
    
    try {
        // Kullanıcının diğer aktif sessionlarını sonlandır (tek session politikası)
        $stmt = $conn->prepare("UPDATE user_sessions SET is_active = FALSE WHERE user_id = ? AND is_active = TRUE");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        
        error_log("Deactivated existing sessions for user: $user_id");
        
        // Yeni session oluştur
        $stmt = $conn->prepare("
            INSERT INTO user_sessions (
                session_id, user_id, ip_address, user_agent, device_info, 
                location_info, login_time, last_activity, is_active, 
                is_mobile, login_method, security_level
            ) VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW(), TRUE, ?, ?, 'medium')
        ");
        
        $stmt->bind_param("sissssis", 
            $session_id, $user_id, $ip_address, $user_agent, $device_info, 
            $location_info, $is_mobile, $login_method
        );
        
        if ($stmt->execute()) {
            error_log("Session created successfully in database for user: $user_id");
            // Session activity log
            logSessionActivityWithUserId($session_id, $user_id, 'login', $_SERVER['REQUEST_URI'] ?? '/', 'User logged in');
            return $session_id;
        } else {
            error_log("Failed to execute session insert statement: " . $stmt->error);
        }
        
    } catch (Exception $e) {
        error_log("Session creation error: " . $e->getMessage());
    }
    
    return false;
}

function isMobileDevice($user_agent) {
    return preg_match('/Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i', $user_agent);
}

function getBrowserInfo($user_agent) {
    if (preg_match('/Chrome/i', $user_agent)) return 'Chrome';
    if (preg_match('/Firefox/i', $user_agent)) return 'Firefox';
    if (preg_match('/Safari/i', $user_agent)) return 'Safari';
    if (preg_match('/Edge/i', $user_agent)) return 'Edge';
    if (preg_match('/Opera/i', $user_agent)) return 'Opera';
    return 'Unknown';
}

function getOSInfo($user_agent) {
    if (preg_match('/Windows/i', $user_agent)) return 'Windows';
    if (preg_match('/Mac/i', $user_agent)) return 'macOS';
    if (preg_match('/Linux/i', $user_agent)) return 'Linux';
    if (preg_match('/Android/i', $user_agent)) return 'Android';
    if (preg_match('/iOS/i', $user_agent)) return 'iOS';
    return 'Unknown';
}

function isAdmin($user_id) {
    global $conn;
    
    // Admin tablosunda bu user_id'nin olup olmadığını kontrol et
    $stmt = $conn->prepare("SELECT id FROM admin WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();
    
    return $result !== null;
}
?>