<?php

require_once dirname(__DIR__) . '/vendor/autoload.php';
$app = require_once dirname(__DIR__) . '/bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

use App\Models\User;
use App\Models\Rank;
use App\Models\Commission;

// Récupérer tous les utilisateurs (user ET member)
$users = User::whereIn('role', ['user', 'member'])->get();
$ranks = Rank::active()->ordered()->get();

echo "=== ANALYSE DES QUALIFICATIONS RANG ===\n\n";

foreach ($users as $user) {
    echo "Utilisateur: {$user->name} (ID: {$user->id})\n";
    echo "Rang actuel: " . ($user->rank ? $user->rank->name : "Aucun") . "\n";
    
    $personalSales = $user->orders()->sum('total_amount');
    $directReferrals = $user->directReferrals()->count();
    
    echo "- Ventes personnelles: " . number_format($personalSales) . " FCFA\n";
    echo "- Filleuls directs: {$directReferrals}\n";
    
    // Vérifier méthode getTeamSales
    try {
        $teamSales = $user->getTeamSales();
        echo "- Ventes équipe: " . number_format($teamSales) . " FCFA\n";
    } catch (Exception $e) {
        echo "- Ventes équipe: ERREUR - " . $e->getMessage() . "\n";
    }
    
    // Vérifier méthode getTeamSize
    try {
        $teamSize = $user->getTeamSize();
        echo "- Taille équipe: {$teamSize}\n";
    } catch (Exception $e) {
        echo "- Taille équipe: ERREUR - " . $e->getMessage() . "\n";
    }
    
    echo "\n";
    
    // Vérifier la qualification pour chaque rang
    echo "Qualifications:\n";
    foreach ($ranks as $rank) {
        $qualified = $rank->checkQualification($user);
        $status = $qualified ? "✓ QUALIFIÉ" : "✗ Non qualifié";
        echo "  - {$rank->name} (Niveau {$rank->level}): {$status}\n";
        echo "    Requis: Ventes perso >= {$rank->min_personal_sales}, Équipe >= {$rank->min_team_sales}, Filleuls >= {$rank->min_direct_referrals}, Taille >= {$rank->min_team_size}\n";
    }
    
    echo "\n" . str_repeat("-", 60) . "\n\n";
}

// Vérifier les commissions de rang existantes
echo "=== COMMISSIONS RANG EXISTANTES ===\n\n";
$rankBonuses = Commission::where('type', 'rank_bonus')->get();
foreach ($rankBonuses as $bonus) {
    $user = User::find($bonus->user_id);
    echo "- User ID {$bonus->user_id} ({$user->name}): {$bonus->amount} FCFA - {$bonus->description} - Statut: {$bonus->status}\n";
}

if ($rankBonuses->isEmpty()) {
    echo "Aucune commission de rang trouvée.\n";
}
