<?php

namespace App\Libs\Services;

use App\Models\EventItem;
use Illuminate\Support\Facades\Auth;

class EventItemService {
    public function list(array $searchData): array {
        $orderDir = $searchData['orderDir'] ? $searchData['orderDir'] : 'asc';

        $query = EventItem::full()
            ->where('status', 'published');

        if(
            (!empty($searchData['userFlag']) && $searchData['userFlag'])
            || (!empty($searchData['upcomingEvents']) && $searchData['upcomingEvents'])
            || (!empty($searchData['pastEvents']) && $searchData['pastEvents'])
        ) {
            $userData = Auth::user();

            $query->where(function ($query) use ($userData) {
                $query->where('type', 'general_event');

                if ($userData->committees) {
                    $query->orWhereIn('committee_id', $userData->committees->pluck('id'));
                }

                if ($userData->workGroups) {
                    $query->orWhereIn('work_group_id', $userData->workGroups->pluck('id'));
                }
            });

            if (!empty($searchData['upcomingEvents'])) {
                $query->where(function ($query) { // next events and ongoing
                    $query->where('start_date', '>=', now())
                        ->orWhere(function ($query) {
                            $query->whereNotNull('end_date')
                                ->where('end_date', '>=', now());
                        });
                });
            } else if (!empty($searchData['pastEvents'])) {
                $query->where(function ($query) { // past events
                    $query->where(function ($query) {
                        $query->where('start_date', '<', now())
                            ->whereNull('end_date');
                        })
                        ->orWhere(function ($query) {
                            $query->whereNotNull('end_date')
                                ->where('end_date', '<', now());
                        });
                });
            }
        } else {
            if ($searchData['committeeId']) {
                $query->where('committee_id', $searchData['committeeId']);
            } else if ($searchData['workGroupId']) {
                $query->where('work_group_id', $searchData['workGroupId']);
            }
        }

        if (!empty($searchData['upcomingEvents'])) {
            $query->orderBy('end_date', 'asc');
        } else if (!empty($searchData['pastEvents'])) {
            $query->orderBy('start_date', 'desc');
        } else {
            switch ($searchData['orderBy']) {
                case 'date':
                    $query->orderBy('start_date', $orderDir);
                    break;
                default:
                    # title
                    $query->orderBy('title', $orderDir);
                    break;
            }
        }

        switch ($searchData['orderBy']) {
            default:
                # title
                $query->orderBy('title', $orderDir)
                    ->orderBy('title', $orderDir);
                break;
        }

        $perPage = $searchData['perPage'] ?? 12;
        $page = $searchData['page'] ?? 1;

        $query->with([
            'agenda',
            'image',
        ]);

        $events = $query->paginate($perPage, ['*'], 'page', $page);

        $paginationData = [
            'currentPage' =>  intval($events->currentPage()),
            'lastPage' => intval($events->lastPage()),
            'perPage' =>  intval($events->perPage()),
            'total' =>  intval($events->total()),
            'count' =>  intval($events->count()),
            'hasMorePages' => $events->hasMorePages(),
            'nextPageUrl' => $events->nextPageUrl(),
            'prevPageUrl' => $events->previousPageUrl(),
        ];

        return [
            'events' => $events,
            'pagination' => $paginationData,
        ];
    }

    public function findBySlug(string $slug): ?EventItem {
        $query = EventItem::full()
            ->where('status', 'published')
            ->where('lang_slug', $slug);

        $query->with([
            'agenda',
            'image',
        ]);

        return $query->first();
    }
}
