<?php

namespace App\Http\Controllers\V3;

use App\Exceptions\ProhibitedAction;
use App\Http\Controllers\Controller;
use App\Http\Traits\ApiResponse;
use App\Models\EdarateOstani;
use App\Models\RoadItemsProject;
use App\Models\RoadObserved;
use App\Models\SafetyAndPrivacy;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Throwable;

class NotificationController extends Controller
{
    use ApiResponse;

    /**
     * Handle the incoming request.
     * @throws Throwable
     */
    public function __invoke(Request $request): JsonResponse
    {
        return $this->successResponse([
            'roadItem' => $this->roadItemNotifications(),
            'safetyAndPrivacy' => $this->safetyAndPrivacyNotifications(),
            'roadObserved' => $this->roadObservedNotifications(),
        ]);
    }

    /**
     * @throws Throwable
     */
    private function roadItemNotifications(): JsonResponse|array
    {
        $user = auth()->user();
        $road_items = [
            'total' => 0
        ];

        if ($user->hasPermissionTo('create-road-item')) {
            $road_items['operation_cnt'] = RoadItemsProject::query()
                ->where('is_new', '=', 1)
                ->where('user_id', '=', $user->id)
                ->where('status', '=', 2)
                ->count();

            $road_items['total'] += $road_items['operation_cnt'];
        }
        if ($user->hasPermissionTo('supervise-road-item')) {
            $road_items['supervise_cnt'] = RoadItemsProject::query()
                ->where('is_new', '=', 1)
                ->where('status', '=', 0)
                ->count();

            $road_items['total'] += $road_items['supervise_cnt'];
        }
        elseif ($user->hasPermissionTo('supervise-road-item-province')) {
            throw_if(is_null($user->province_id) || !$user->province_id, new ProhibitedAction('استانی برای شما در سامانه ثبت نشده است!'));

            $road_items['supervise_cnt'] = RoadItemsProject::query()
                ->where('is_new', '=', 1)
                ->where('province_id', '=', $user->province_id)
                ->where('status', '=', 0)
                ->count();

            $road_items['total'] += $road_items['supervise_cnt'];
        }
        elseif ($user->hasPermissionTo('supervise-road-item-by-edareostani')) {
            throw_if(is_null($user->edarate_ostani_id) || !$user->edarate_ostani_id, new ProhibitedAction('اداره ای برای شما در سامانه ثبت نشده است!'));

            $confirmableItems = EdarateOstani::query()->where('id', '=', $user->edarate_ostani_id)->value('items_for_confirm');
            $road_items['supervise_cnt'] = RoadItemsProject::query()
                ->where('is_new', '=', 1)
                ->where('province_id', '=', $user->province_id)
                ->whereIn('item', explode(",", $confirmableItems))
                ->where('status', '=', 0)
                ->count();

            $road_items['total'] += $road_items['supervise_cnt'];
        }
        return $road_items;
    }

    /**
     * @throws Throwable
     */
    private function safetyAndPrivacyNotifications(): JsonResponse|array
    {
        $user = auth()->user();
        $safety_and_privacy = array();
        if ($user->hasPermissionTo('show-safety-and-privacy-operator-cartable')) {
            $activity = SafetyAndPrivacy::query()
                ->selectRaw('count(*) as cnt, step')
                ->groupby('step')
                ->orderBy('step')
                ->get();

        }
        elseif ($user->hasPermissionTo('show-safety-and-privacy-operator-cartable-province')) {
            throw_if(is_null($user->province_id), new ProhibitedAction('استانی برای شما در سامانه ثبت نشده است!'));

            $activity = SafetyAndPrivacy::query()
                ->where('province_id', '=', $user->province_id)
                ->selectRaw('count(*) as cnt, step')
                ->groupby('step')
                ->orderBy('step')
                ->get();

        }
        elseif ($user->hasPermissionTo('show-safety-and-privacy-operator-cartable-edarate-shahri')) {
            throw_if(is_null($user->edarate_shahri_id), new ProhibitedAction('اداره ای برای شما در سامانه ثبت نشده است!'));

            $activity = SafetyAndPrivacy::query()
                ->where('edare_shahri_id', '=', $user->edarate_shahri_id)
                ->selectRaw('count(*) as cnt, step')
                ->groupby('step')
                ->orderBy('step')
                ->get();
        }

        $safety_and_privacy['step_one'] = isset($activity[0]) ? $activity[0]->cnt : 0;
        $safety_and_privacy['step_two'] = isset($activity[1]) ? $activity[1]->cnt : 0;

        return $safety_and_privacy;
    }

    /**
     * @throws Throwable
     */
    private function roadObservedNotifications(): JsonResponse|array
    {
        $user = auth()->user();
        $road_observations = [
            'total' => 0,
            'operation_cnt' => 0,
            'complaint_cnt' => 0,
            'supervise_cnt' => 0
        ];

        $conditions = [];
        $complaintConditions = [
            ['rms_status', '=', 0],
            ['edarate_shahri_id', '!=', null]
        ];

        if ($user->hasPermissionTo('show-fast-react')) {
            $conditions[] = ['status', '=', 2];
        }
        elseif ($user->hasPermissionTo('show-fast-react-province')) {
            throw_if(is_null($user->province_id), new ProhibitedAction('استانی برای شما در سامانه ثبت نشده است!'));
            $conditions = [
                ['status', '=', 2],
                ['rms_province_id', '=', $user->province_id]
            ];
            $complaintConditions[] = ['province_id', '=', $user->province_id];
        }
        elseif ($user->hasPermissionTo('show-fast-react-edarate-shahri')) {
            throw_if(is_null($user->edarate_shahri_id), new ProhibitedAction('اداره ای برای شما در سامانه ثبت نشده است!'));
            $conditions = [
                ['status', '=', 2],
                ['edarate_shahri_id', '=', $user->edarate_shahri_id]
            ];
            $complaintConditions[] = ['edarate_shahri_id', '=', $user->edarate_shahri_id];
        }

        if (!empty($conditions)) {
            $road_observations['operation_cnt'] = RoadObserved::query()->where($conditions)->count();
            $road_observations['complaint_cnt'] = RoadObserved::query()->where($complaintConditions)->count();
            $road_observations['total'] += $road_observations['operation_cnt'] + $road_observations['complaint_cnt'];
        }

        $superviseConditions = [
            ['status', '=', 0]
        ];

        if ($user->hasPermissionTo('supervise-fast-react')) {
            $road_observations['supervise_cnt'] = RoadObserved::query()->where($superviseConditions)->count();
            $road_observations['complaint_cnt'] = RoadObserved::query()->where($complaintConditions)->count();
            $road_observations['total'] += $road_observations['supervise_cnt'] + $road_observations['complaint_cnt'];
        }
        elseif ($user->hasPermissionTo('supervise-fast-react-province')) {
            throw_if(is_null($user->province_id), new ProhibitedAction('استانی برای شما در سامانه ثبت نشده است!'));
            $superviseConditions[] = ['province_id', '=', $user->province_id];
            $complaintConditions[] = ['province_id', '=', $user->province_id];

            $road_observations['supervise_cnt'] = RoadObserved::query()->where($superviseConditions)->count();
            $road_observations['complaint_cnt'] = RoadObserved::query()->where($complaintConditions)->count();
            $road_observations['total'] += $road_observations['supervise_cnt'] + $road_observations['complaint_cnt'];
        }

        return $road_observations;
    }
}
