<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Models\Show;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Inertia\Response;

class DashboardController extends Controller
{
    /**
     * Display the admin dashboard.
     */
    public function __invoke(Request $request): Response
    {
        // Get statistics
        $totalUsers = User::where('role', 'user')->count();
        $totalPartners = User::where('role', 'partner')->count();
        $totalShows = Show::count();
        $activeShows = Show::where('is_active', true)->count();

        // Get user growth (this month vs last month)
        $currentMonthUsers = User::where('role', 'user')
            ->whereMonth('created_at', now()->month)
            ->whereYear('created_at', now()->year)
            ->count();
        $lastMonthUsers = User::where('role', 'user')
            ->whereMonth('created_at', now()->subMonth()->month)
            ->whereYear('created_at', now()->subMonth()->year)
            ->count();
        $userGrowth = $lastMonthUsers > 0
            ? round((($currentMonthUsers - $lastMonthUsers) / $lastMonthUsers) * 100, 1)
            : ($currentMonthUsers > 0 ? 100 : 0);

        // Get partner growth
        $currentMonthPartners = User::where('role', 'partner')
            ->whereMonth('created_at', now()->month)
            ->whereYear('created_at', now()->year)
            ->count();
        $lastMonthPartners = User::where('role', 'partner')
            ->whereMonth('created_at', now()->subMonth()->month)
            ->whereYear('created_at', now()->subMonth()->year)
            ->count();
        $partnerGrowth = $lastMonthPartners > 0
            ? round((($currentMonthPartners - $lastMonthPartners) / $lastMonthPartners) * 100, 1)
            : ($currentMonthPartners > 0 ? 100 : 0);

        // Get active sessions count (users with active sessions in last 24 hours)
        $activeSessions = DB::table('sessions')
            ->where('last_activity', '>=', now()->subDay()->timestamp)
            ->distinct('user_id')
            ->count('user_id');

        // Get recent activity logs
        $recentActivities = ActivityLog::with('user')
            ->latest()
            ->limit(10)
            ->get()
            ->map(function ($log) {
                return [
                    'id' => $log->id,
                    'action' => $log->action,
                    'description' => $log->description,
                    'user' => $log->user ? [
                        'id' => $log->user->id,
                        'name' => $log->user->name,
                        'email' => $log->user->email,
                    ] : null,
                    'created_at' => $log->created_at->toISOString(),
                    'time_ago' => $log->created_at->diffForHumans(),
                ];
            });

        // Get total shows assigned to users
        $totalShowAssignments = DB::table('show_user')->count();

        // Get transaction statistics
        $totalTopups = \App\Models\CoinTransaction::count();
        $successfulTopups = \App\Models\CoinTransaction::where('status', 'success')->count();
        $totalTopupAmount = \App\Models\CoinTransaction::where('status', 'success')->sum('amount');
        $totalTopupFee = \App\Models\CoinTransaction::where('status', 'success')->sum('fee');
        $totalCoinsDistributed = \App\Models\CoinTransaction::where('status', 'success')->sum('coins');

        $totalPurchases = \App\Models\ShowPurchase::count();
        $totalCoinsSpent = \App\Models\ShowPurchase::sum('coin_price');
        $totalPurchaseAmount = $totalCoinsSpent * 1000; // Convert to IDR (1 coin = 1000 IDR)

        // Calculate revenue (topup amount - fees)
        $totalRevenue = $totalTopupAmount - $totalTopupFee;

        return Inertia::render('Admin/Dashboard', [
            'stats' => [
                'totalUsers' => $totalUsers,
                'totalPartners' => $totalPartners,
                'totalShows' => $totalShows,
                'activeShows' => $activeShows,
                'activeSessions' => $activeSessions,
                'totalShowAssignments' => $totalShowAssignments,
                'userGrowth' => $userGrowth,
                'partnerGrowth' => $partnerGrowth,
                'totalTopups' => $totalTopups,
                'successfulTopups' => $successfulTopups,
                'totalTopupAmount' => $totalTopupAmount,
                'totalTopupFee' => $totalTopupFee,
                'totalCoinsDistributed' => $totalCoinsDistributed,
                'totalPurchases' => $totalPurchases,
                'totalCoinsSpent' => $totalCoinsSpent,
                'totalPurchaseAmount' => $totalPurchaseAmount,
                'totalRevenue' => $totalRevenue,
            ],
            'recentActivities' => $recentActivities,
        ]);
    }
}
