<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Api\BaseController;
use App\Models\Transaction;
use App\Models\User;
use App\Models\Wallet;
use App\Models\Payment;
use App\Models\Setting;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AdminDashboardController extends BaseController
{
    public function index(Request $request): JsonResponse
    {
        $today = now()->startOfDay();

        $stats = [
            'total_users' => User::count(),
            'active_users' => User::where('status', 'active')->count(),
            'new_users_today' => User::whereDate('created_at', $today)->count(),
            'total_transactions' => Transaction::count(),
            'successful_transactions' => Transaction::where('status', 'successful')->count(),
            'failed_transactions' => Transaction::where('status', 'failed')->count(),
            'total_revenue' => Transaction::where('status', 'successful')->sum('fee'),
            'today_revenue' => Transaction::where('status', 'successful')->whereDate('created_at', $today)->sum('fee'),
            'total_volume' => Transaction::where('status', 'successful')->sum('total_amount'),
            'today_volume' => Transaction::where('status', 'successful')->whereDate('created_at', $today)->sum('total_amount'),
            'total_wallet_balance' => Wallet::sum('balance'),
            'total_funded' => Payment::where('status', 'successful')->sum('amount'),
            'pending_transactions' => Transaction::where('status', 'pending')->count(),
            'refunded_amount' => Transaction::where('status', 'refunded')->sum('total_amount'),
        ];

        $recentTransactions = Transaction::with('user')
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get();

        $recentUsers = User::orderBy('created_at', 'desc')->limit(10)->get();

        return $this->successResponse([
            'stats' => $stats,
            'recent_transactions' => $recentTransactions,
            'recent_users' => $recentUsers,
        ]);
    }
}
