<?php

namespace App\Http\Controllers\Admin;

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

class AnalyticsController extends Controller
{
    public function index()
    {
        // User statistics
        $totalUsers = User::count();
        $activeUsers = User::where('status', 'active')->count();
        $newUsersToday = User::whereDate('created_at', Carbon::today())->count();
        $newUsersThisWeek = User::whereBetween('created_at', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])->count();
        
        // Call statistics
        $totalCalls = Call::count();
        $activeCalls = Call::where('status', 'completed')->count();
        $callsToday = Call::whereDate('date_time', Carbon::today())->count();
        $callsThisWeek = Call::whereBetween('date_time', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])->count();
        
        // API requests (mock data for now)
        $totalApiRequests = 12400;
        $apiRequestsToday = 1200;
        
        // Success rate
        $successfulCalls = Call::where('status', 'completed')->count();
        $successRate = $totalCalls > 0 ? round(($successfulCalls / $totalCalls) * 100, 1) : 0;
        
        // User growth data for charts
        $userGrowthData = $this->getUserGrowthData();
        $callVolumeData = $this->getCallVolumeData();
        $geographicData = $this->getGeographicData();
        $peakHoursData = $this->getPeakHoursData();
        
        return view('admin.analytics.index', compact(
            'totalUsers',
            'activeUsers',
            'newUsersToday',
            'newUsersThisWeek',
            'totalCalls',
            'activeCalls',
            'callsToday',
            'callsThisWeek',
            'totalApiRequests',
            'apiRequestsToday',
            'successRate',
            'userGrowthData',
            'callVolumeData',
            'geographicData',
            'peakHoursData'
        ));
    }
    
    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 getGeographicData()
    {
        // Mock geographic data - in real app, this would come from user location data
        return [
            'labels' => ['India', 'USA', 'UK', 'Canada', 'Australia'],
            'data' => [65, 15, 10, 5, 5]
        ];
    }
    
    private function getPeakHoursData()
    {
        // Get call distribution by hour
        $peakHours = Call::selectRaw('HOUR(date_time) as hour, COUNT(*) as count')
            ->whereNotNull('date_time')
            ->groupBy('hour')
            ->orderBy('hour')
            ->get()
            ->keyBy('hour');

        $labels = [];
        $data = [];
        
        for ($i = 0; $i < 24; $i++) {
            $labels[] = sprintf('%02d:00', $i);
            $data[] = $peakHours->get($i)->count ?? 0;
        }

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