<?php

namespace App\Services\Cartables;

use App\Facades\DataTable\DataTableFacade;
use App\Models\RoadPatrol;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class RoadPatrolTableService
{
    public function supervisorCartableReport(Request $request, $loadRelations = false)
    {
        $allowedFilters = ['*'];
        $allowedSortings = ['*'];

        $user = auth()->user();
        $query = null;

        if ($user->hasPermissionTo('show-road-patrol-supervise-cartable')) {
            $query = RoadPatrol::query()
                ->select([
                    'province_fa', 'province_id', 'id', 'edare_id', 'edare_name', 'start_time', 'end_time', 'created_at', 'description',
                    'distance', 'vehicle_runtime', 'fuel_consumption', 'stop_points'
                ])
                ->when($loadRelations, fn ($query) => $query->with(['rahdaran:id,name,code', 'cmmsMachines:id,machine_code,car_name,plak_number']));
        }
        elseif ($user->hasPermissionTo('show-road-patrol-supervise-cartable-province')) {
            if (is_null($user->province_id)) {
                return $this->errorResponse('استانی برای شما در سامانه ثبت نشده است!');
            }
            $query = RoadPatrol::query()
                ->select([
                    'province_fa', 'province_id', 'id', 'edare_id', 'edare_name', 'start_time', 'end_time', 'created_at', 'description',
                    'distance', 'vehicle_runtime', 'fuel_consumption', 'stop_points'
                ])
                ->where('province_id', '=', $user->province_id)
                ->when($loadRelations, fn ($query) => $query->with(['rahdaran:id,name,code', 'cmmsMachines:id,machine_code,car_name,plak_number']));
        }

        $data = DataTableFacade::run(
            $query,
            $request,
            allowedFilters: $allowedFilters,
            allowedSortings: $allowedSortings);

        return $data;
    }

    public function operatorCartableReport(Request $request, $loadRelations = false)
    {
        $allowedFilters = ['*'];
        $allowedSortings = ['*'];

        $query = RoadPatrol::query()
            ->select([
                'province_fa', 'province_id', 'id', 'edare_id', 'edare_name', 'start_time', 'end_time', 'created_at', 'description',
                'distance', 'vehicle_runtime', 'fuel_consumption', 'stop_points'
            ])
            ->where('operator_id', '=', auth()->user()->id)
            ->when($loadRelations, fn ($query) => $query->with(['rahdaran:id,name,code', 'cmmsMachines:id,machine_code,car_name,plak_number']));

        $data = DataTableFacade::run(
            $query,
            $request,
            allowedFilters: $allowedFilters,
            allowedSortings: $allowedSortings);

        return $data;
    }

    public function countryActivity(Request $request): array
    {
        $fromDate = $request->from_date ? $request->from_date . ' 00:00:00' : now()->startOfDay()->toDateTimeString();
        $toDate = $request->date_to ? $request->date_to . ' 23:59:59' : now()->endOfDay()->toDateTimeString();

        $activities = DB::select('SELECT
            "کشوری" as province_fa,
            -1 as province_id,
            COUNT(*) tedade,
            SUM(tedad_mavarede_moshede_shode_adi) as tedad_mavarede_moshede_shode_adi,
            SUM(tedad_mavarede_moshede_shode_fori) as tedad_mavarede_moshede_shode_fori,
            SUM(tedad_mavarede_moshede_shode_ani) as tedad_mavarede_moshede_shode_ani,
            SUM(tedad_mavarede_peygiri_shode) as tedad_mavarede_peygiri_shode,
            SUM(tedad_faliyat_sabt_shode) as tedad_faliyat_sabt_shode,
            ROUND(SUM(distance)) as masafat_tey_shode
            FROM (SELECT 
            province_id,
            province_fa,
            distance,
            (SELECT COUNT(*)  FROM `observed_items` oi WHERE rp.`id`= oi.road_patrol_id AND priority = 1) AS tedad_mavarede_moshede_shode_adi,
            (SELECT COUNT(*)  FROM `observed_items` oi WHERE rp.`id`= oi.road_patrol_id AND priority = 2) AS tedad_mavarede_moshede_shode_fori,
            (SELECT COUNT(*)  FROM `observed_items` oi WHERE rp.`id`= oi.road_patrol_id AND priority = 3) AS tedad_mavarede_moshede_shode_ani,
            (SELECT COUNT(*) FROM `observed_items` oii WHERE rp.`id`= oii.road_patrol_id AND oii.road_item_id IS NOT NULL AND priority IS NOT NULL) AS tedad_mavarede_peygiri_shode,
            (SELECT COUNT(*) FROM `observed_items` oii WHERE rp.`id`= oii.road_patrol_id AND oii.road_item_id IS NOT NULL AND priority IS NULL) AS tedad_faliyat_sabt_shode
            FROM `road_patrols` rp where rp.start_time BETWEEN "'.$fromDate.'" AND "'.$toDate.'") temp
            union
            SELECT
            province_fa,
            province_id,
            COUNT(*) tedade,            
            SUM(tedad_mavarede_moshede_shode_adi) as tedad_mavarede_moshede_shode_adi,
            SUM(tedad_mavarede_moshede_shode_fori) as tedad_mavarede_moshede_shode_fori,
            SUM(tedad_mavarede_moshede_shode_ani) as tedad_mavarede_moshede_shode_ani,
            SUM(tedad_mavarede_peygiri_shode) as tedad_mavarede_peygiri_shode,
            SUM(tedad_faliyat_sabt_shode) as tedad_faliyat_sabt_shode,
            ROUND(SUM(distance)) as masafat_tey_shode
            FROM (SELECT 
            province_id,
            province_fa,
            distance,
            (SELECT COUNT(*)  FROM `observed_items` oi WHERE rp.`id`= oi.road_patrol_id AND priority = 1) AS tedad_mavarede_moshede_shode_adi,
            (SELECT COUNT(*)  FROM `observed_items` oi WHERE rp.`id`= oi.road_patrol_id AND priority = 2) AS tedad_mavarede_moshede_shode_fori,
            (SELECT COUNT(*)  FROM `observed_items` oi WHERE rp.`id`= oi.road_patrol_id AND priority = 3) AS tedad_mavarede_moshede_shode_ani,
            (SELECT COUNT(*) FROM `observed_items` oii WHERE rp.`id`= oii.road_patrol_id AND oii.road_item_id IS NOT NULL AND priority IS NOT NULL) AS tedad_mavarede_peygiri_shode,
            (SELECT COUNT(*) FROM `observed_items` oii WHERE rp.`id`= oii.road_patrol_id AND oii.road_item_id IS NOT NULL AND priority IS NULL) AS tedad_faliyat_sabt_shode
            FROM `road_patrols` rp where rp.start_time BETWEEN "'.$fromDate.'" AND "'.$toDate.'") temp 
            GROUP BY province_id'
        );

        return [
            'data' => $activities,
            'fromDate' => $fromDate,
            'toDate' => $toDate
        ];
    }

    public function provinceActivity(Request $request): array
    {
        $fromDate = $request->from_date ? $request->from_date . ' 00:00:00' : now()->startOfDay()->toDateTimeString();
        $toDate = $request->date_to ? $request->date_to . ' 23:59:59' : now()->endOfDay()->toDateTimeString();
        $provinceId = $request->province_id;

        $activities = DB::select(
            'SELECT
            province_fa,
            province_id,
            -1 AS edare_id,
            "استانی" AS edare_name,
            COUNT(*) tedade,
            SUM(tedad_mavarede_moshede_shode_adi) as tedad_mavarede_moshede_shode_adi,
            SUM(tedad_mavarede_moshede_shode_fori) as tedad_mavarede_moshede_shode_fori,
            SUM(tedad_mavarede_moshede_shode_ani) as tedad_mavarede_moshede_shode_ani,
            SUM(tedad_mavarede_peygiri_shode) as tedad_mavarede_peygiri_shode,
            SUM(tedad_faliyat_sabt_shode) as tedad_faliyat_sabt_shode,
            ROUND(SUM(distance)) as masafat_tey_shode
            FROM (SELECT 
            province_id,
            province_fa,
            edare_id,
            edare_name,
            distance,            
            (SELECT COUNT(*)  FROM `observed_items` oi WHERE rp.`id`= oi.road_patrol_id AND priority = 1) AS tedad_mavarede_moshede_shode_adi,
            (SELECT COUNT(*)  FROM `observed_items` oi WHERE rp.`id`= oi.road_patrol_id AND priority = 2) AS tedad_mavarede_moshede_shode_fori,
            (SELECT COUNT(*)  FROM `observed_items` oi WHERE rp.`id`= oi.road_patrol_id AND priority = 3) AS tedad_mavarede_moshede_shode_ani,
            (SELECT COUNT(*) FROM `observed_items` oii WHERE rp.`id`= oii.road_patrol_id AND oii.road_item_id IS NOT NULL AND priority IS NOT NULL) AS tedad_mavarede_peygiri_shode,
            (SELECT COUNT(*) FROM `observed_items` oii WHERE rp.`id`= oii.road_patrol_id AND oii.road_item_id IS NOT NULL AND priority IS NULL) AS tedad_faliyat_sabt_shode
            FROM `road_patrols` rp where rp.province_id = "'.$provinceId.'" AND rp.start_time BETWEEN "'.$fromDate.'" AND "'.$toDate.'") temp 
            UNION
            SELECT
            province_fa,
            province_id,
            edare_id,
            edare_name,
            COUNT(*) tedade,
            SUM(tedad_mavarede_moshede_shode_adi) as tedad_mavarede_moshede_shode_adi,
            SUM(tedad_mavarede_moshede_shode_fori) as tedad_mavarede_moshede_shode_fori,
            SUM(tedad_mavarede_moshede_shode_ani) as tedad_mavarede_moshede_shode_ani,
            SUM(tedad_mavarede_peygiri_shode) as tedad_mavarede_peygiri_shode,
            SUM(tedad_faliyat_sabt_shode) as tedad_faliyat_sabt_shode,
            ROUND(SUM(distance)) as masafat_tey_shode
            FROM (SELECT 
            province_id,
            province_fa,
            edare_id,
            edare_name,
            distance,            
            (SELECT COUNT(*)  FROM `observed_items` oi WHERE rp.`id`= oi.road_patrol_id AND priority = 1) AS tedad_mavarede_moshede_shode_adi,
            (SELECT COUNT(*)  FROM `observed_items` oi WHERE rp.`id`= oi.road_patrol_id AND priority = 2) AS tedad_mavarede_moshede_shode_fori,
            (SELECT COUNT(*)  FROM `observed_items` oi WHERE rp.`id`= oi.road_patrol_id AND priority = 3) AS tedad_mavarede_moshede_shode_ani,
            (SELECT COUNT(*) FROM `observed_items` oii WHERE rp.`id`= oii.road_patrol_id AND oii.road_item_id IS NOT NULL AND priority IS NOT NULL) AS tedad_mavarede_peygiri_shode,
            (SELECT COUNT(*) FROM `observed_items` oii WHERE rp.`id`= oii.road_patrol_id AND oii.road_item_id IS NOT NULL AND priority IS NULL) AS tedad_faliyat_sabt_shode
            FROM `road_patrols` rp where rp.province_id = "'.$provinceId.'" AND rp.start_time BETWEEN "'.$fromDate.'" AND "'.$toDate.'") temp 
            GROUP BY edare_id
            '
        );

        return [
            'data' => $activities,
            'fromDate' => $fromDate,
            'toDate' => $toDate
        ];
    }
}