<?php

namespace App\Repositories;

use App\Enumerations\ParticipationType;
use App\Enumerations\UserRole;
use App\Models\CostUnit;
use App\Models\Event;
use App\Providers\AuthCheckProvider;
use App\Resources\CostUnitResource;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Psy\Readline\Hoa\EventBucket;

class EventRepository {
    public function listAll() : array {
        return $this->getEventsByCriteria([
            'archived' => false
        ]);

    }

    public function getMyCurrentEvent() : ?Event {
        $events = $this->getEventsByCriteria([
            ['archived', '=', false],
            ['start_date', '<=', now()],
            ['end_date', '>=', now()],
        ], true);
        if (count($events) !== 1) {
            return null;
        }
        return $events[0];
    }

    public function getUpcoming(int $maxCount = 5, bool $accessCheck = true) : array {
        $events = [];
        foreach ( $this->getEventsByCriteria([
            'archived' => false,

        ],$accessCheck) as $event) {
            if ($event->end_date >= now()) {
                $event = $event->toResource()->toArray(new Request());

                $events[] = $event;
            }
        };

        return array_slice($events, 0, $maxCount);
    }

    public function getAvailable(bool $accessCheck = true) : array {
        $events = [];
        foreach ( $this->getEventsByCriteria([
            'archived' => false,

        ],$accessCheck) as $event) {
            if ($event->start_date > now()) {
                $events[] = $event;
            }
        };

        return $events;
    }

    public function getForRegistration(int $id) : ?Event {
        $events = self::getEventsByCriteria(['id' => $id, 'registration_allowed' => true]);
    }

    public function getById(int $id, bool $accessCheck = true) : ?Event {
        $events = self::getEventsByCriteria(['id' => $id], $accessCheck);
        return $events[0] ?? null;
    }

    public function getByIdentifier(string $identifier, bool $accessCheck = true) : ?Event {
        $events = self::getEventsByCriteria(['identifier' => $identifier], $accessCheck);
        return $events[0] ?? null;
    }

    public function getEventsByCriteria(array $criteria, $accessCheck = true) : array {
        $user = Auth()->user();

        if (!$accessCheck) {
            $canSeeAll = true;
        } else {
            $canSeeAll = in_array(new AuthCheckProvider()->getUserRole(), [
                UserRole::USER_ROLE_ADMIN, UserRole::USER_ROLE_GROUP_LEADER
            ]);
        }

        $visibleEvents = [];
        /** @var Event $event */
        foreach (Event::where($criteria)->orderBy('start_date')->get() as $event) {
            if ($canSeeAll || $event->eventManagers()->where('user_id', $user->id)->exists()) {
                $visibleEvents[] = $event;
            }
        }

        return $visibleEvents;
    }
}
