<?php

namespace App\Http\Controllers\HeadquartersDashboard;

use App\Facades\DataTable\DataTableFacade;
use App\Http\Controllers\Controller;
use App\Models\CountryCallsReport;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CumulativeCentersStatsController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = DB::table('country_calls_reports')
            ->selectRaw("
                province_id,
                province_name,
                SUM(total) as total,
                SUM(route_to_teh4) as route_to_teh4,
                SUM(route_to_teh5) as route_to_teh5,
                SUM(route_to_os4) as route_to_os4,
                SUM(route_to_os5) as route_to_os5,
                SUM(answered) as answered,
                SUM(answered_over10) as answered_over10,
                SUM(missed) as missed,
                SUM(dnd) as dnd,
                SUM(transferred) as transferred,
                SUM(talked_to_operator) as talked_to_operator,
                AVG(average_calls_time) as average_calls_time,
                SUM(fails) as fails
            ")
            ->groupBy('province_id', 'province_name')
            ->unionAll(
                DB::table('country_calls_reports')
                    ->selectRaw("
                    0 as province_id,
                    'کشوری' as province_name,
                    SUM(total),
                    SUM(route_to_teh4),
                    SUM(route_to_teh5),
                    SUM(route_to_os4),
                    SUM(route_to_os5),
                    SUM(answered),
                    SUM(answered_over10),
                    SUM(missed),
                    SUM(dnd),
                    SUM(transferred),
                    SUM(talked_to_operator),
                    AVG(average_calls_time),
                    SUM(fails)
                ")
            );

        return response()->json(
            DataTableFacade::run(
                $query,
                $request,
                allowedFilters: ['*'],
                allowedSortings: ['*'])
        );
    }
}
