<?php

namespace App\Classes\General\Eloquent\Filters;

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

class HasVouchersAllWithCompany 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;
            $user = User::where('id', $userId)->first();
            $users = $user->company()->first()->employees;
            $userIds = $users->pluck('id');

            return $builder->whereIn('user_id', $userIds)
            ->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{
            $user = User::where('id', Auth::user()->id)->first();
            $users = $user->company()->first()->employees;
            $userIds = $users->pluck('id');

            return $builder->whereIn('user_id', $userIds)
            ->where(function ($query) {
                $query->whereHas('reward', function ($subquery) {
                    $subquery->where('is_active', true);
                })
                ->orWhereDoesntHave('reward');
            })
            ->whereDoesntHave('voucher.redemptions.transaction.owner');
        }
    }
}
