<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\AiUsageLog;
use App\Models\TravelAgent;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class AiUsageController extends Controller
{
    public function index(Request $request)
    {
        $query = AiUsageLog::with(['travelAgent', 'aiKey']);

        // Date filtering
        if ($request->has('start_date') && $request->has('end_date')) {
            $query->whereBetween('created_at', [
                Carbon::parse($request->start_date)->startOfDay(),
                Carbon::parse($request->end_date)->endOfDay()
            ]);
        }

        // Travel Agent filter
        if ($request->has('travel_agent_id') && $request->travel_agent_id) {
            $query->where('travel_agent_id', $request->travel_agent_id);
        }

        $usageLogs = $query->orderBy('created_at', 'desc')
            ->paginate(20);

        return response()->json($usageLogs);
    }

    public function analytics(Request $request)
    {
        $period = $request->get('period', 'monthly');

        // Total usage statistics
        $totalStats = AiUsageLog::selectRaw('
            COUNT(*) as total_requests,
            SUM(word_count) as total_words,
            SUM(cost) as total_cost,
            AVG(word_count) as avg_words_per_request
        ')->first();

        // Usage by travel agent
        $usageByAgent = AiUsageLog::selectRaw('
            travel_agent_id,
            COUNT(*) as request_count,
            SUM(word_count) as total_words,
            SUM(cost) as total_cost
        ')
        ->with('travelAgent')
        ->groupBy('travel_agent_id')
        ->orderBy('total_words', 'desc')
        ->get();

        // Monthly usage trend
        if ($period === 'monthly') {
            $usageTrend = 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, COUNT(*) as request_count')
                ->groupBy('year', 'month')
                ->orderBy('year', 'asc')
                ->orderBy('month', 'asc')
                ->get();
        }

        return response()->json([
            'total_stats' => $totalStats,
            'usage_by_agent' => $usageByAgent,
            'usage_trend' => $usageTrend ?? [],
        ]);
    }

    public function topUsers(Request $request)
    {
        $topUsers = DB::table('ai_usage_logs')
            ->join('users', 'ai_usage_logs.travel_agent_id', '=', 'users.travel_agent_id')
            ->selectRaw('
                users.name,
                users.email,
                COUNT(ai_usage_logs.id) as request_count,
                SUM(ai_usage_logs.word_count) as total_words
            ')
            ->groupBy('users.id', 'users.name', 'users.email')
            ->orderBy('total_words', 'desc')
            ->limit(10)
            ->get();

        return response()->json($topUsers);
    }
}