<?php
session_start();
require_once 'config.php';
require_once 'functions.php';
requireLogin();
$user = getConnectedUser($pdo);
requireAdmin($user);

// Seuils de détection
$seuil_gages_meme_personne = 5;    // X gages entre 2 mêmes personnes
$seuil_pct_perte = 80;             // % de pertes suspectes
$seuil_transfert_jetons = 500;     // Jetons transférés via gages
$jours_analyse = 30;               // Fenêtre d'analyse

$anomalies = [];

try {
    // 1. Paires suspects: trop de gages entre 2 mêmes personnes
    $pairs = $pdo->query("
        SELECT
            LEAST(b.user_id, b.parieur2_id) as u1,
            GREATEST(b.user_id, b.parieur2_id) as u2,
            COUNT(*) as nb_gages,
            SUM(b.wallet_stake) as total_jetons,
            u1.username as nom1, u2.username as nom2,
            SUM(CASE WHEN b.honored=1 AND b.status='lost' AND b.user_id=LEAST(b.user_id,b.parieur2_id) THEN 1 ELSE 0 END) as pertes_u1,
            SUM(CASE WHEN b.honored=1 THEN 1 ELSE 0 END) as gages_honores
        FROM bets b
        JOIN users u1 ON u1.id = LEAST(b.user_id, b.parieur2_id)
        JOIN users u2 ON u2.id = GREATEST(b.user_id, b.parieur2_id)
        WHERE b.parieur2_id IS NOT NULL
          AND b.created_at >= DATE_SUB(NOW(), INTERVAL {$jours_analyse} DAY)
        GROUP BY LEAST(b.user_id, b.parieur2_id), GREATEST(b.user_id, b.parieur2_id)
        HAVING nb_gages >= {$seuil_gages_meme_personne}
        ORDER BY total_jetons DESC, nb_gages DESC
        LIMIT 20
    ")->fetchAll();

    foreach ($pairs as $p) {
        $pctPerte = $p['gages_honores'] > 0 ? round($p['pertes_u1'] / $p['gages_honores'] * 100) : 0;
        $niveau = $p['total_jetons'] > $seuil_transfert_jetons || $pctPerte >= $seuil_pct_perte ? 'danger' : 'warning';
        $anomalies[] = [
            'niveau'  => $niveau,
            'type'    => 'PAIRE SUSPECTE',
            'icone'   => 'fa-users',
            'desc'    => "{$p['nom1']} ↔ {$p['nom2']} : {$p['nb_gages']} gages, {$p['total_jetons']} jetons échangés" .
                         ($pctPerte >= $seuil_pct_perte ? " — {$p['nom1']} perd {$pctPerte}% du temps" : ""),
            'detail'  => "Gages honorés: {$p['gages_honores']}, Pertes de {$p['nom1']}: {$p['pertes_u1']}",
            'u1' => $p['u1'], 'u2' => $p['u2'],
        ];
    }

    // 2. Votes ne correspondant jamais aux résultats
    $voteAnomaly = $pdo->query("
        SELECT b.id, b.description, b.vote_oui, b.vote_non, b.status,
               u.username as lanceur,
               CASE
                   WHEN b.status='won'  AND b.vote_non  > b.vote_oui THEN 1
                   WHEN b.status='lost' AND b.vote_oui > b.vote_non  THEN 1
                   ELSE 0
               END as contra_vote
        FROM bets b JOIN users u ON u.id=b.user_id
        WHERE b.honored=1
          AND (b.vote_oui+b.vote_non) >= 3
          AND b.created_at >= DATE_SUB(NOW(), INTERVAL {$jours_analyse} DAY)
        HAVING contra_vote=1
        LIMIT 15
    ")->fetchAll();

    foreach ($voteAnomaly as $v) {
        $anomalies[] = [
            'niveau'  => 'warning',
            'type'    => 'VOTE CONTRA-RÉSULTAT',
            'icone'   => 'fa-thumbs-down',
            'desc'    => "Gage #{$v['id']} par {$v['lanceur']}: résultat " . strtoupper($v['status']) .
                         " mais votes OUI:{$v['vote_oui']} NON:{$v['vote_non']}",
            'detail'  => substr($v['description'], 0, 80),
        ];
    }

    // 3. Utilisateur perd trop souvent (>80% en jetons)
    $perdants = $pdo->query("
        SELECT u.id, u.username,
               COUNT(*) as nb_gages,
               SUM(CASE WHEN b.status='lost' AND b.user_id=u.id THEN 1 ELSE 0 END) as nb_pertes,
               SUM(CASE WHEN b.wallet_stake>0 AND b.status='lost' AND b.user_id=u.id THEN b.wallet_stake ELSE 0 END) as jetons_perdus,
               SUM(CASE WHEN b.wallet_stake>0 AND b.status='won'  AND b.user_id=u.id THEN b.wallet_stake ELSE 0 END) as jetons_gagnes
        FROM bets b JOIN users u ON u.id=b.user_id
        WHERE b.honored=1
          AND b.created_at >= DATE_SUB(NOW(), INTERVAL {$jours_analyse} DAY)
          AND b.wallet_stake > 0
        GROUP BY u.id
        HAVING nb_gages >= 3 AND (nb_pertes/nb_gages)*100 >= {$seuil_pct_perte}
        ORDER BY jetons_perdus DESC
        LIMIT 10
    ")->fetchAll();

    foreach ($perdants as $p) {
        $pct = round($p['nb_pertes']/$p['nb_gages']*100);
        $anomalies[] = [
            'niveau'  => $p['jetons_perdus'] > 200 ? 'danger' : 'warning',
            'type'    => 'PERTES EXCESSIVES',
            'icone'   => 'fa-arrow-trend-down',
            'desc'    => "{$p['username']} perd {$pct}% de ses gages ({$p['nb_pertes']}/{$p['nb_gages']}) — {$p['jetons_perdus']} jetons perdus",
            'detail'  => "Jetons gagnés: {$p['jetons_gagnes']} | Net: -" . ($p['jetons_perdus'] - $p['jetons_gagnes']),
            'uid' => $p['id'],
        ];
    }

    // 4. IPs multiples (si table disponible)
    // Note: nécessite log des IPs - placeholder
    
} catch (Exception $e) {
    $anomalies[] = ['niveau'=>'info','type'=>'ERREUR','icone'=>'fa-circle-info','desc'=>$e->getMessage(),'detail'=>''];
}

include 'header.php';
?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">

<div class="container-fluid mt-3 mb-5" style="max-width:1000px;">
    <div class="d-flex align-items-center gap-3 mb-4">
        <a href="admin.php" class="btn btn-outline-secondary btn-sm"><i class="fa-solid fa-arrow-left fa-xs me-1"></i>Admin</a>
        <h4 class="mb-0" style="color:#dc3545;letter-spacing:2px;font-family:'Orbitron';">
            <i class="fa-solid fa-triangle-exclamation me-2"></i>DÉTECTION D'ANOMALIES
        </h4>
        <span class="ms-auto badge bg-danger"><?= count($anomalies) ?> anomalie<?= count($anomalies)>1?'s':'' ?></span>
    </div>

    <!-- Paramètres -->
    <div class="card bg-dark border-secondary shadow mb-4">
        <div class="card-body py-2 d-flex gap-4" style="font-size:0.65rem;color:#888;">
            <span><i class="fa-solid fa-calendar fa-xs me-1"></i>Fenêtre: <?= $jours_analyse ?> jours</span>
            <span><i class="fa-solid fa-users fa-xs me-1"></i>Seuil paire: <?= $seuil_gages_meme_personne ?> gages</span>
            <span><i class="fa-solid fa-percent fa-xs me-1"></i>Seuil pertes: <?= $seuil_pct_perte ?>%</span>
            <span><i class="fa-solid fa-coins fa-xs me-1"></i>Seuil jetons: <?= $seuil_transfert_jetons ?></span>
        </div>
    </div>

    <?php if (empty($anomalies)): ?>
    <div class="card bg-dark border-success shadow">
        <div class="card-body text-center py-5">
            <i class="fa-solid fa-circle-check fa-3x text-success mb-3"></i>
            <div class="text-success fw-bold">Aucune anomalie détectée</div>
            <div class="text-muted small mt-1">Le système semble fonctionner normalement sur les <?= $jours_analyse ?> derniers jours.</div>
        </div>
    </div>
    <?php else: ?>

    <?php foreach ($anomalies as $a):
        $colors = ['danger'=>['#dc3545','rgba(220,53,69,0.08)','rgba(220,53,69,0.3)'],
                   'warning'=>['#ffc107','rgba(255,193,7,0.06)','rgba(255,193,7,0.3)'],
                   'info'=>['#0dcaf0','rgba(13,202,240,0.06)','rgba(13,202,240,0.3)']];
        [$col,$bg,$border] = $colors[$a['niveau']] ?? $colors['info'];
    ?>
    <div class="card mb-3 shadow" style="background:<?=$bg?>;border:1px solid <?=$border?>;">
        <div class="card-body py-3">
            <div class="d-flex align-items-start gap-3">
                <div style="width:36px;height:36px;border-radius:50%;background:<?=$bg?>;border:1px solid <?=$border?>;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                    <i class="fa-solid <?=$a['icone']?>" style="color:<?=$col?>;font-size:0.85rem;"></i>
                </div>
                <div style="flex:1;">
                    <div style="display:flex;align-items:center;gap:8px;margin-bottom:4px;">
                        <span style="font-size:0.62rem;font-weight:700;color:<?=$col?>;letter-spacing:1px;background:rgba(0,0,0,0.3);border:1px solid <?=$border?>;border-radius:4px;padding:1px 7px;"><?=$a['type']?></span>
                    </div>
                    <div style="font-size:0.78rem;color:#ddd;font-weight:600;margin-bottom:2px;"><?=htmlspecialchars($a['desc'])?></div>
                    <?php if ($a['detail']): ?>
                    <div style="font-size:0.65rem;color:#999;"><?=htmlspecialchars($a['detail'])?></div>
                    <?php endif; ?>
                </div>
                <div style="display:flex;gap:5px;flex-shrink:0;">
                    <?php if (!empty($a['uid'])): ?>
                    <a href="admin_users.php?edit=<?=$a['uid']?>" class="btn btn-sm btn-outline-secondary" style="font-size:0.6rem;">Voir membre</a>
                    <?php endif; ?>
                    <?php if (!empty($a['u1']) && !empty($a['u2'])): ?>
                    <a href="admin_bets.php?u1=<?=$a['u1']?>&u2=<?=$a['u2']?>" class="btn btn-sm btn-outline-warning" style="font-size:0.6rem;">Voir gages</a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>
</div>

<?php include 'footer.php'; ?>
