<?php

namespace Inside\BCLH\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Inside\BCLH\Http\Requests\SopExportRequest;
use Inside\BCLH\Services\ExcelExporterService;

/**
 * Export SOP in xlsx file
 *
 * @category Class
 * @author   Maecia <technique@maecia.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     http://www.maecia.com/
 */
class SopExportController
{
    public function __construct(private ExcelExporterService $excelExporterService)
    {
    }

    public function invoke(SopExportRequest $request): JsonResponse
    {
        $response = ['success' => true];
        $filters = json_decode($request->input('filters'), true);
        if (! empty($filters['uuid:in']) && is_string($filters['uuid:in'])) {
            $filters['uuid:in'] = explode(',', $filters['uuid:in']);
        }

        try {
            $this->excelExporterService
                ->setFilters($filters)
                ->execute();
        } catch (\Exception $exception) {
            $response['success'] = false;
        }

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