<?php

namespace App\Http\Controllers;

use App\Helpers\CacheHelper;
use App\Models\Episode;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;

class HomeController extends Controller
{
    /**
     * Display Home Page.
     */
    public function index(): View
    {
        $guest = Auth::guest();

        $guestString = $guest ? 'guest' : 'authed';

        $mostLikes = \cache()->remember('mostLikes'.$guestString, 300, fn () => Episode::with('gallery')
            ->when($guest, fn ($query) => $query->withoutTags(['loli', 'shota']))
            ->whereIn('id', function ($query) {
                $mostLikesIds = CacheHelper::getMostLikes()->pluck('markable_id')->toArray();
                $query->selectRaw('id')
                    ->from('episodes')
                    ->whereIn('id', $mostLikesIds)
                    ->orderByRaw('FIELD(id, '.implode(',', $mostLikesIds).')');
            })
            ->get()
        );

        return view('home.index', [
            'recentlyReleased' => CacheHelper::getRecentlyReleased($guest),
            'recentlyUploaded' => CacheHelper::getRecentlyUploaded($guest),
            'popularAllTime' => CacheHelper::getPopularAllTime($guest),
            'popularMonthly' => CacheHelper::getPopularMonthly(),
            'popularWeekly' => CacheHelper::getPopularWeekly(),
            'popularDaily' => CacheHelper::getPopularDaily(),
            'mostLikes' => $mostLikes,
            'latestComments' => CacheHelper::getLatestComments(),
        ]);
    }

    /**
     * Display Banned Page.
     */
    public function banned(): View
    {
        return view('auth.banned');
    }

    /**
     * Redirects to a random Hentai episode
     * Done due to performance reasons
     */
    public function random(): RedirectResponse
    {
        $random = Episode::inRandomOrder()
            ->limit(1)
            ->pluck('slug')
            ->first();

        return redirect()->route('hentai.index', [
            'title' => $random,
        ]);
    }

    /**
     * Display Search Page.
     */
    public function search(): View
    {
        return view('search.index');
    }

    /**
     * Display Download Search Page.
     */
    public function downloadSearch(): View
    {
        return view('search.download');
    }

    /**
     * Redirect POST Data to GET with Query String.
     */
    public function searchRedirect(Request $request): RedirectResponse
    {
        return redirect()->route('hentai.search', [
            'search' => $request->input('live-search'),
        ]);
    }

    /**
     * Display Stats Page.
     */
    public function stats(): View
    {
        return view('home.stats', [
            'viewCount' => CacheHelper::getTotalViewCount(),
            'episodeCount' => CacheHelper::getTotalEpisodeCount(),
            'hentaiCount' => CacheHelper::getTotalHentaiCount(),
        ]);
    }

    /**
     * Manually set website language
     */
    public function updateLanguage(Request $request): RedirectResponse
    {
        abort_unless(in_array($request->language, config('app.supported_locales'), true), 404);

        session(['locale' => $request->language]);

        if (Auth::check()) {
            Auth::user()->update(['locale' => $request->language]);
        }

        return redirect()->back();
    }
}
