<?php
/**
 * Test manuel du calcul des commissions
 */

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

use App\Models\Order;
use App\Models\User;
use App\Services\MLMService;
use Illuminate\Support\Facades\Log;

echo "=== TEST CALCUL COMMISSIONS MLM ===\n\n";

// Récupérer la dernière commande d'investissement payée avec sponsor
$order = Order::where('order_type', 'investment')
    ->where('payment_status', 'paid')
    ->whereHas('user', function($q) {
        $q->whereNotNull('sponsor_id');
    })
    ->orderBy('created_at', 'desc')
    ->first();

if (!$order) {
    echo "❌ Aucune commande d'investissement payée avec sponsor trouvée\n";
    exit;
}

echo "📦 Commande: #{$order->order_number}\n";
echo "   - ID: {$order->id}\n";
echo "   - Total: {$order->total_amount} XOF\n";
echo "   - Payment Status: {$order->payment_status}\n\n";

$user = $order->user;
echo "👤 Acheteur: {$user->name} (ID: {$user->id})\n";
echo "   - Sponsor ID: {$user->sponsor_id}\n\n";

// Vérifier le parrain N1
$sponsor1 = User::find($user->sponsor_id);
if ($sponsor1) {
    echo "👤 Parrain N1: {$sponsor1->name} (ID: {$sponsor1->id})\n";
    echo "   - is_active: " . ($sponsor1->is_active ? 'OUI' : 'NON') . "\n";
    echo "   - subscription_paid: " . ($sponsor1->subscription_paid ? 'OUI' : 'NON') . "\n";
    echo "   - has_paid_investment_product: " . ($sponsor1->has_paid_investment_product ? 'OUI' : 'NON') . "\n";
    
    // Vérifier si peut recevoir commissions
    $canReceive = $sponsor1->is_active && ($sponsor1->subscription_paid || $sponsor1->has_paid_investment_product);
    echo "   - Peut recevoir commissions: " . ($canReceive ? 'OUI' : 'NON') . "\n\n";
    
    // Parrain N2
    if ($sponsor1->sponsor_id) {
        $sponsor2 = User::find($sponsor1->sponsor_id);
        if ($sponsor2) {
            echo "👤 Parrain N2: {$sponsor2->name} (ID: {$sponsor2->id})\n";
            echo "   - is_active: " . ($sponsor2->is_active ? 'OUI' : 'NON') . "\n";
            echo "   - subscription_paid: " . ($sponsor2->subscription_paid ? 'OUI' : 'NON') . "\n";
            echo "   - has_paid_investment_product: " . ($sponsor2->has_paid_investment_product ? 'OUI' : 'NON') . "\n";
        }
    }
}

echo "\n--- EXÉCUTION DU CALCUL DES COMMISSIONS ---\n\n";

try {
    $mlmService = new MLMService();
    $commissions = $mlmService->calculateCommissions($order);
    
    echo "✅ Résultat: " . count($commissions) . " commissions créées\n\n";
    
    foreach ($commissions as $comm) {
        $recipient = User::find($comm->user_id);
        echo "   💰 Niveau {$comm->level}: {$comm->amount} XOF -> {$recipient->name}\n";
    }
    
    // Vérifier les transactions wallet
    echo "\n--- TRANSACTIONS WALLET CRÉÉES ---\n\n";
    $transactions = \App\Models\WalletTransaction::where('type', 'commission')
        ->orderBy('created_at', 'desc')
        ->take(5)
        ->get();
    
    foreach ($transactions as $txn) {
        $txnUser = User::find($txn->user_id);
        echo "   💳 {$txn->amount} XOF - {$txnUser->name} - {$txn->description}\n";
    }
    
} catch (\Exception $e) {
    echo "❌ ERREUR: " . $e->getMessage() . "\n";
    echo "   File: " . $e->getFile() . ":" . $e->getLine() . "\n";
    echo "   Trace:\n" . $e->getTraceAsString() . "\n";
}

echo "\n=== FIN DU TEST ===\n";
