<?php
session_start();
require_once 'config.php';

$type   = $_GET['type']   ?? 'points';
$period = $_GET['period'] ?? 'all'; // v1.7: week, month, year, all

switch ($period) {
    case 'week':  $periodCond = "AND b.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)";   break;
    case 'month': $periodCond = "AND b.created_at >= DATE_SUB(NOW(), INTERVAL 1 MONTH)"; break;
    case 'year':  $periodCond = "AND b.created_at >= DATE_SUB(NOW(), INTERVAL 1 YEAR)";  break;
    default:      $periodCond = ''; break;
}

// v1.7 — Restreindre au cercle pour comptes privés
$userId   = (int)($_SESSION['user_id'] ?? 0);
$circleId = (int)($_SESSION['circle_id'] ?? 0);
$circleCond = '';
try {
    if ($circleId && $userId) {
        $hasPU = (bool)$pdo->query("SHOW COLUMNS FROM users LIKE 'is_private_user'")->fetch();
        if ($hasPU) {
            $uRow = $pdo->prepare("SELECT is_private_user FROM users WHERE id=?");
            $uRow->execute([$userId]);
            if (!empty($uRow->fetchColumn())) {
                $circleCond = "AND u.id IN (SELECT user_id FROM circle_members WHERE circle_id={$circleId})";
            }
        }
    }
} catch (Exception $e) {}

