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

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['error' => 'Méthode non autorisée']); exit;
}

try {
    // Compter avant suppression
    $count = (int)$pdo->query("SELECT COUNT(*) FROM bets")->fetchColumn();

    // Désactiver FK temporairement
    try { $pdo->exec("SET FOREIGN_KEY_CHECKS=0"); } catch(Exception $e) {}

    // Supprimer toutes les tables liées aux gages
    $tables = ['bet_votes','bet_proofs','bet_media','reports'];
    foreach ($tables as $t) {
        try { $pdo->exec("DELETE FROM {$t} WHERE 1=1"); } catch(Exception $e) {}
    }

    // Réinitialiser les stats liées aux gages
    try {
        $pdo->exec("UPDATE user_stats SET total_bets=0, won_bets=0, lost_bets=0, honored_bets=0, refused_bets=0, reliability_score=100");
    } catch (Exception $e) {}

    // Supprimer tous les gages
    $pdo->exec("DELETE FROM bets");

    // Réactiver FK
    try { $pdo->exec("SET FOREIGN_KEY_CHECKS=1"); } catch(Exception $e) {}

    // Remettre l'auto-increment à 1
    try { $pdo->exec("ALTER TABLE bets AUTO_INCREMENT = 1"); } catch (Exception $e) {}

    // Log admin
    addNotification($pdo, (int)$user['id'],
        "✅ Purge complète : {$count} gage(s) supprimé(s) par l'admin.",
        "admin_config.php"
    );

    echo json_encode(['ok' => true, 'count' => $count]);
} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
?>
