<?php

namespace App\Nova\Resources\Ecommerce\Product\Order\Actions;

use App\Exports\Ecommerce\Product\Order\ExportOrderReport;
use App\Nova\Fields\FieldHelpers;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Storage;
use Laravel\Nova\Actions\Action;
use Laravel\Nova\Fields\ActionFields;
use Laravel\Nova\Fields\Date;
use Laravel\Nova\Http\Requests\NovaRequest;

class ExportOrderReportAction extends Action
{
    use InteractsWithQueue, Queueable;

    /**
     * Get the displayable name of the action.
     */
    public function name(): string
    {
        return __('Export Order Report');
    }

    /**
     * Perform the action on the given models.
     */
    public function handle(ActionFields $fields, Collection $models): mixed
    {
        $start_date = Carbon::createFromFormat('Y-m-d', $fields->start_date)->format('d.m.Y');
        $end_date = Carbon::createFromFormat('Y-m-d', $fields->end_date)->format('d.m.Y');

        (new ExportOrderReport(
            start_date: $fields->start_date,
            end_date: $fields->end_date
        ))->store('order-reports.xlsx', 'order_reports');

        return Action::download(
            url: Storage::disk('order_reports')->url('order-reports.xlsx'),
            name: sprintf('Hasabat %s - %s.xlsx', $start_date, $end_date)
        );
    }

    /**
     * Get the fields available on the action.
     *
     * @return array
     */
    public function fields(NovaRequest $request)
    {
        return [
            Date::make(__('Start date'), 'start_date')
                ->rules('required')
                ->displayUsing(FieldHelpers::tmDate()),

            Date::make(__('End date'), 'end_date')
                ->rules('required')
                ->displayUsing(FieldHelpers::tmDate()),
        ];
    }
}
