<?php
/**
 * Script de debug pour le système AMM
 */

require_once __DIR__ . '/../vendor/autoload.php';

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

use App\Models\Order;
use App\Models\User;
use App\Services\AMMService;
use Carbon\Carbon;

echo "=== Debug AMM - Janvier 2026 ===\n\n";

// 1. Récupérer les commandes de janvier 2026
$monthStart = Carbon::now()->startOfMonth();
$monthEnd = Carbon::now()->endOfMonth();

echo "Période: {$monthStart->format('Y-m-d')} au {$monthEnd->format('Y-m-d')}\n\n";

// 2. Toutes les commandes du mois
$orders = Order::whereBetween('created_at', [$monthStart, $monthEnd])
    ->get(['id', 'user_id', 'total', 'status', 'payment_status', 'created_at', 'order_type']);

echo "=== Toutes les commandes de janvier 2026 ===\n";
echo "Total: " . $orders->count() . " commandes\n\n";

foreach ($orders as $order) {
    $user = User::find($order->user_id);
    echo "Commande #{$order->id}:\n";
    echo "  - User: " . ($user ? $user->name : 'N/A') . " (ID: {$order->user_id})\n";
    echo "  - Total: " . number_format($order->total, 0, ',', ' ') . " XOF\n";
    echo "  - Status: {$order->status}\n";
    echo "  - Payment Status: {$order->payment_status}\n";
    echo "  - Order Type: {$order->order_type}\n";
    echo "  - Date: {$order->created_at}\n";
    echo "\n";
}

// 3. Commandes PAYÉES
$paidOrders = Order::whereBetween('created_at', [$monthStart, $monthEnd])
    ->where(function($q) {
        $q->where('payment_status', 'paid')
          ->orWhereIn('status', ['delivered', 'completed']);
    })
    ->get();

echo "=== Commandes PAYÉES (pour AMM) ===\n";
echo "Total: " . $paidOrders->count() . " commandes payées\n\n";

// 4. Tester avec un utilisateur spécifique
echo "=== Test AMM pour chaque utilisateur avec commandes ===\n\n";

$userIds = $orders->pluck('user_id')->unique();
$ammService = new AMMService();

// Forcer le refresh des données
\Illuminate\Support\Facades\DB::enableQueryLog();

foreach ($userIds as $userId) {
    $user = User::find($userId);
    if (!$user) continue;
    
    $status = $ammService->getAmmStatus($user);
    
    echo "Utilisateur: {$user->name} (ID: {$user->id})\n";
    echo "  - Achats personnels: " . number_format($status['progress']['personal_purchases'], 0, ',', ' ') . " XOF\n";
    echo "  - Ventes boutique: " . number_format($status['progress']['shop_sales'], 0, ',', ' ') . " XOF\n";
    echo "  - Total: " . number_format($status['progress']['total'], 0, ',', ' ') . " XOF\n";
    echo "  - Requis: " . number_format($status['progress']['required'], 0, ',', ' ') . " XOF\n";
    echo "  - Pourcentage: " . number_format($status['progress']['percentage'], 1) . "%\n";
    echo "  - AMM Active: " . ($status['is_active'] ? 'OUI' : 'NON') . "\n";
    echo "  - Exonéré: " . ($status['is_exempted'] ? 'OUI' : 'NON') . "\n";
    echo "  - Avance payée: " . ($status['next_month_advance_paid'] ? 'OUI' : 'NON') . "\n";
    echo "  - Active jusqu'au: " . ($status['active_until_formatted'] ?? 'N/A') . "\n";
    echo "  - Avance jusqu'au: " . ($status['advance_paid_until_formatted'] ?? 'N/A') . "\n";
    echo "\n";
}

echo "=== Fin du debug ===\n";

// Debug des commandes regular avec total = 0
echo "\n=== Debug commandes regular avec total = 0 ===\n";
$regularOrders = Order::where('order_type', 'regular')
    ->whereBetween('created_at', [$monthStart, $monthEnd])
    ->get();

foreach ($regularOrders->take(3) as $order) {
    echo "\nCommande #{$order->id}:\n";
    echo "  - total: {$order->total}\n";
    echo "  - total_amount: " . ($order->total_amount ?? 'NULL') . "\n";
    echo "  - subtotal: " . ($order->subtotal ?? 'NULL') . "\n";
    
    // Vérifier les items
    $items = \App\Models\OrderItem::where('order_id', $order->id)->get();
    echo "  - Items: " . $items->count() . "\n";
    foreach ($items as $item) {
        echo "    * Produit ID {$item->product_id}: Qty {$item->quantity} x {$item->price} = " . ($item->quantity * $item->price) . " XOF\n";
    }
    $itemsTotal = $items->sum(function($item) { return $item->quantity * $item->price; });
    echo "  - Total calculé depuis items: {$itemsTotal} XOF\n";
}
