<?php

namespace App\Http\Controllers\V3\Dashboard\Reports;

use App\Exports\V3\RoadItemsProjects\CountryActivityPerItemReport;
use App\Exports\V3\RoadItemsProjects\CountryActivityPerSubItemReport;
use App\Exports\V3\RoadItemsProjects\ProvinceActivityPerItemReport;
use App\Exports\V3\RoadItemsProjects\ProvinceActivityPerSubItemReport;
use App\Http\Controllers\Controller;
use App\Http\Traits\ApiResponse;
use App\Models\EdarateShahri;
use App\Models\InfoItem;
use App\Models\Province;
use App\Models\RoadItemsProject;
use App\Services\Reports\RoadItemReportService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class RoadItemsReportController extends Controller
{
    use ApiResponse;
    public function getSubItems(): JsonResponse
    {
        $data = InfoItem::all();
        $items = InfoItem::query()->groupBy('item')->get();

        return $this->successResponse([
            'items' => $items,
            'data' => $data,
        ]);
    }

    public function provinceActivityPerSubItem(Request $request): JsonResponse
    {
        $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);
        $provinces = Province::all(['id', 'name_fa']);
        $subItems = InfoItem::query()
            ->where('item', $item)
            ->get(['id', 'item', 'item_str', 'sub_item_str', 'sub_item_unit', 'sub_item']);

        return $this->successResponse([
            'activities' => $activities,
            'sub_items' => $subItems,
            'provinces' => $provinces,
        ]);
    }

    public function cityActivityPerSubItem(Request $request): JsonResponse
    {
        $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();


        $edarateShahri = EdarateShahri::query()->where('province_id', '=', $province)->get(['id', 'name_fa']);
        $activities = $cityRoadItemsPerSubItem->push(...$provinceRoadItemsPerSubItem);
        $subItems = InfoItem::query()
            ->where('item', $item)
            ->get(['id', 'item', 'item_str', 'sub_item_str', 'sub_item_unit', 'sub_item']);

        return $this->successResponse([
            'activities' => $activities,
            'edarateShahri' => $edarateShahri,
            'sub_items' => $subItems,
        ]);
    }

    public function provinceActivityPerItem(Request $request): JsonResponse
    {
        if (auth()->check()) {
            auth()->user()->addActivityComplete(1033);
        }

        $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();

        $provinces = Province::all(['id', 'name_fa']);

        return $this->successResponse([
            'activities' => $activities,
            'provinces' => $provinces,
        ]);
    }

    public function cityActivityPerItem(Request $request): JsonResponse
    {
        $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();

        $edarateShahri = EdarateShahri::query()->where('province_id', '=', $provinceId)->get(['id', 'name_fa']);

        return $this->successResponse([
            'activities' => $activities,
            'edarateShahri' => $edarateShahri,
        ]);
    }

    public function map(Request $request): JsonResponse
    {
        $provinceId = $request->province_id;
        $cityId = $request->city_id;
        $subId = $request->sub_id;
        $item = $request->item;
        $dateFrom = $request->date_from ? $request->date_from . ' 00:00:00' : now()->startOfDay()->toDateTimeString();
        $dateTo = $request->date_to ? $request->date_to . ' 23:59:59' : now()->addDay()->startOfDay()->toDateTimeString();

        $data = RoadItemsProject::query()
            ->where('is_new', '=', 1)
            ->when($provinceId, fn($query) => $query->where('province_id', '=', $provinceId))
            ->when($cityId, fn($query) => $query->where('city_id', '=', $cityId))
            ->when($subId, fn($query) => $query->where('sub_items', 'like', '%' . $subId . '%'))
            ->when($item, fn($query) => $query->where('item', '=', $item))
            ->when(!is_null($request->status), fn($query) => $query->where('status', '=', $request->status))
            ->whereBetween('activity_date', [$dateFrom, $dateTo])
            ->leftJoin('users', 'users.id', '=', 'road_items_projects.user_id')
            ->select('road_items_projects.id as i', 'start_lat as l', 'start_lng as g', 'status')
            ->get();

        return $this->successResponse($data);
    }

    public function countryActivityExcelPerItem(Request $request): BinaryFileResponse
    {
        auth()->user()->addActivityComplete(1034);
        $name = 'گزارش کشوری از فعالیت روزانه و جاری - جدول 1 ' . verta()->now()->format('Y-m-d H-i') . '.xlsx';
        return Excel::download(new CountryActivityPerItemReport($request->fromDate, $request->toDate), $name);
    }

    public function provinceActivityExcelPerItem(Request $request): BinaryFileResponse
    {
        auth()->user()->addActivityComplete(1034);
        $name = 'گزارش استانی از فعالیت روزانه و جاری - جدول 1 ' . verta()->now()->format('Y-m-d H-i') . '.xlsx';
        return Excel::download(new ProvinceActivityPerItemReport($request->fromDate, $request->toDate, $request->province), $name);
    }

    public function countryActivityExcelPerSubItem(Request $request, RoadItemReportService $roadItemReportService): BinaryFileResponse
    {
        auth()->user()->addActivityComplete(1034);

        $activities = $roadItemReportService->countryActivityPerSubItem(
            $request->item,
            $request->fromDate,
            $request->toDate,
        );

        $name = "گزارش کشوری از فعالیت روزانه و جاری - جدول 2 " . verta()->now()->format('Y-m-d H-i') . '.xlsx';

        return Excel::download(new CountryActivityPerSubItemReport($activities), $name);
    }

    public function provinceActivityExcelPerSubItem(Request $request, RoadItemReportService $roadItemReportService): BinaryFileResponse
    {
        auth()->user()->addActivityComplete(1034);

        $activities = $roadItemReportService->provinceActivityPerSubItem(
            $request->item,
            $request->fromDate,
            $request->toDate,
            $request->province_id
        );

        $name = "گزارش استانی از فعالیت روزانه و جاری - جدول 2 " . verta()->now()->format('Y-m-d H-i') . '.xlsx';

        return Excel::download(new ProvinceActivityPerSubItemReport($activities), $name);
    }
}
