<?php
// Function to get total earnings
function getTotalEarnings() {
    global $pdo;
    $stmt = $pdo->query("SELECT SUM(amount) FROM transactions WHERE status = 'success'");
    return $stmt->fetchColumn() ?: 0;
}

// Function to get earnings for user based on role
function getEarningsForUser($user) {
    $total = getTotalEarnings();
    if ($user['role'] === 'super_admin') {
        return $total;
    } elseif ($user['role'] === 'admin') {
        $percentage = getSetting('admin_percentage') / 100;
        return $total * $percentage;
    } elseif ($user['role'] === 'presenter') {
        $adminPercentage = getSetting('admin_percentage') / 100;
        $presenterPercentage = getSetting('presenter_percentage') / 100;
        return $total * $adminPercentage * $presenterPercentage;
    }
    return 0;
}

// Function to get transactions count
function getTransactionsCount() {
    global $pdo;
    $stmt = $pdo->query("SELECT COUNT(*) FROM transactions WHERE status = 'success'");
    return $stmt->fetchColumn();
}

// Function to get total players (unique phones from sessions)
function getTotalPlayers() {
    global $pdo;
    $stmt = $pdo->query("SELECT COUNT(DISTINCT phone) FROM sessions");
    return $stmt->fetchColumn();
}

// Function to get total plays (total sessions)
function getTotalPlays() {
    global $pdo;
    $stmt = $pdo->query("SELECT COUNT(*) FROM sessions");
    return $stmt->fetchColumn();
}

// Function to get new players (unique phones in last 30 days)
function getNewPlayers() {
    global $pdo;
    $stmt = $pdo->prepare("SELECT COUNT(DISTINCT phone) FROM sessions WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)");
    $stmt->execute();
    return $stmt->fetchColumn();
}

// Function to get dialed but not paid (pending sessions)
function getDialedNotPaid() {
    global $pdo;
    $stmt = $pdo->query("SELECT COUNT(*) FROM sessions WHERE status = 'pending'");
    return $stmt->fetchColumn();
}

// Function to get paid players (completed sessions)
function getPaidPlayers() {
    global $pdo;
    $stmt = $pdo->query("SELECT COUNT(DISTINCT phone) FROM sessions WHERE status = 'completed'");
    return $stmt->fetchColumn();
}

// Function to get PesaPal mode
function getPesapalMode() {
    $mode = getSetting('pesapal_mode');
    return $mode ? $mode : 'sandbox';
}

// Function to check if PesaPal is configured
function isPesapalConfigured() {
    $key = getSetting('pesapal_consumer_key');
    $secret = getSetting('pesapal_consumer_secret');
    return !empty($key) && !empty($secret) && $key !== 'your_pesapal_consumer_key';
}
?>