<?php

namespace App\Models\Virtual\Scopes;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Builder;

class OrderCardPartitionNotRefundedScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        $builder->whereNull('refunded_at');
    }

    /**
     * Extend the query builder with the needed functions.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @return void
     */
    public function extend(Builder $builder)
    {
        $builder->macro('refunded', function (Builder $builder) {
            return $builder->withoutGlobalScope($this)->whereNotNull('refunded_at');
        });

        $builder->macro('withRefunded', function (Builder $builder, $withRefunded = true) {
            if (! $withRefunded) {
                return $builder->withoutRefunded();
            }

            return $builder->withoutGlobalScope($this);
        });
    }
}
