<?php

namespace App\Http\Controllers;

use App\Models\Client;
use App\Models\Token;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class BtrcReportController extends Controller
{
    public function activeUser(Request $request)
    {

        $clients = Client::where('clients_status', 'active')->get()->count();

        $data = [
             $clients,
        ];

        return response()->json($data, 200);

    }

    public function thanaLevel(Request $request)
    {
        $thanaLevel = DB::table('clients')
        ->select('thanas.name', DB::raw('COUNT(clients.id) as total_clients'))
        ->join('clientsinfo', 'clients.id', '=', 'clientsinfo.client_id')
        ->join('thanas', 'clientsinfo.thana', '=', 'thanas.id')
        ->where('clients.clients_status', 'active')
        ->groupBy('thanas.name')
        ->pluck('total_clients', 'thanas.name'); // Key = Thana name, Value = Total clients

        return response()->json($thanaLevel, 200);
    }

    public function monthlyTicketGenerated(Request $request)
    {

        $monthlyTicketGenerated = Token::select(
                DB::raw('DATE_FORMAT(created_at, "%Y-%m") as month'),
                DB::raw('COUNT(*) as count')
            )
            ->groupBy('month')
            ->orderBy('month', 'asc')
            ->pluck('count', 'month'); // key = month, value = count

        return response()->json($monthlyTicketGenerated, 200);


    }


    public function averageTimeToResolveTicket(Request $request)
    {
        $allCloseTokens = Token::whereNotNull('close_time')->get();

        $totalTime = 0;
        $tokenCount = $allCloseTokens->count();

        foreach ($allCloseTokens as $token) {
            $createdAt = Carbon::parse($token->created_at);
            $closeTime = Carbon::parse($token->close_time);
            $totalTime += $closeTime->diffInMinutes($createdAt);
        }

        $averageTime = $tokenCount > 0 ? round($totalTime / $tokenCount, 2) : 0;

       $data = [
        'averageTimeInMinutes' => $averageTime,
       ];

       return response()->json($data, 200);
    }

}
