<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\TravelAgent;
use App\Models\User;
use App\Models\Payment;
use App\Models\AiSubscription;
use App\Models\AiUsageLog;
use Illuminate\Http\Request;
use Carbon\Carbon;

class DashboardController extends Controller
{
    public function stats(Request $request)
    {
        // Total counts
        $totalAgents = TravelAgent::count();
        $activeAgents = TravelAgent::where('is_active', true)->count();
        $totalUsers = User::count();
        $activeUsers = User::where('is_active', true)->count();

        // Revenue stats
        $totalRevenue = Payment::where('status', 'captured')->sum('amount');
        $monthlyRevenue = Payment::where('status', 'captured')
            ->where('created_at', '>=', Carbon::now()->subMonth())
            ->sum('amount');

        // Subscription stats
        $subscriptionStats = AiSubscription::selectRaw('
            COUNT(*) as total_subscriptions,
            SUM(CASE WHEN status = "active" THEN 1 ELSE 0 END) as active_subscriptions
        ')->first();

        // Recent AI usage
        $recentAiUsage = AiUsageLog::with('travelAgent')
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get();

        // Top travel agents by revenue
        $topAgents = Payment::where('status', 'captured')
            ->selectRaw('travel_agent_id, SUM(amount) as total_revenue')
            ->with('travelAgent')
            ->groupBy('travel_agent_id')
            ->orderBy('total_revenue', 'desc')
            ->limit(5)
            ->get();

        return response()->json([
            'total_travel_agents' => $totalAgents,
            'active_travel_agents' => $activeAgents,
            'inactive_travel_agents' => $totalAgents - $activeAgents,
            'total_users' => $totalUsers,
            'active_users' => $activeUsers,
            'total_revenue' => (float) $totalRevenue,
            'monthly_revenue' => (float) $monthlyRevenue,
            'total_subscriptions' => $subscriptionStats->total_subscriptions,
            'active_subscriptions' => $subscriptionStats->active_subscriptions,
            'recent_ai_usage' => $recentAiUsage,
            'top_agents_by_revenue' => $topAgents,
        ]);
    }

    public function chartData(Request $request)
    {
        $period = $request->get('period', 'monthly'); // daily, weekly, monthly

        if ($period === 'monthly') {
            $revenueData = Payment::where('status', 'captured')
                ->where('created_at', '>=', Carbon::now()->subMonths(6))
                ->selectRaw('YEAR(created_at) as year, MONTH(created_at) as month, SUM(amount) as revenue')
                ->groupBy('year', 'month')
                ->orderBy('year', 'asc')
                ->orderBy('month', 'asc')
                ->get();

            $usageData = AiUsageLog::where('created_at', '>=', Carbon::now()->subMonths(6))
                ->selectRaw('YEAR(created_at) as year, MONTH(created_at) as month, SUM(word_count) as total_words')
                ->groupBy('year', 'month')
                ->orderBy('year', 'asc')
                ->orderBy('month', 'asc')
                ->get();
        }

        return response()->json([
            'revenue_data' => $revenueData,
            'usage_data' => $usageData,
        ]);
    }
}