<?php

namespace App\Libs\Services;

use App\Models\NewsItem;

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

        $query = NewsItem::full()
            ->where('status', 'published')
            ->where(function ($query) {
                $query->whereNull('publish_date')
                    ->orWhere('publish_date', '<=', now()->tz('Europe/Berlin'));
            })->where(function ($query) {
                $query->whereNull('expiry_date')
                    ->orWhere('expiry_date', '>', now()->tz('Europe/Berlin'));
            });

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

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

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

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

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

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

    public function findBySlug(string $slug): ?NewsItem {
        $query = NewsItem::full()
            ->where('status', 'published')
            ->where(function ($query) {
                $query->whereNull('publish_date')
                    ->orWhere('publish_date', '<=', now()->tz('Europe/Berlin'));
            })->where(function ($query) {
                $query->whereNull('expiry_date')
                    ->orWhere('expiry_date', '>', now()->tz('Europe/Berlin'));
            })
            ->where('lang_slug', $slug);

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

        return $query->first();
    }
}
