<?php

namespace App\Classes\General\Eloquent\Filters;

use App\Classes\ValueObjects\Constants\RoleTypes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;

class HasVouchersAllWithUser implements Filter
{

    /**
     * @param Builder $builder
     * @param $value
     * @return mixed
     */
    public static function apply(Builder $builder, $value)
    {
        if(in_array(Auth::user()->type, RoleTypes::ADMIN_ROLES)){
            // $userId = $value !== 1 ? $value : Auth::user()->id;
            $userId = $value;
            return $builder->where('user_id', $userId)
            ->where(function ($query) {
                $query->whereHas('reward', function ($subquery) {
                    $subquery->where('is_active', true);
                })
                ->orWhereDoesntHave('reward');
            })
            ->whereDoesntHave('voucher.redemptions.transaction.booking.company.employees', function ($query) use ($userId) {
                $query->where('user_id', $userId);
            });
        }
        else{
            return $builder->where('user_id', Auth::user()->id)
            ->where(function ($query) {
                $query->whereHas('reward', function ($subquery) {
                    $subquery->where('is_active', true);
                })
                ->orWhereDoesntHave('reward');
            })
            ->whereDoesntHave('voucher.redemptions.transaction.owner');
        }
    }
}
