<?php

namespace App\Services\Cartables;

use App\Facades\DataTable\DataTableFacade;
use App\Http\Traits\ApiResponse;
use App\Models\Province;
use App\Models\SafetyAndPrivacy;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SafetyAndPrivacyTableService
{
    use ApiResponse;

    public function dataTable(Request $request, $loadRelations = false)
    {
        $user = auth()->user();

        $fields = ['id','lat','lon','province_id','province_fa','city_id','city_fa','edare_shahri_id','edare_shahri_name',
            'recognize_picture','action_picture','operator_id','operator_name','way_id','created_at','updated_at','step',
            'info_id','info_fa','activity_date_time', 'action_picture_document_upload_date', 'judiciary_document_upload_date',
            'step_fa', 'axis_type_id', 'axis_type_name'
        ];

        if ($user->hasPermissionTo('show-safety-and-privacy-operator-cartable')) {
            $query = SafetyAndPrivacy::query()->select($fields);
        }
        elseif ($user->hasPermissionTo('show-safety-and-privacy-operator-cartable-province')) {
            if (is_null($user->province_id)) {
                return $this->errorResponse('استانی برای شما در سامانه ثبت نشده است!');
            }

            $query = SafetyAndPrivacy::query()->where('province_id', '=', $user->province_id)->select($fields);
        }
        elseif ($user->hasPermissionTo('show-safety-and-privacy-operator-cartable-edarate-shahri')) {
            if (is_null($user->edarate_shahri_id)) {
                return $this->errorResponse('اداره ای برای شما در سامانه ثبت نشده است!');
            }

            $query = SafetyAndPrivacy::query()->where('edare_shahri_id', '=', $user->edarate_shahri_id);
        }

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

    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();
        $axisTypeId = $request->axis_type_id;

        $activities = [];

        $country = SafetyAndPrivacy::query()
            ->selectRaw('COUNT(*) as qty,info_id, step')
            ->whereBetween('created_at', [$fromDate, $toDate])
            ->when($axisTypeId, function ($query) use ($axisTypeId) {
                $query->where('axis_type_id', '=', $axisTypeId);
            })
            ->groupBy('info_id', 'step')
            ->get();

//        $country = DB::select(
//            "SELECT COUNT(*) as qty,info_id, step
//                    FROM safety_and_privacy where created_at BETWEEN '".$fromDate."' and '".$toDate."'
//                    GROUP BY info_id,step"
//        );

        $countryTotalSum = 0;
        $countryData = [
            'name_fa' => 'کشوری',
            'province_id' => -1,
            'sum' => 0,
            '89' => [
                '1' => 0,
                '2' => 0,
                '3' => 0,
            ],
            '90' => [
                '1' => 0,
                '2' => 0,
                '3' => 0,
            ],
            '91' => [
                '1' => 0,
                '2' => 0,
                '3' => 0,
            ],
        ];
        foreach ($country as $key => $value) {
            $countryTotalSum += $value->qty;
            $countryData[$value->info_id][$value->step] = $value->qty;
            $countryData["sum"] = $countryTotalSum;
        }
        $activities[] = (object) $countryData;

        $provinces = SafetyAndPrivacy::query()
            ->selectRaw('province_id, province_fa, COUNT(*) as qty,info_id, step')
            ->whereBetween('created_at', [$fromDate, $toDate])
            ->when($axisTypeId, function ($query) use ($axisTypeId) {
                $query->where('axis_type_id', '=', $axisTypeId);
            })
            ->groupBy('info_id', 'step', 'province_id', 'province_fa')
            ->get();

//        $provinces = DB::select(
//            "SELECT province_id, province_fa, COUNT(*) as qty,info_id, step
//                    FROM safety_and_privacy where created_at BETWEEN '".$fromDate."' and '".$toDate."'
//                    GROUP BY info_id,step,province_id,province_fa"
//        );

        foreach ($provinces as $value) {
            $provinceId = $value->province_id;

            // Check if the province already exists in the activities array
            if (!isset($activities[$provinceId])) {
                $activities[$provinceId] = (object) [
                    'province_id' => $provinceId,
                    'name_fa' => $value->province_fa,
                    'sum' => 0,
                    '89' => ['1' => 0, '2' => 0, '3' => 0],
                    '90' => ['1' => 0, '2' => 0, '3' => 0],
                    '91' => ['1' => 0, '2' => 0, '3' => 0],
                ];
            }

            $activities[$provinceId]->{$value->info_id}[$value->step] = $value->qty;
            $activities[$provinceId]->sum += $value->qty;
        }

        $activities = array_values($activities);

        return [
            'activities' => $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;
        $axisTypeId = $request->axis_type_id;
        $activities = [];

        $province = SafetyAndPrivacy::query()
            ->selectRaw('COUNT(*) as qty,info_id, step')
            ->where('province_id', '=', $provinceId)
            ->whereBetween('created_at', [$fromDate, $toDate])
            ->when($axisTypeId, function ($query) use ($axisTypeId) {
                $query->where('axis_type_id', '=', $axisTypeId);
            })
            ->groupBy('info_id', 'step')
            ->get();

//        $province = DB::select('
//            SELECT COUNT(*) as qty,info_id, step
//            FROM safety_and_privacy where province_id ='.$provinceId.' and created_at BETWEEN "'.$fromDate.'" and "'.$toDate.'"
//            GROUP BY info_id,step
//        ');

        $provinceTotalSum = 0;
        $provinceData = [
            'name_fa' => 'استانی',
            'edare_shahri_id' => -1,
            'sum' => 0,
            '89' => [
                '1' => 0,
                '2' => 0,
                '3' => 0,
            ],
            '90' => [
                '1' => 0,
                '2' => 0,
                '3' => 0,
            ],
            '91' => [
                '1' => 0,
                '2' => 0,
                '3' => 0,
            ],
        ];
        foreach ($province as $key => $value) {
            $provinceTotalSum += $value->qty;
            $provinceData["sum"] = $provinceTotalSum;
            $provinceData[$value->info_id][$value->step] = $value->qty;
        }
        $activities[] = (object) $provinceData;

        $cities = SafetyAndPrivacy::query()
            ->selectRaw('edare_shahri_id, COUNT(*) as qty,info_id, step')
            ->where('province_id', '=', $provinceId)
            ->whereBetween('created_at', [$fromDate, $toDate])
            ->when($axisTypeId, function ($query) use ($axisTypeId) {
                $query->where('axis_type_id', '=', $axisTypeId);
            })
            ->groupBy('info_id', 'step', 'edare_shahri_id')
            ->get();

//        $cities = DB::select('
//            SELECT edare_shahri_id, COUNT(*) as qty,info_id, step
//            FROM safety_and_privacy where province_id ='.$provinceId.' and created_at BETWEEN "'.$fromDate.'" and "'.$toDate.'"
//            GROUP BY info_id,step,edare_shahri_id
//        ');

        foreach ($cities as $value) {
            $cityId = $value->edare_shahri_id;

            // Initialize data for each unique city
            if (!isset($activities[$cityId])) {
                $activities[$cityId] = (object) [
                    'edare_shahri_id' => $cityId,
                    'name_fa' => \App\Models\EdarateShahri::query()->find($cityId)->name_fa,
                    'sum' => 0,
                    '89' => ['1' => 0, '2' => 0, '3' => 0],
                    '90' => ['1' => 0, '2' => 0, '3' => 0],
                    '91' => ['1' => 0, '2' => 0, '3' => 0],
                ];
            }
            $activities[$cityId]->{$value->info_id}[$value->step] = $value->qty;
            $activities[$cityId]->sum += $value->qty;
        }

        $activities = array_values($activities);

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