<?php

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

use App\Exports\V3\AccidentReceipt\ProvinceReport;
use App\Exports\V3\AccidentReceipt\CountryReport;
use App\Http\Controllers\Controller;
use App\Http\Traits\ApiResponse;
use App\Models\City;
use App\Models\Province;
use App\Services\Cartables\AccidentReceiptTableService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class AccidentReceiptReportController extends Controller
{
    use ApiResponse;

    public function countryReport(Request $request, AccidentReceiptTableService $accidentReceiptTableService): JsonResponse
    {
        $data = $accidentReceiptTableService->countryReport($request);
        return $this->successResponse([
            'activities' => $data['data'],
            'provinces' => Province::all(['id', 'name_fa']),
        ]);
    }

    public function provinceReport(Request $request, AccidentReceiptTableService $accidentReceiptTableService): JsonResponse
    {
        $data = $accidentReceiptTableService->provinceReport($request);
        return $this->successResponse([
            'activities' => $data['data'],
            'cities' => City::query()->where('province_id', '=', $request->province_id)
                ->where('type_id', '=', 1)
                ->get(['id', 'name_fa']),
        ]);
    }

    public function countryExcelReport(Request $request, AccidentReceiptTableService $accidentReceiptTableService): BinaryFileResponse
    {
        $data = $accidentReceiptTableService->countryReport($request);
        $name = 'گزارش از خسارات وارده به ابنیه فنی و تاسیسات راه ' . verta()->now()->format('Y-m-d H-i') . '.xlsx';
        return Excel::download(new CountryReport($data), $name);
    }

    public function provinceExcelReport(Request $request, AccidentReceiptTableService $accidentReceiptTableService): BinaryFileResponse
    {
        $data = $accidentReceiptTableService->provinceReport($request);
        $name = 'گزارش از خسارات وارده به ابنیه فنی و تاسیسات راه ' . verta()->now()->format('Y-m-d H-i') . '.xlsx';
        return Excel::download(new ProvinceReport([
            'report' => $data,
            'cities' => City::query()->where('province_id', '=', $request->province_id)
                ->where('type_id', '=', 1)
                ->get(['id', 'name_fa']),
        ]), $name);
    }
}
