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

requireLogin();
$user   = getConnectedUser($pdo);
$userId = (int)$user['id'];

try {
    $stmt = $pdo->prepare("SELECT status, COUNT(*) as nb FROM bets WHERE user_id=? GROUP BY status");
    $stmt->execute([$userId]);
    $raw = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
} catch (Exception $e) { $raw = []; }

$won     = (int)($raw['won']     ?? 0);
$lost    = (int)($raw['lost']    ?? 0);
$pending = (int)($raw['pending'] ?? 0);
$total   = $won + $lost;
$ratio   = $total > 0 ? round($won / $total * 100) : 0;

try {
    $us = $pdo->prepare("SELECT * FROM user_stats WHERE user_id=?");
    $us->execute([$userId]);
    $uStats = $us->fetch() ?: [];
} catch (Exception $e) { $uStats = []; }

try {
    $nhCount = (int)$pdo->query("SELECT COUNT(*) FROM bets WHERE not_honored=1 AND (user_id={$userId} OR parieur2_id={$userId})")->fetchColumn();
} catch (Exception $e) { $nhCount = 0; }
$refused     = (int)($uStats['refused'] ?? 0) + $nhCount;
$reliability = $total > 0 ? max(0, round((1 - $refused / $total) * 100)) : 100;

try {
    $rStmt = $pdo->prepare("SELECT AVG(stars) as avg, COUNT(*) as total FROM user_ratings WHERE rated_id=?");
    $rStmt->execute([$userId]);
    $ratingRow = $rStmt->fetch();
    $avgStars  = round((float)($ratingRow['avg'] ?? 0), 1);
    $nbRatings = (int)($ratingRow['total'] ?? 0);
} catch (Exception $e) { $avgStars = 0; $nbRatings = 0; }

$walletPts = (int)($user['wallet_points'] ?? 0);

try {
    $wtStmt = $pdo->prepare("SELECT type, SUM(amount) as total FROM wallet_transactions WHERE user_id=? GROUP BY type");
    $wtStmt->execute([$userId]);
    $wtRows = $wtStmt->fetchAll();
    $walletByType = [];
    foreach ($wtRows as $r) $walletByType[$r['type']] = $r['total'];
} catch (Exception $e) { $walletByType = []; }

try {
    $hist = $pdo->prepare("SELECT b.*, c.name as circle_name FROM bets b LEFT JOIN circles c ON c.id=b.circle_id WHERE b.user_id=? ORDER BY b.id DESC LIMIT 15");
    $hist->execute([$userId]);
    $history = $hist->fetchAll();
} catch (Exception $e) { $history = []; }

try {
    $monthly = $pdo->prepare("SELECT DATE_FORMAT(created_at,'%Y-%m') as mois, COUNT(*) as nb FROM bets WHERE user_id=? AND created_at >= DATE_SUB(NOW(), INTERVAL 12 MONTH) GROUP BY mois ORDER BY mois ASC");
    $monthly->execute([$userId]);
    $monthlyData = $monthly->fetchAll();
} catch (Exception $e) { $monthlyData = []; }

include 'header.php';
?>

