<?php

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

use App\Exports\V3\RoadPatrols\SupervisorCartableReport;
use App\Http\Controllers\Controller;
use App\Http\Traits\ApiResponse;
use App\Services\Cartables\RoadPatrol\SupervisorService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Throwable;

class SupervisorController extends Controller
{
    use ApiResponse;

    /**
     * @throws Throwable
     */
    public function index(Request $request, SupervisorService $supervisorService): JsonResponse
    {
        $data = $supervisorService->dataTable($request);

        foreach ($data['data'] as $road_patrol) {
            if (Gate::allows('gate-supervise-road-item', $road_patrol)) {
                $road_patrol['can_supervise'] = 1;
            } else {
                $road_patrol['can_supervise'] = 0;
            }
        }

        return response()->json($data);
    }

    /**
     * @throws Throwable
     */
    public function excel(Request $request, SupervisorService $supervisorService): BinaryFileResponse
    {
        $name = 'گزارش از کارتابل ارزیابی گشت راهداری ' . verta()->now()->format('Y-m-d H:i') . '.xlsx';
        $data = $supervisorService->dataTable($request, true);
        return Excel::download(new SupervisorCartableReport($data['data']), $name);
    }
}
