<?php

namespace App\Nova\Actions;

use App\Models\VerificationRequest;
use App\Notifications\VerificationRequestAccepted;
use App\Notifications\VerificationRequestDeclined;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Laravel\Nova\Actions\Action;
use Laravel\Nova\Fields\ActionFields;
use Laravel\Nova\Http\Requests\NovaRequest;

class VerifyWorker extends Action
{
    use InteractsWithQueue, Queueable;

    /**
     * The displayable name of the action.
     *
     * @var string
     */
    public $name = 'Verify';

    /**
     * Perform the action on the given models.
     *
     * @param ActionFields $fields
     * @param Collection $models
     * @return mixed
     */
    public function handle(ActionFields $fields, Collection $models)
    {
        foreach ($models as $model) {
            if($model->getModel() instanceof VerificationRequest){
                if($model->action ==null){
                    $model->action = true;
                    $model->entity->verified_at = now();
                    $model->user()->associate(Auth::user(),);
                    $model->save();
                    $model->entity->save();
                    $model->entity->notify(new VerificationRequestAccepted());
                }else{
                    return Action::danger('this request has ' . $model->action ? 'already verified': 'already declined');
                }
            }else{
                if($model->verified_at==null){
                    $model->verified_at = now();
                    $model->save();
                }else{
                     return Action::danger('Already Verified');
                }

            }

        }
        return Action::message('Verified!');
    }

    /**
     * Get the fields available on the action.
     *
     * @param NovaRequest $request
     * @return array
     */
    public function fields(NovaRequest $request)
    {
        return [];
    }
}
