<?php

/**
 * Script de vérification de la logique du Pool de commissions
 */

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

use App\Services\PoolService;
use App\Models\Setting;
use App\Models\User;
use App\Models\Order;
use App\Models\Wallet;
use App\Models\WalletTransaction;
use App\Models\PoolShare;
use App\Models\PoolDistribution;

echo "====== VÉRIFICATION LOGIQUE POOL ======\n\n";

$poolService = app(PoolService::class);

// 1. Vérifier les paramètres du pool
echo "1. PARAMÈTRES DU POOL\n";
echo str_repeat("-", 40) . "\n";

$poolPercentage = Setting::where('key', 'pool_percentage')->value('value') ?? 10;
$minimumPurchase = Setting::where('key', 'minimum_monthly_purchase')->value('value') ?? 100000;
$minimumReferrals = Setting::where('key', 'minimum_referrals_for_pool')->value('value') ?? 3;

echo "- Pourcentage du pool: {$poolPercentage}%\n";
echo "- Achat mensuel minimum: " . number_format($minimumPurchase, 0, ',', ' ') . " XOF\n";
echo "- Filleuls minimum requis: {$minimumReferrals}\n\n";

// 2. Statistiques du mois actuel
echo "2. STATISTIQUES DU MOIS ACTUEL (" . now()->format('F Y') . ")\n";
echo str_repeat("-", 40) . "\n";

$stats = $poolService->getPoolStats();
echo "- Ventes mensuelles: " . number_format($stats['monthly_sales'], 0, ',', ' ') . " XOF\n";
echo "- Montant du pool: " . number_format($stats['pool_amount'], 0, ',', ' ') . " XOF\n";
echo "- Distributeurs actifs éligibles: {$stats['active_distributors']}\n\n";

// 3. Récupérer les distributeurs actifs
echo "3. DISTRIBUTEURS ÉLIGIBLES\n";
echo str_repeat("-", 40) . "\n";

$activeDistributors = $poolService->getActiveDistributors();

if (empty($activeDistributors)) {
    echo "Aucun distributeur éligible ce mois-ci.\n";
    echo "\nConditions d'éligibilité:\n";
    echo "- Ventes totales (personnelles + équipe) >= " . number_format($minimumPurchase, 0, ',', ' ') . " XOF\n";
    echo "- Nombre de filleuls actifs >= {$minimumReferrals}\n";
} else {
    foreach ($activeDistributors as $index => $data) {
        $user = $data['user'];
        echo "\n" . ($index + 1) . ". {$user->name} (ID: {$user->id})\n";
        echo "   - Ventes personnelles: " . number_format($data['personal_sales'], 0, ',', ' ') . " XOF\n";
        echo "   - Ventes équipe: " . number_format($data['team_sales'], 0, ',', ' ') . " XOF\n";
        echo "   - Total ventes: " . number_format($data['total_sales'], 0, ',', ' ') . " XOF\n";
        echo "   - Filleuls totaux: " . ($data['total_referrals'] ?? 0) . "\n";
        echo "   - Filleuls avec ventes: " . ($data['active_referrals_with_sales'] ?? 0) . "\n";
    }
}

// 4. Vérifier les commandes ce mois
echo "\n\n4. COMMANDES DU MOIS\n";
echo str_repeat("-", 40) . "\n";

$ordersThisMonth = Order::whereMonth('created_at', now()->month)
    ->whereYear('created_at', now()->year)
    ->selectRaw('status, COUNT(*) as count, SUM(total_amount) as total')
    ->groupBy('status')
    ->get();

if ($ordersThisMonth->isEmpty()) {
    echo "Aucune commande ce mois-ci.\n";
} else {
    foreach ($ordersThisMonth as $order) {
        echo "- Status '{$order->status}': {$order->count} commandes, total: " . number_format($order->total, 0, ',', ' ') . " XOF\n";
    }
}

// 5. Vérifier les distributions précédentes
echo "\n\n5. DERNIÈRES DISTRIBUTIONS\n";
echo str_repeat("-", 40) . "\n";

