<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Lead;
use App\Models\Offerwall;
use App\Models\User;
use App\Models\Withdrawal;
use App\Support\AdminAnalytics;
use Illuminate\Http\Request;

class HomeController extends Controller
{
    public function index(Request $request)
    {
        $range = (int) $request->query('range', 14);

        $range = in_array($range, [7, 14, 30], true) ? $range : 14;

        $analytics = [
            'daily' => AdminAnalytics::dailySeries($range),
            'cumulative' => AdminAnalytics::revenueCumulative($range),
            'cashouts' => AdminAnalytics::cashoutBreakdown(),
            'providers' => AdminAnalytics::topProviders(),
            'countries' => AdminAnalytics::topCountries(),
            'users' => AdminAnalytics::userBreakdown(),
            'lead_status' => AdminAnalytics::leadStatus($range),
            'weekday' => AdminAnalytics::weekdayActivity(),
            'headline' => AdminAnalytics::headline(),
            'range' => $range,
        ];

        $profit = [
            'total' => Lead::sum('payout'),
            'today' => Lead::whereDate('created_at', today())->sum('payout'),
            'this_month' => Lead::whereMonth('created_at', now()->month)
                ->whereYear('created_at', now()->year)
                ->sum('payout'),
        ];

        $users = [
            'count' => User::count(),
            'new' => User::whereDate('created_at', today())->count(),
            'active' => User::where('last_seen_at', '>=', now()->subDay())->count(),
            'banned' => User::where('is_banned', true)->count(),
        ];

        $withdrawals = [
            'count' => Withdrawal::count(),
            'pending' => Withdrawal::where('status', 'pending')->count(),
            'paid' => Withdrawal::where('status', 'approved')->count(),
            'rejected' => Withdrawal::where('status', 'rejected')->count(),
        ];

        $operations = [
            'active_offerwalls' => Offerwall::where('is_active', true)->count(),
            'total_offerwalls' => Offerwall::count(),
            'leads_today' => Lead::whereDate('created_at', today())->count(),
            'latest_leads' => Lead::with('user')->latest()->take(6)->get(),
            'latest_withdrawals' => Withdrawal::with('user')->latest()->take(6)->get(),
            'top_users' => User::where('is_admin', false)->orderByDesc('total_points')->take(5)->get(),
        ];

        return view('admin.home', compact('profit', 'users', 'withdrawals', 'operations', 'analytics'));
    }
}
