<?php

namespace App\Services\Cartables;

use App\Facades\DataTable\DataTableFacade;
use App\Models\InfoItem;
use App\Models\RoadItemsProject;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

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

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

        if ($user->hasPermissionTo('show-road-item-supervise-cartable')) {
            $query = RoadItemsProject::query()
                ->select(['id', 'province_fa', 'edarat_name', 'item', 'item_fa', 'sub_item', 'sub_item_fa', 'sub_item_data', 'unit_fa', 'start_lat', 'start_lng',
                    'end_lat', 'end_lng', 'activity_date_time', 'created_at', 'status_fa', 'status'])
                ->where('is_new', 1)
                ->when($loadRelations, fn ($query) => $query->with(['rahdaran:id,name,code', 'cmmsMachines:id,machine_code,car_name,plak_number']));
        }
        elseif ($user->hasPermissionTo('show-road-item-supervise-cartable-province')) {
            if (is_null($user->province_id)) {
                return $this->errorResponse('استانی برای شما در سامانه ثبت نشده است!');
            }
            $query = RoadItemsProject::query()
                ->select(['id', 'province_fa', 'edarat_name', 'item', 'item_fa', 'sub_item', 'sub_item_fa', 'sub_item_data', 'unit_fa', 'start_lat', 'start_lng',
                    'end_lat', 'end_lng', 'activity_date_time', 'created_at', 'status_fa', 'status'])
                ->where('is_new', 1)
                ->where('province_id', auth()->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 = RoadItemsProject::query()
            ->select(['id', 'supervisor_description', 'item', 'item_fa', 'sub_item', 'sub_item_fa', 'sub_item_data', 'unit_fa', 'start_lat', 'start_lng',
                'end_lat', 'end_lng', 'activity_date_time', 'created_at', 'status_fa', 'status'])
            ->where('is_new', 1)
            ->where('user_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 countryActivityPerSubItem(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();
        $item = $request->item;

        $provinceRoadItemsPerSubItem = RoadItemsProject::query()->selectRaw('
            sub_item AS t,
            COUNT(*) AS c,
            CAST(SUM(CASE WHEN sub_item_data > 0 THEN sub_item_data ELSE ABS(sub_item_data) END) AS UNSIGNED) AS s,
            province_id AS p')
            ->where('item', '=', $item)
            ->whereBetween('activity_date_time', [$fromDate, $toDate])
            ->where('status', '=', 1)
            ->groupBy('province_id', 'sub_item')
            ->get();

        $countryRoadItemsPerSubItem = RoadItemsProject::query()->selectRaw('
            sub_item AS t,
            COUNT(*) AS c,
            CAST(SUM(CASE WHEN sub_item_data > 0 THEN sub_item_data ELSE ABS(sub_item_data) END) AS UNSIGNED) AS s,
            -1 AS p')
            ->where('item', '=', $item)
            ->whereBetween('activity_date_time', [$fromDate, $toDate])
            ->where('status', '=', 1)
            ->groupBy('sub_item')
            ->get();


        $activities = $provinceRoadItemsPerSubItem->push(...$countryRoadItemsPerSubItem);

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

    public function provinceActivityPerSubItem(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();
        $item = $request->item;
        $province = $request->province_id;

        $cityRoadItemsPerSubItem = RoadItemsProject::query()->selectRaw('
            sub_item AS t,
            COUNT(*) AS c,
            CAST(SUM(CASE WHEN sub_item_data > 0 THEN sub_item_data ELSE ABS(sub_item_data) END) AS UNSIGNED) AS s,
            province_id AS p,
            edarat_id AS ci
        ')
            ->where('item', '=', $item)
            ->where('province_id', '=', $province)
            ->whereBetween('activity_date_time', [$fromDate, $toDate])
            ->where('status', '=', 1)
            ->groupBy('edarat_id', 'sub_item')
            ->get();

        $provinceRoadItemsPerSubItem = RoadItemsProject::query()->selectRaw('
            sub_item AS t,
            COUNT(*) AS c,
            CAST(SUM(CASE WHEN sub_item_data > 0 THEN sub_item_data ELSE ABS(sub_item_data) END) AS UNSIGNED) AS s,
            province_id AS p,
            -1 AS ci
        ')
            ->where('item', '=', $item)
            ->where('province_id', '=', $province)
            ->whereBetween('activity_date_time', [$fromDate, $toDate])
            ->where('status', '=', 1)
            ->groupBy('sub_item')
            ->get();


        $activities = $cityRoadItemsPerSubItem->push(...$provinceRoadItemsPerSubItem);

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

    public function countryActivityPerItem(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();
        $user = auth()->user();
//        $isSpecialUser = in_array($user->username, ['witel', 'drdanesh']);
        $isSpecialUser = $user->hasPermissionTo("show-road-item-supervise-cartable");
        $provinceId = $isSpecialUser ? null : $user->province_id;

        $provinceActivity = RoadItemsProject::query()
            ->selectRaw('COUNT(*) AS s, province_id AS p, item AS i')
            ->where('status', 1)
            ->whereBetween('activity_date_time', [$fromDate, $toDate])
            ->when(!$isSpecialUser, function ($query) use ($provinceId) {
                $query->where('province_id', $provinceId);
            })
            ->groupBy('province_id', 'item');

        $countryActivity = RoadItemsProject::query()
            ->selectRaw('COUNT(*) AS s, -1 AS p, item AS i')
            ->where('status', 1)
            ->whereBetween('activity_date_time', [$fromDate, $toDate])
            ->when(!$isSpecialUser, function ($query) use ($provinceId) {
                $query->where('province_id', $provinceId);
            })
            ->groupBy('item');

        $activities = $provinceActivity
            ->unionAll($countryActivity)
            ->get();

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

    public function provinceActivityPerItem(Request $request): array
    {
        $provinceId = $request->province_id;
        $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();

        $edarehActivity = RoadItemsProject::query()
            ->selectRaw('
            COUNT(*) AS s,
            edarat_id AS c,
            item AS i')
            ->where('status', '=', 1)
            ->whereBetween('activity_date_time', [$fromDate, $toDate])
            ->where('province_id', $provinceId)
            ->groupBy('item', 'edarat_id');

        $cityActivity = RoadItemsProject::query()
            ->selectRaw('
            COUNT(*) AS s,
            -1 AS c,
            item AS i')
            ->where('status', '=', 1)
            ->whereBetween('activity_date_time', [$fromDate, $toDate])
            ->where('province_id', $provinceId)
            ->groupBy('item');

        $activities = $edarehActivity
            ->unionAll($cityActivity)
            ->get();

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