<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\EpigraphsCollection;
use App\Http\Resources\Epigraphs;
use App\Models\Epigraph;
use App\Http\Requests\Api\BaseShow;

class EpigraphController extends Controller
{
    public function index()
    {
        $epigraphs = Epigraph::full()
        ->select(
            'id',
            'slug',
            'title'
        )
        ->with([
            'classifications' => function ($query) {
                $query->full()->classificationFilters();
            }
        ])
        ->get();
        return response()->json(new EpigraphsCollection($epigraphs));
    }

    public function show(BaseShow $request)
    {
        $data = $request->validated();
        $slug = $data['slug'] ?? "";
        $epigraph = Epigraph::select('*')->full()
        ->where('lang_slug', $slug)
        ->with([
            'images' => function ($query) {
                $query->select('*')->full()->orderBy('website_objects.position', 'asc')->with('image');
            },
            'idiom' => function ($query) {
                $query->select('*')->full()->orderBy('website_objects.position', 'asc');
            },
            'technique' => function ($query) {
                $query->select('*')->full()->orderBy('website_objects.position', 'asc');
            },
            'inscriptionType' => function ($query) {
                $query->select('*')->full()->orderBy('website_objects.position', 'asc');
            },
            'location' => function ($query) {
                $query->select('*')->full();
            },
            'chronologies' => function ($query) {
                $query->select('*')->full()->orderBy('website_objects.position', 'asc');
            },
            'classifications' => function ($query) {
                $query->select('*')->full()->classificationFilters();
            },
            'themes' => function ($query) {
                $query->select('*')->full()->whereNull('themes.parent_id');
            },
            'properties' => function ($query) {
                //I Had to do this in order to remove some extra queries since full() wasn't loading website and website languages relation
                $query->select('*')->full()->with(['websites' => function ($query) {
                    $query->with('languages');
                }]);
            },
            'audioVisuals' => function ($query) {
                $query->select('*')->full();
            },
            //I Had to do this in order to remove some extra queries since full() wasn't loading website and website languages relation
            'websites' => function ($query) {
                $query->with('languages');
            },
        ])
        ->first();
        if ($epigraph) {
            return response()->json(new Epigraphs($epigraph, true));
        } else {
            return response()->json();
        }
    }
}
