<?php

namespace App\Http\Controllers\Front;

use App\Http\Controllers\Controller;
use App\Http\Resources\DefaultCollection;
use App\Models\Admin\Interna;
use App\Models\Admin\Modulos;
use Illuminate\View\View;

class InternaController extends Controller
{
    public function index($slug_modulo)
    {

        $modulo = $this->getModulo($slug_modulo);

        $size = request('page.size', 10);
        $page = request('page.number', 1);

        $result = Interna::modulo($modulo->id)
            ->activo()
            ->where('operadores', false)
            ->noBorrador()
            ->selectFillableAnd(['id as image_large_getter'])
            ->filterLike(request('filter', []))
            ->applySorts(request('sort'))
            ->ordenar()
            ->fastPaginate(
                perPage: $size,
                columns: ['id'],
                page: $page,
                pageName: 'page[number]',
            )->appends(request()->only('sort', 'page.size', 'filter'));

        return [
            'result' => $result,
            'modulo' => $modulo
        ];
    }

    public function listView(String $slug_modulo): View
    {
        $modulo = $this->getModulo($slug_modulo);

        if (!$modulo) {
            abort(404);
        }

        return view('index');
    }

    private function getModulo(String $slug): ?Modulos
    {
        return  Modulos::slug($slug)
            ->activo()
            ->selectFillable()
            ->first();
    }

    public function show(String $slug_modulo, int $id)
    {
        $modulo = $this->getModulo($slug_modulo);

        if (!$modulo) abort(404);

        $interna =  Interna::modulo($modulo->id)
            ->where('id', $id)
            ->activo()
            ->noBorrador()
            ->selectFillableAnd(['id as image_large_getter'])
            ->first();

        if (!$interna) abort(404);

        $titulo = $interna->titulo;
        $descripcion = $interna->descripcion;
        $imagen = $interna->image_large;

        return view('index', compact('titulo', 'descripcion', 'imagen'));
    }

    public function watch(String $slug, int $id)
    {
        $result = Interna::where('id', $id)
            ->activo()
            ->noBorrador()
            ->selectFillableAnd(['id as image_large_getter'])
            ->first();

        $result->secciones = $result->secciones()
            ->where('estado', true)
            ->ordenar()
            ->get();

        return $result;
    }
}
