<?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\Cartables\RoadItemTableService;
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 countryActivityPerSubItem(Request $request, RoadItemTableService $roadItemTableService): JsonResponse
    {
        $activities = $roadItemTableService->countryActivityPerSubItem($request);
        $provinces = Province::all(['id', 'name_fa']);
        $subItems = InfoItem::query()
            ->where('item', $request->item)
            ->get(['id', 'item', 'item_str', 'sub_item_str', 'sub_item_unit', 'sub_item']);

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

    public function provinceActivityPerSubItem(Request $request, RoadItemTableService $roadItemTableService): JsonResponse
    {
        $activities = $roadItemTableService->provinceActivityPerSubItem($request);

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

        $subItems = InfoItem::query()
            ->where('item', $request->item)
            ->get(['id', 'item', 'item_str', 'sub_item_str', 'sub_item_unit', 'sub_item']);

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

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

        $activities = $roadItemTableService->countryActivityPerItem($request);
        $provinces = Province::all(['id', 'name_fa']);

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

    public function provinceActivityPerItem(Request $request, RoadItemTableService $roadItemTableService): JsonResponse
    {
        $activities = $roadItemTableService->provinceActivityPerItem($request);
        $edarateShahri = EdarateShahri::query()->where('province_id', '=', $request->province_id)->get(['id', 'name_fa']);

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

    public function countryActivityExcelPerItem(Request $request, RoadItemTableService $roadItemTableService): BinaryFileResponse
    {
        auth()->user()->addActivityComplete(1034);
        $name = 'گزارش کشوری از فعالیت روزانه و جاری - جدول 1 ' . verta()->now()->format('Y-m-d H-i') . '.xlsx';
        $activities = $roadItemTableService->countryActivityPerItem($request);
        return Excel::download(new CountryActivityPerItemReport([
            'activities' => $activities,
            'provinces' => Province::all(['id', 'name_fa']),
            'items' => InfoItem::query()->distinct()->get(['item', 'item_str']),
        ]), $name);
    }

    public function provinceActivityExcelPerItem(Request $request, RoadItemTableService $roadItemTableService): BinaryFileResponse
    {
        auth()->user()->addActivityComplete(1034);
        $name = 'گزارش استانی از فعالیت روزانه و جاری - جدول 1 ' . verta()->now()->format('Y-m-d H-i') . '.xlsx';
        $activities = $roadItemTableService->provinceActivityPerItem($request);
        return Excel::download(new ProvinceActivityPerItemReport([
            'activities' => $activities,
            'edarateShahri' => EdarateShahri::query()->where('province_id', '=', $request->province_id)->get(['id', 'name_fa']),
            'items' => InfoItem::query()->distinct()->get(['item', 'item_str']),
        ]), $name);
    }

    public function countryActivityExcelPerSubItem(Request $request, RoadItemTableService $roadItemTableService): BinaryFileResponse
    {
        auth()->user()->addActivityComplete(1034);
        $name = "گزارش کشوری از فعالیت روزانه و جاری - جدول 2 " . verta()->now()->format('Y-m-d H-i') . '.xlsx';
        $activities = $roadItemTableService->countryActivityPerSubItem($request);
        $subItems = InfoItem::query()
            ->where('item', $request->item)
            ->get(['id', 'item', 'item_str', 'sub_item_str', 'sub_item_unit', 'sub_item']);

        return Excel::download(new CountryActivityPerSubItemReport([
            'activities' => $activities,
            'provinces' => Province::all(['id', 'name_fa']),
            'subItems' => $subItems
        ]), $name);
    }

    public function provinceActivityExcelPerSubItem(Request $request, RoadItemTableService $roadItemTableService): BinaryFileResponse
    {
        auth()->user()->addActivityComplete(1034);
        $activities = $roadItemTableService->provinceActivityPerSubItem($request);
        $name = "گزارش استانی از فعالیت روزانه و جاری - جدول 2 " . verta()->now()->format('Y-m-d H-i') . '.xlsx';
        $subItems = InfoItem::query()
            ->where('item', $request->item)
            ->get(['id', 'item', 'item_str', 'sub_item_str', 'sub_item_unit', 'sub_item']);

        return Excel::download(new ProvinceActivityPerSubItemReport([
            'activities' => $activities,
            'subItems' => $subItems,
            'edarateShahri' => EdarateShahri::query()->where('province_id', '=', $request->province_id)->get(['id', 'name_fa']),
        ]), $name);
    }

    public function activitiesOnMap(Request $request): JsonResponse
    {
        $provinceId = $request->province_id;
        $cityId = $request->city_id;
        $subId = $request->sub_id;
        $item = $request->item;
        $status = $request->status;
        $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, $provinceId) => $query->where('road_items_projects.province_id', '=', $provinceId))
            ->when($cityId, fn($query, $cityId) => $query->where('road_items_projects.city_id', '=', $cityId))
            ->when($subId, fn($query, $subId) => $query->where('sub_items', 'like', '%' . $subId . '%'))
            ->when($item, fn($query, $item) => $query->where('item', '=', $item))
            ->when(!is_null($status), fn($query, $status) => $query->where('status', '=', $status))
            ->leftJoin('users', 'users.id', '=', 'road_items_projects.user_id')
            ->whereBetween('road_items_projects.activity_date', [$dateFrom, $dateTo])
            ->select('road_items_projects.id as i', 'start_lat as l', 'start_lng as g', 'status')
            ->get();

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

    public function showOnMap(RoadItemsProject $roadItemsProject): JsonResponse
    {
        return $this->successResponse($roadItemsProject->load(['files', 'rahdaran:id,name,code', 'cmmsMachines:id,machine_code,car_name,plak_number']));
    }
}
