<?php

namespace App\Http\Controllers\HeadquartersDashboard;

use App\Facades\DataTable\DataTableFacade;
use App\Http\Controllers\Controller;
use app\Http\Traits\ApiResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CumulativeMessageRatingStatsController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = DB::table('country_message_rating_reports')->selectRaw("
                province_id,
                province_name,
                SUM(total) as total,
                SUM(listens) as listens,
                SUM(not_listens) as not_listens,
                AVG(review_average) as review_average,
                SUM(action1) as action1,
                SUM(action2) as action2,
                SUM(action3) as action3,
                SUM(action4) as action4,
                SUM(action5) as action5
            ")
            ->groupBy('province_id', 'province_name')
            ->unionAll(DB::table('country_message_rating_reports')->selectRaw("
                0 as province_id,
                'کشوری' as province_name,
                SUM(total),
                SUM(listens),
                SUM(not_listens),
                AVG(review_average),
                SUM(action1),
                SUM(action2),
                SUM(action3),
                SUM(action4),
                SUM(action5)
            "));

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