<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Resources\Api\NewsResource;
use App\Models\News;
use App\Traits\ApiResponseTrait;
use Illuminate\Http\JsonResponse;

class NewsController extends Controller
{
    use ApiResponseTrait;

    public function index(): JsonResponse
    {
        $news = News::query()
            ->where('active', true)
            ->where(function ($q) {
                $today = now()->toDateString();
                $q->whereNull('start_date')->orWhere('start_date', '<=', $today);
            })
            ->where(function ($q) {
                $today = now()->toDateString();
                $q->whereNull('end_date')->orWhere('end_date', '>=', $today);
            })
            ->orderByRaw('COALESCE(sort, 999999) ASC')
            ->orderByDesc('created_at')
            ->paginate(20);

        return $this->ApiResponse(NewsResource::collection($news), __('Success'), 200);
    }
}
