<?php

namespace App\Nova;

use Carbon\Carbon;
use Laravel\Nova\Fields\ID;
use Illuminate\Http\Request;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Fields\Number;
use Laravel\Nova\Fields\Select;
use Laravel\Nova\Fields\Boolean;
use Laravel\Nova\Fields\DateTime;
use Laravel\Nova\Fields\Textarea;
use Laravel\Nova\Fields\BelongsTo;
use Laravel\Nova\Http\Requests\NovaRequest;
use App\Nova\Filters\StatusWithdrawalFilter;
use App\Nova\Filters\SubscriptionStatusFilter;


class Withdrawal extends Resource
{

    public static $group = 'Finance';

    /**
     * The model the resource corresponds to.
     *
     * @var string
     */
    public static $model = \App\Domain\Payments\Models\Withdrawal::class;

    /**
     * The single value that should be used to represent the resource when being displayed.
     *
     * @var string
     */
    public static $title = 'id';

    // public static $with = ['user.subscription'];


    /**
     * The columns that should be searched.
     *
     * @var array
     */
    public static $search = [
        'id', 'amount'
    ];

    /**
     * Get the fields displayed by the resource.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function fields(Request $request)
    {
        return [
            ID::make(__('ID'), 'id')->sortable(),
            BelongsTo::make('User')->readonly(),

            Select::make('Тип пользователя', 'userType')->options([
                1 => 'Физ. лицо',
                2 => 'Самозанятый',
                3 => 'Юридическое лицо',
                4 => 'ИП',
            ])->displayUsingLabels()->readonly(),


            Text::make('Реквизиты', 'requisites')
            ->readonly(),

            Text::make('Телефон', 'userPhone')
            ->readonly(),

            Number::make('Amount')->min(1)->step(0.01)->readonly(),
            Select::make('Status')->options([
                'pending' => 'В ожидании',
                'success' => 'Выполнен',
                'cancel' => 'Отменен',
            ])->displayUsingLabels()->readonly(optional($this->resource)->status !== 'pending'),

            Boolean::make('Подписка', function () {
                $last = $this->user->subscription->first();
                if ($last && $last->ends_at > Carbon::now()) {
                    return true;
                }
                return false;
            })->onlyOnIndex(),

            Textarea::make('Данные платежа', 'history_payment_details')->alwaysShow()->readonly(),
            Textarea::make('Примечания (причина отказа)', 'description')->alwaysShow()->readonly(optional($this->resource)->status !== 'pending'),
            DateTime::make('Created At')->format('DD MMM YYYY')->readonly(),
            DateTime::make('Updated At')->hideFromIndex()->readonly(),
        ];
    }

    /**
     * Get the cards available for the request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function cards(Request $request)
    {
        return [

        ];
    }

    /**
     * Get the filters available for the resource.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function filters(Request $request)
    {
        return [
            new StatusWithdrawalFilter(),
            new SubscriptionStatusFilter(),
        ];
    }

    /**
     * Get the lenses available for the resource.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function lenses(Request $request)
    {
        return [];
    }

    /**
     * Get the actions available for the resource.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function actions(Request $request)
    {
        return [];
    }

    protected static function afterUpdateValidation(NovaRequest $request, $validator)
    {
        if($request->created_at !== $request->updated_at){
            $validator->errors()->add('status', 'Данный платеж только для чтения!');
            return;
        }
        $status = $request->status;
        $description = $request->description;
        if($status === 'cancel' && empty($description)){
            $validator->errors()->add('description', 'Нужно указать причину отмены платежа!');
        }
    }

    public static function indexQuery(NovaRequest $request, $query)
    {
        return $query->with('user.subscription');
    }


}