try {
    $cols           = $pdo->query("SHOW COLUMNS FROM users")->fetchAll(PDO::FETCH_COLUMN);
    $hasNickname    = in_array('nickname', $cols);
    $hasInteraction = in_array('interaction_points', $cols);
    $nickSelect     = $hasNickname ? ', u.nickname' : '';

    switch ($type) {

        case 'gain_perte':
            $hasSales = false; $saleAmtCol = 'price';
            try {
                $sc = $pdo->query("SHOW COLUMNS FROM store_sales")->fetchAll(PDO::FETCH_COLUMN);
                foreach (['total_price','amount','price'] as $c) {
                    if (in_array($c, $sc)) { $hasSales = true; $saleAmtCol = $c; break; }
                }
            } catch(Exception $e) {}
            $sql = $hasSales
                ? "SELECT u.id, u.username {$nickSelect}, (u.points - COALESCE((SELECT SUM(ss.{$saleAmtCol}) FROM store_sales ss WHERE ss.user_id=u.id AND ss.status='paid'),0)) as valeur FROM users u WHERE 1=1 {$circleCond} ORDER BY valeur DESC LIMIT 10"
                : "SELECT u.id, u.username {$nickSelect}, u.points as valeur FROM users u WHERE 1=1 {$circleCond} ORDER BY u.points DESC LIMIT 10";
            $label = 'pts net'; break;

        case 'gages':
            $sql = "SELECT u.id, u.username {$nickSelect}, COUNT(b.id) as valeur FROM users u LEFT JOIN bets b ON b.user_id=u.id {$periodCond} WHERE 1=1 {$circleCond} GROUP BY u.id, u.username" . ($hasNickname ? ', u.nickname' : '') . " ORDER BY valeur DESC LIMIT 10";
            $label = 'gages'; break;

        case 'honores': // v1.7 — engagements honorés (surtout utile cercles privés)
            $hasHon = (bool)$pdo->query("SHOW COLUMNS FROM bets LIKE 'honored'")->fetch();
            $sql = $hasHon
                ? "SELECT u.id, u.username {$nickSelect}, COUNT(b.id) as valeur FROM users u LEFT JOIN bets b ON (b.user_id=u.id OR b.parieur2_id=u.id) AND b.honored=1 {$periodCond} WHERE 1=1 {$circleCond} GROUP BY u.id, u.username" . ($hasNickname ? ', u.nickname' : '') . " ORDER BY valeur DESC LIMIT 10"
                : "SELECT u.id, u.username {$nickSelect}, 0 as valeur FROM users u WHERE 1=1 {$circleCond} LIMIT 10";
            $label = 'honorés'; break;

        case 'interaction':
            $sql = $hasInteraction
                ? "SELECT u.id, u.username {$nickSelect}, u.interaction_points as valeur FROM users u WHERE 1=1 {$circleCond} ORDER BY u.interaction_points DESC LIMIT 10"
                : "SELECT u.id, u.username {$nickSelect}, 0 as valeur FROM users u WHERE 1=1 {$circleCond} LIMIT 10";
            $label = 'pts'; break;

        case 'wallet':
            $hasW = (bool)$pdo->query("SHOW COLUMNS FROM users LIKE 'wallet_points'")->fetch();
            $sql = $hasW
                ? "SELECT u.id, u.username {$nickSelect}, COALESCE(u.wallet_points,0) as valeur FROM users u WHERE 1=1 {$circleCond} ORDER BY valeur DESC LIMIT 10"
                : "SELECT u.id, u.username {$nickSelect}, 0 as valeur FROM users u WHERE 1=1 {$circleCond} LIMIT 10";
            $label = 'jetons'; break;

        case 'fiable':
            $hasNH  = (bool)$pdo->query("SHOW COLUMNS FROM bets LIKE 'not_honored'")->fetch();
            $hasRef = false;
            try { $hasRef = (bool)$pdo->query("SHOW COLUMNS FROM user_stats LIKE 'refused'")->fetch(); } catch(Exception $e){}
            $refExpr = $hasRef ? "COALESCE(us.refused,0)" : "0";
            $nhExpr  = $hasNH ? "(SELECT COUNT(*) FROM bets bnh WHERE bnh.not_honored=1 {$periodCond} AND (bnh.user_id=u.id OR bnh.parieur2_id=u.id))" : "0";
            $sql = "SELECT u.id, u.username {$nickSelect}, ROUND(CASE WHEN COALESCE(us.total_bets,0)=0 THEN 100 ELSE (1-(({$refExpr}+{$nhExpr})/COALESCE(us.total_bets,1)))*100 END,1) as valeur FROM users u LEFT JOIN user_stats us ON us.user_id=u.id WHERE 1=1 {$circleCond} ORDER BY valeur DESC LIMIT 10";
            $label = '% fiable'; break;

        default: // honneur
            $sql = "SELECT u.id, u.username {$nickSelect}, u.points as valeur FROM users u WHERE 1=1 {$circleCond} ORDER BY u.points DESC LIMIT 10";
            $label = 'pts'; break;
    }

    $rows = $pdo->query($sql)->fetchAll();
    if (empty($rows)) {
        echo "<tr><td colspan='3' class='text-center text-muted small py-2'>Aucune donnée</td></tr>";
    } else {
        $rank = 1;
        foreach ($rows as $row) {
            $icon = $rank===1 ? '&#127881;' : ($rank===2 ? '&#129352;' : ($rank===3 ? '&#129353;' : "{$rank}."));
            $name = htmlspecialchars($row['username']);
            $nick = ($hasNickname && !empty($row['nickname'])) ? ' <small class="text-muted" style="font-size:0.58rem;">(' . htmlspecialchars($row['nickname']) . ')</small>' : '';
            $val  = number_format((float)($row['valeur'] ?? 0), 0);
            $id   = (int)$row['id'];
            echo "<tr>";
            echo "<td class='ps-2' style='font-size:0.7rem;'>{$icon}</td>";
            echo "<td style='font-size:0.7rem;cursor:pointer;color:#0d6efd;' onclick='viewProfile({$id})'>{$name}{$nick}</td>";
            echo "<td class='text-end pe-2 text-success fw-bold' style='font-size:0.7rem;'>{$val} <small class='text-muted'>{$label}</small></td>";
            echo "</tr>";
            $rank++;
        }
    }
} catch (Exception $e) {
    echo "<tr><td colspan='3' class='text-danger small p-2'>Erreur: " . htmlspecialchars($e->getMessage()) . "</td></tr>";
}
?>