$lastDistributions = PoolDistribution::orderBy('year', 'desc')
    ->orderBy('month', 'desc')
    ->take(5)
    ->get()
    ->unique(function($item) {
        return $item->month . '-' . $item->year;
    });

if ($lastDistributions->isEmpty()) {
    echo "Aucune distribution effectuée.\n";
} else {
    foreach ($lastDistributions as $dist) {
        $period = \Carbon\Carbon::createFromDate($dist->year, $dist->month, 1)->format('F Y');
        echo "- {$period}: " . number_format($dist->total_pool, 0, ',', ' ') . " XOF (répartis entre {$dist->total_distributors} distributeurs)\n";
    }
}

// 6. Vérifier les PoolShares récents
echo "\n\n6. PARTS DE POOL RÉCENTES\n";
echo str_repeat("-", 40) . "\n";

$recentShares = PoolShare::with('user')
    ->orderBy('created_at', 'desc')
    ->take(5)
    ->get();

if ($recentShares->isEmpty()) {
    echo "Aucune part de pool enregistrée.\n";
} else {
    foreach ($recentShares as $share) {
        $userName = $share->user ? $share->user->name : 'Utilisateur supprimé';
        echo "- {$userName}: " . number_format($share->amount, 0, ',', ' ') . " XOF";
        echo " (" . round($share->percentage, 2) . "%)";
        echo " - Status: {$share->status}";
        echo " - " . $share->period_start->format('m/Y') . "\n";
    }
}

// 7. Vérifier les transactions wallet pool_share
echo "\n\n7. TRANSACTIONS WALLET 'pool_share'\n";
echo str_repeat("-", 40) . "\n";

$poolTransactions = WalletTransaction::where('type', 'pool_share')
    ->orderBy('created_at', 'desc')
    ->take(5)
    ->get();

if ($poolTransactions->isEmpty()) {
    echo "Aucune transaction pool_share trouvée.\n";
} else {
    foreach ($poolTransactions as $tx) {
        echo "- Wallet #{$tx->wallet_id}: " . number_format($tx->amount, 0, ',', ' ') . " XOF";
        echo " - Ref: {$tx->reference}";
        echo " - Status: {$tx->status}";
        echo " - " . $tx->created_at->format('d/m/Y H:i') . "\n";
    }
}

// 8. Vérifier les utilisateurs avec filleuls
echo "\n\n8. TOP 10 UTILISATEURS AVEC LE PLUS DE FILLEULS\n";
echo str_repeat("-", 40) . "\n";

$usersWithReferrals = User::where('is_active', true)
    ->withCount(['referrals' => function($query) {
        $query->where('is_active', true);
    }])
    ->having('referrals_count', '>', 0)
    ->orderByDesc('referrals_count')
    ->take(10)
    ->get();

if ($usersWithReferrals->isEmpty()) {
    echo "Aucun utilisateur n'a de filleuls.\n";
} else {
    foreach ($usersWithReferrals as $index => $user) {
        echo ($index + 1) . ". {$user->name} (ID: {$user->id}): {$user->referrals_count} filleuls\n";
    }
}

// 9. Simulation de distribution
echo "\n\n9. SIMULATION DE DISTRIBUTION\n";
echo str_repeat("-", 40) . "\n";

if (!empty($activeDistributors) && $stats['pool_amount'] > 0) {
    $totalSalesAll = array_sum(array_column($activeDistributors, 'total_sales'));
    
    echo "Montant total du pool: " . number_format($stats['pool_amount'], 0, ',', ' ') . " XOF\n";
    echo "Ventes totales des éligibles: " . number_format($totalSalesAll, 0, ',', ' ') . " XOF\n\n";
    
    echo "Répartition estimée:\n";
    foreach ($activeDistributors as $data) {
        $user = $data['user'];
        $percentage = ($data['total_sales'] / $totalSalesAll) * 100;
        $amount = ($percentage / 100) * $stats['pool_amount'];
        
        echo "- {$user->name}: " . round($percentage, 2) . "% = " . number_format($amount, 0, ',', ' ') . " XOF\n";
    }
} else {
    echo "Impossible de simuler (pas de distributeurs éligibles ou pool vide).\n";
}

echo "\n\n====== FIN DE VÉRIFICATION ======\n";
