<?php

namespace App\Http\Controllers\HeadquartersDashboard;

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

class CumulativeKeypressStatsController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = DB::table('country_keypress_reports')->selectRaw("
                province_id,
                province_name,
                SUM(total) as total,
                SUM(key1) as key1,
                SUM(key2) as key2,
                SUM(key3) as key3,
                SUM(key4) as key4,
                SUM(key5) as key5,
                SUM(key6) as key6,
                SUM(key9) as key9,
                SUM(key4_1) as key4_1,
                SUM(key4_2) as key4_2,
                SUM(key5_1) as key5_1,
                SUM(key5_2) as key5_2,
                SUM(key2_1) as key2_1,
                SUM(key2_2) as key2_2,
                SUM(key2_3) as key2_3
            ")
            ->groupBy('province_id', 'province_name')
            ->unionAll(DB::table('country_keypress_reports')->selectRaw("
                    0 as province_id,
                    'کشوری' as province_name,
                    SUM(total),
                    SUM(key1),
                    SUM(key2),
                    SUM(key3),
                    SUM(key4),
                    SUM(key5),
                    SUM(key6),
                    SUM(key9),
                    SUM(key4_1),
                    SUM(key4_2),
                    SUM(key5_1),
                    SUM(key5_2),
                    SUM(key2_1),
                    SUM(key2_2),
                    SUM(key2_3)
            "));

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