<?php

namespace App\Http\Controllers\Api\Publications;

use App\Http\Controllers\Controller;
use App\Models\Pages\Page;
use App\Models\Publications\Publication;
use App\Models\Publications\PublicationType;
use App\Transformers\Publications\PublicationTransformer;
use App\Transformers\Registries\RegistryTransformer;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Date;

class PublicationsController extends Controller {
    protected Publication $model;

    public function __construct(Publication $model) {
        $this->model = $model;
    }


    public function find(Request $request): ?JsonResponse {
        return ($model = Publication::byUrl($request->get('url'))) ? fractal($model, new PublicationTransformer())->respond() : null;
    }

    public function index(Request $request): JsonResponse {
        $query = $this->model->query()->orderBy('published_at', 'desc');
        $user = Auth::user();
        if (!($user->isAdmin ?? null)) {
            $query->where(['is_published' => true]);
            $query->where('published_at', '<=', now());
        }

        if ($page = Page::byUuid($request->get('page_id'))->first()) {
            $query->where(['page_id' => $page->id]);
        } elseif ($page = Page::query()->where(['sub_type' => $request->get('sub_type')])->first()) {
            $query->where('page_id', $page->id);
        }
        $paginator = $query->paginate(config('app.pagination_limit'));
        return fractal($paginator, new PublicationTransformer())->respond();
    }

    public function show(Request $request, $id): JsonResponse {
        $model = $this->model->ByUuid($id)->firstOrFail();
        return fractal($model, new RegistryTransformer())->respond();
    }


    public function store(Request $request): void {
    }


    public function update(Request $request, $uuid): void	{
    }

    public function destroy(Request $request, $uuid): JsonResponse {
        $model = $this->model->byUuid($uuid)->firstOrFail();
        $model->delete();
        return response()->json(null, 204);
    }

    public function published(Request $request, $uuid): JsonResponse {
        $model = $this->model->byUuid($uuid)->firstOrFail();
        $data = [
            'is_published' => $request->get('publish')
        ];
        $model->update($data);
        return fractal($model, new PublicationTransformer())->respond();
    }
}
