<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Call;
use App\Models\WalletTransaction;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Carbon;

class AdminDashboardController extends Controller
{
    public function index()
    {
        // User stats
        $totalUsers = User::count();
        $activeUsers = User::where('status', 'active')->count();
        $newUsersToday = User::whereDate('created_at', Carbon::today())->count();
        $recentUsers = User::latest()->take(5)->get();

        // Call stats
        $totalCalls = Call::count();
        $todayCalls = Call::whereDate('date_time', Carbon::today())->count();
        $thisWeekCalls = Call::whereBetween('date_time', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])->count();
        $thisMonthCalls = Call::whereMonth('date_time', Carbon::now()->month)->count();

        // Revenue stats
        $totalRevenue = WalletTransaction::where('type', 'credit')->sum('amount');
        $todayRevenue = WalletTransaction::where('type', 'credit')
            ->whereDate('created_at', Carbon::today())->sum('amount');
        $thisMonthRevenue = WalletTransaction::where('type', 'credit')
            ->whereMonth('created_at', Carbon::now()->month)->sum('amount');

        // User growth data for charts (last 30 days)
        $userGrowthData = $this->getUserGrowthData();
        $callVolumeData = $this->getCallVolumeData();
        $revenueData = $this->getRevenueData();

        // Recent transactions
        $recentTransactions = WalletTransaction::with('user')
            ->latest()
            ->take(10)
            ->get();

        return view('admin.dashboard', compact(
            'totalUsers',
            'activeUsers',
            'newUsersToday',
            'recentUsers',
            'totalCalls',
            'todayCalls',
            'thisWeekCalls',
            'thisMonthCalls',
            'totalRevenue',
            'todayRevenue',
            'thisMonthRevenue',
            'userGrowthData',
            'callVolumeData',
            'revenueData',
            'recentTransactions'
        ));
    }

    private function getUserGrowthData()
    {
        $startDate = Carbon::now()->subDays(29)->startOfDay();
        $endDate = Carbon::now()->endOfDay();
        
        $userGrowth = User::whereBetween('created_at', [$startDate, $endDate])
            ->selectRaw('DATE(created_at) as date, COUNT(*) as count')
            ->groupBy('date')
            ->orderBy('date')
            ->get()
            ->keyBy('date');

        $labels = [];
        $data = [];
        
        for ($i = 0; $i < 30; $i++) {
            $day = Carbon::now()->subDays(29 - $i)->format('Y-m-d');
            $labels[] = Carbon::parse($day)->format('d M');
            $data[] = $userGrowth->get($day)->count ?? 0;
        }

        return ['labels' => $labels, 'data' => $data];
    }

    private function getCallVolumeData()
    {
        $startDate = Carbon::now()->subDays(29)->startOfDay();
        $endDate = Carbon::now()->endOfDay();
        
        $callVolume = Call::whereBetween('date_time', [$startDate, $endDate])
            ->selectRaw('DATE(date_time) as date, COUNT(*) as count')
            ->groupBy('date')
            ->orderBy('date')
            ->get()
            ->keyBy('date');

        $labels = [];
        $data = [];
        
        for ($i = 0; $i < 30; $i++) {
            $day = Carbon::now()->subDays(29 - $i)->format('Y-m-d');
            $labels[] = Carbon::parse($day)->format('d M');
            $data[] = $callVolume->get($day)->count ?? 0;
        }

        return ['labels' => $labels, 'data' => $data];
    }

    private function getRevenueData()
    {
        $startDate = Carbon::now()->subDays(29)->startOfDay();
        $endDate = Carbon::now()->endOfDay();
        
        $revenue = WalletTransaction::where('type', 'credit')
            ->whereBetween('created_at', [$startDate, $endDate])
            ->selectRaw('DATE(created_at) as date, SUM(amount) as total')
            ->groupBy('date')
            ->orderBy('date')
            ->get()
            ->keyBy('date');

        $labels = [];
        $data = [];
        
        for ($i = 0; $i < 30; $i++) {
            $day = Carbon::now()->subDays(29 - $i)->format('Y-m-d');
            $labels[] = Carbon::parse($day)->format('d M');
            $data[] = $revenue->get($day)->total ?? 0;
        }

        return ['labels' => $labels, 'data' => $data];
    }
}