<div class="container mt-4 px-4" style="max-width:1000px;">
    <div class="d-flex align-items-center gap-3 mb-4">
        <a href="index.php" class="btn btn-outline-secondary btn-sm">&larr; Dashboard</a>
        <h5 class="oracle-text text-primary mb-0">STATISTIQUES — <?= htmlspecialchars($user['username']) ?></h5>
    </div>

    <div class="row g-2 mb-4">
        <?php foreach ([
            [$won,'Gagnes','success'],[$lost,'Perdus','danger'],[$pending,'En cours','warning'],
            [$ratio.'%','Victoires','primary'],[$reliability.'%','Fiabilite','info'],[number_format($walletPts),'Jetons','warning']
        ] as [$val,$lbl,$col]): ?>
        <div class="col-4 col-md-2">
            <div class="card bg-dark border-<?= $col ?> text-center p-2">
                <div class="text-<?= $col ?> fw-bold" style="font-size:1.4rem;"><?= $val ?></div>
                <small class="text-white" style="font-size:0.6rem;"><?= $lbl ?></small>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <div class="row g-3 mb-4">
        <div class="col-md-4">
            <div class="card bg-dark border-secondary p-3 h-100">
                <h6 class="text-info fw-bold small mb-3">Points & Wallet</h6>
                <?php foreach ([
                    ["Points d'honneur", (int)$user['points'],'success'],
                    ["Pts interaction",  (int)($user['interaction_points']??0),'info'],
                    ["Jetons wallet",    $walletPts,'warning'],
                    ["Bonus connexion",  (int)($walletByType['daily_bonus']??0),'warning'],
                    ["Gains roulette",   (int)($walletByType['daily_roll']??0),'info'],
                    ["Gains gages",      (int)($walletByType['bet_win']??0),'success'],
                    ["Notation",         $nbRatings>0?$avgStars.'/5':'—','warning'],
                ] as [$lbl,$val,$col]): ?>
                <div class="d-flex justify-content-between mb-1">
                    <span style="color:#aaa;font-size:0.75rem;"><?= $lbl ?></span>
                    <span class="text-<?= $col ?> fw-bold" style="font-size:0.75rem;"><?= $val ?></span>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card bg-dark border-secondary p-3 h-100">
                <h6 class="text-info fw-bold small mb-3">Progression</h6>
                <?php foreach ([
                    ['Victoires',$won,max($total,1),'bg-success'],
                    ['Defaites',$lost,max($total,1),'bg-danger'],
                    ['Taux succes',$ratio,100,'bg-primary'],
                    ['Fiabilite',$reliability,100,'bg-warning'],
                    ['Notation',$avgStars*20,100,'bg-info'],
                ] as [$lbl,$val,$max,$col]):
                    $pct = $max > 0 ? round($val/$max*100) : 0; ?>
                <div class="mb-2">
                    <div class="d-flex justify-content-between mb-1">
                        <small class="text-white"><?= $lbl ?></small>
                        <small class="text-white"><?= $val ?><?= $max===100?'%':'' ?></small>
                    </div>
                    <div class="progress" style="height:5px;background:#2a2a2a;">
                        <div class="progress-bar <?= $col ?>" style="width:<?= $pct ?>%;"></div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card bg-dark border-secondary p-3 h-100">
                <h6 class="text-info fw-bold small mb-3">Activite (12 mois)</h6>
                <?php if (!empty($monthlyData)):
                    $maxNb = max(array_column($monthlyData,'nb'));
                    foreach ($monthlyData as $m):
                        $pct = $maxNb>0 ? round($m['nb']/$maxNb*100) : 0;
                        $lbl = date('M y', strtotime($m['mois'].'-01')); ?>
                <div class="d-flex align-items-center gap-2 mb-1">
                    <small style="color:#aaa;min-width:42px;font-size:0.6rem;"><?= $lbl ?></small>
                    <div class="flex-grow-1" style="background:#1a1a1a;border-radius:3px;height:10px;">
                        <div style="width:<?= $pct ?>%;background:#0d6efd;height:100%;border-radius:3px;"></div>
                    </div>
                    <small class="text-white" style="font-size:0.6rem;"><?= $m['nb'] ?></small>
                </div>
                <?php endforeach; else: ?>
                <p style="color:#aaa;font-size:0.72rem;">Aucune activite.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="card bg-dark border-secondary shadow">
        <div class="card-header bg-secondary text-white py-2 fw-bold small">HISTORIQUE RECENT</div>
        <div class="table-responsive">
            <table class="table table-dark table-hover table-sm mb-0 small">
                <thead><tr><th class="ps-3">#</th><th>Defi</th><th>Cercle</th><th class="text-center">Pts</th><th class="text-center">Jetons</th><th class="text-center">Statut</th></tr></thead>
                <tbody>
                <?php foreach ($history as $row):
                    $st = $row['status'] ?? 'pending';
                    $bc = match($st){'won'=>'bg-success','lost'=>'bg-danger','pending'=>'bg-warning text-dark',default=>'bg-secondary'};
                    $sl = match($st){'won'=>'Gagne','lost'=>'Perdu','pending'=>'En cours',default=>$st};
                    $stake = (int)($row['wallet_stake']??0);
                ?>
                <tr>
                    <td class="ps-3 text-muted"><?= $row['id'] ?></td>
                    <td><?= htmlspecialchars(mb_substr($row['description']??'',0,45)) ?><?= strlen($row['description']??'')>45?'...':'' ?></td>
                    <td><small class="text-info"><?= htmlspecialchars($row['circle_name']??'Global') ?></small></td>
                    <td class="text-center text-success"><?= (int)$row['amount'] ?></td>
                    <td class="text-center"><?= $stake>0?'<span class="badge bg-warning text-dark" style="font-size:0.52rem;">'.$stake.'</span>':'—' ?></td>
                    <td class="text-center">
                        <span class="badge <?= $bc ?>" style="font-size:0.55rem;"><?= $sl ?></span>
                        <?php if(!empty($row['honored'])) echo '<span class="badge bg-success ms-1" style="font-size:0.5rem;">H</span>'; ?>
                        <?php if(!empty($row['not_honored'])) echo '<span class="badge bg-danger ms-1" style="font-size:0.5rem;">NH</span>'; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php if(empty($history)): ?><tr><td colspan="6" class="text-center text-muted py-3">Aucun gage.</td></tr><?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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