<?php

namespace App\Services;

use App\Models\ErrorLog;
use App\Models\Model;
use App\Models\Notification;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class PlanService
{

    static function getUserWithPlan(Model $model)
    {
        $requiredPlanIds = $model->plans->pluck('id')->toArray();

        return User::whereHas('plans', function ($q) use ($requiredPlanIds) { // get user that have the plan
            $q->whereIn('plans.id', $requiredPlanIds);
        }, '=', count($requiredPlanIds))
        ->with(['plans' => function ($q) use ($requiredPlanIds) { // get the pivot
            $q->whereIn('plans.id', $requiredPlanIds)
            ->select('plans.id', 'plans.name', 'plans.payment_type')
            ->orderBy('id', 'asc');
        }])
        ->get();
    }

    static function getPlanListForUser($userId)
    {
        return Model::whereHas('plans.users', function ($q) use ($userId) {
            $q->where('users.id', $userId);
        })
        ->with(['plans' => function ($q) use ($userId) {
            $q->whereHas('users', function ($q) use ($userId) {
                $q->where('users.id', $userId);
            })
            ->with(['users' => function ($q) use ($userId) {
                $q->where('users.id', $userId);
            }])
            ->orderBy('id', 'asc');
        }])
        ->get();
    }

    static function getPlanForUser($modelId, $userId)
    {
        return Model::whereHas('plans.users', function ($q) use ($userId) {
            $q->where('users.id', $userId);
        })
        ->with(['plans' => function ($q) use ($userId) {
            $q->whereHas('users', function ($q) use ($userId) {
                $q->where('users.id', $userId);
            })
            ->with(['users' => function ($q) use ($userId) {
                $q->where('users.id', $userId);
            }])
            ->orderBy('id', 'asc');
        }])
        ->where('id', $modelId)
        ->first();
    }
}
