<?php
/**
 * Script de test pour vérifier la fonctionnalité Analytics
 * Exécuter: php tools/test_analytics.php
 */

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

use App\Models\User;
use App\Models\Order;
use App\Models\MonthlySalesTracking;
use App\Models\Product;
use App\Models\Review;
use App\Models\Setting;

echo "=== TEST ANALYTICS DASHBOARD ===\n\n";

// Test 1: Statistiques principales
echo "1. STATISTIQUES PRINCIPALES\n";
echo "----------------------------\n";

$totalMembers = User::where('role', 'member')->count();
$activeMembers = User::where('role', 'member')->where('is_active', true)->count();
echo "Membres totaux: {$totalMembers}\n";
echo "Membres actifs: {$activeMembers}\n";

// Test 2: Données AMM
echo "\n2. DONNÉES AMM (ACHAT MENSUEL MINIMUM)\n";
echo "--------------------------------------\n";

$ammRequired = floatval(Setting::get('minimum_monthly_purchase', 50000));
$currentMonth = now()->month;
$currentYear = now()->year;

echo "AMM requis: " . number_format($ammRequired, 0, ',', ' ') . " XOF\n";
echo "Mois en cours: " . now()->format('F Y') . "\n";

$membersWithAmm = MonthlySalesTracking::where('year', $currentYear)
    ->where('month', $currentMonth)
    ->where('has_met_amm', true)
    ->count();

echo "Membres avec AMM validé: {$membersWithAmm}\n";

$membersWithoutAmm = User::where('role', 'member')
    ->where('is_active', true)
    ->whereNotIn('id', function($query) use ($currentYear, $currentMonth) {
        $query->select('user_id')
            ->from('monthly_sales_tracking')
            ->where('year', $currentYear)
            ->where('month', $currentMonth)
            ->where('has_met_amm', true);
    })->count();

echo "Membres sans AMM: {$membersWithoutAmm}\n";

// Test 3: Réseau MLM
echo "\n3. RÉSEAU MLM\n";
echo "-------------\n";

$totalSponsors = User::where('role', 'member')->whereHas('referrals')->count();
echo "Parrains (avec filleuls): {$totalSponsors}\n";

$membersWithSponsor = User::where('role', 'member')->whereNotNull('sponsor_id')->count();
echo "Membres avec parrain: {$membersWithSponsor}\n";

$membersWithoutSponsor = User::where('role', 'member')->whereNull('sponsor_id')->count();
echo "Membres sans parrain: {$membersWithoutSponsor}\n";

// Test 4: Produits
echo "\n4. PRODUITS\n";
echo "-----------\n";

$totalViews = Product::sum('views_count');
$totalSales = Product::sum('sales_count');
$avgRating = Product::where('reviews_count', '>', 0)->avg('rating');

echo "Vues totales: " . number_format($totalViews) . "\n";
echo "Ventes totales: " . number_format($totalSales) . "\n";
echo "Note moyenne: " . round($avgRating ?? 0, 2) . "/5\n";

$lowRated = Product::where('is_active', true)
    ->where('reviews_count', '>', 0)
    ->where('rating', '<', 3)
    ->count();
echo "Produits mal notés (<3): {$lowRated}\n";

// Test 5: Liste des membres sans AMM (top 10)
echo "\n5. TOP 10 MEMBRES SANS AMM À CONTACTER\n";
echo "--------------------------------------\n";

$membersToContact = User::where('role', 'member')
    ->where('is_active', true)
    ->whereNotIn('id', function($q) use ($currentYear, $currentMonth) {
        $q->select('user_id')
            ->from('monthly_sales_tracking')
            ->where('year', $currentYear)
            ->where('month', $currentMonth)
            ->where('has_met_amm', true);
    })
    ->limit(10)
    ->get();

foreach ($membersToContact as $index => $member) {
    $tracking = MonthlySalesTracking::where('user_id', $member->id)
        ->where('year', $currentYear)
        ->where('month', $currentMonth)
        ->first();
    
    $totalPurchase = $tracking ? $tracking->total_purchase_amount : 0;
    $remaining = max(0, $ammRequired - $totalPurchase);
    $percentage = min(100, round(($totalPurchase / $ammRequired) * 100, 1));
    
    echo ($index + 1) . ". {$member->name}\n";
    echo "   Email: {$member->email}\n";
    echo "   Acheté: " . number_format($totalPurchase, 0, ',', ' ') . " XOF ({$percentage}%)\n";
    echo "   Restant: " . number_format($remaining, 0, ',', ' ') . " XOF\n\n";
}

echo "\n=== FIN DU TEST ===\n";
echo "L'onglet Analytics est accessible à: /admin/analytics\n";
echo "Onglets disponibles:\n";
echo "  - ?tab=overview   : Vue d'ensemble\n";
echo "  - ?tab=members    : Analyse des membres\n";
echo "  - ?tab=products   : Analyse des produits (vues, notes)\n";
echo "  - ?tab=amm        : Suivi AMM (membres sans achat minimum)\n";
echo "  - ?tab=network    : Réseau MLM (parrains, filleuls)\n";
echo "  - ?tab=ai         : IA & Insights (rappels, recommandations)\n";
