<?php

use App\Models\User;
use App\Models\SafetyReport;
use App\Models\UserAppeal;
use App\Models\UserTrustScore;
use Illuminate\Support\Facades\DB;

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

try {
    $user = User::first();
    if (!$user) {
        die("No users found in database.\n");
    }
    $userId = $user->id;
    echo "Testing User ID: $userId\n";

    echo "1. Loading User with relations (ads, trustScore, appeals)...\n";
    $user = User::with(['ads', 'trustScore', 'appeals'])
               ->findOrFail($userId);
    echo "   Success.\n";

    echo "2. Calculating stats...\n";
    $userStats = [
        'total_ads' => $user->ads->count(),
        'active_ads' => $user->ads->where('status', 'active')->count(),
        'pending_ads' => $user->ads->where('status', 'pending')->count(),
        'sold_ads' => $user->ads->where('status', 'sold')->count(),
        'expired_ads' => $user->ads->where('status', 'expired')->count(),
        'rejected_ads' => $user->ads->where('status', 'rejected')->count(),
        'total_views' => $user->adAnalytics()->sum('views'),
        'account_age_days' => now()->diffInDays($user->created_at),
        'last_login' => $user->last_login,
        'is_verified' => $user->is_verified,
        'trust_score' => $user->trustScore ? $user->trustScore->score : 0,
        'safety_reports' => SafetyReport::where('reported_user_id', $userId)->count(),
        'appeals_pending' => UserAppeal::where('user_id', $userId)
                                   ->where('status', 'pending')
                                   ->count()
    ];
    echo "   Success.\n";

    echo "3. Fetching recent reports...\n";
    $recentReports = SafetyReport::where('reported_user_id', $userId)
                               ->with('reporter')
                               ->latest()
                               ->take(5)
                               ->get();
    echo "   Success.\n";

    echo "4. Fetching user ads...\n";
    $userAds = $user->ads()
                   ->select('id', 'title', 'status', 'price', 'currency', 'created_at')
                   ->orderBy('created_at', 'desc')
                   ->take(10)
                   ->get();
    echo "   Success.\n";

    echo "\nALL CHECKS PASSED.\n";

} catch (\Throwable $e) {
    echo "\nCRASHED!\n";
    echo "Error Message: " . $e->getMessage() . "\n";
    echo "Location: " . $e->getFile() . " on line " . $e->getLine() . "\n";
}
