<?php

namespace App\Http\Controllers;

use App\Models\Episode;
use App\Models\Gallery;
use App\Models\Hentai;
use App\Models\Playlist;
use App\Models\PlaylistEpisode;
use App\Models\Watched;
use App\Helpers\CacheHelper;

use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;

use hisorange\BrowserDetect\Facade as Browser;

class StreamController extends Controller
{
    /**
     * Display Stream Page.
     */
    public function index(Request $request, string $title): \Illuminate\View\View
    {
        $titleParts = explode('-', $title);
        if (! is_numeric($titleParts[array_key_last($titleParts)])) {
            $hentai = Hentai::with('episodes')->where('slug', $title)->firstOrFail();

            if (Auth::guest() && $hentai->isLoliOrShota()) {
                return view('auth.please-login');
            }

            return view('series.index', [
                'hentai'        => $hentai,
                'popularWeekly' => CacheHelper::getPopularWeekly(),
            ]);
        }


        $episode = Episode::where('slug', $title)->firstOrFail();
        $gallery = Gallery::where('episode_id', $episode->id)->get();
        $moreEpisodes = Episode::with(['gallery', 'studio'])->where('hentai_id', $episode->hentai_id)->whereNot('id', $episode->id)->get();
        $studioEpisodes = Episode::with(['gallery', 'studio'])->inRandomOrder()->where('studios_id', $episode->studios_id)->whereNot('id', $episode->id)->limit(6)->get();

        // Only allow access to problematic stuff when logged in
        if (Auth::guest() && $episode->isLoliOrShota()) {
            return view('auth.please-login');
        }

        // Increment View Count
        $episode->incrementViewCount();

        // Increment Popular Count
        $episode->incrementPopularCount();

        if (!Auth::guest()) {
            $user = Auth::user();

            // Add to user watched list
            $time = Carbon::now()->subHour(1);
            $alreadyWatched = Watched::where('user_id', $user->id)->where('episode_id', $episode->id)->where('created_at', '>=', $time)->exists();
            if (!$alreadyWatched) {
                Watched::create(['user_id' => $user->id, 'episode_id' => $episode->id]);
                cache()->forget('user' . $user->id . 'watched' . $episode->id);
            }
        }

        // Mobile Detection
        $isMobile = Browser::isMobile();

        // Playlist
        if ($request->has('playlist')) {
            // Get and check if playlist exists
            $playlist = Playlist::where('id', $request->input('playlist'))->firstOrFail();

            // Check if episode is in playlist
            $inPlaylist = PlaylistEpisode::where('playlist_id', $playlist->id)->where('episode_id', $episode->id)->firstOrFail();

            // Get Playlist Episodes and order them
            $playlistEpisodes = $playlist->episodes()->orderBy('position')->get();

            // Check if authorized
            if ($playlist->is_private && (Auth::guest() || (!Auth::guest() && Auth::user()->id != $playlist->user_id))) {
                abort(404);
            }

            return view('stream.index', [
                'episode'           => $episode,
                'moreEpisodes'      => $moreEpisodes,
                'studioEpisodes'    => $studioEpisodes,
                'gallery'           => $gallery,
                'playlist'          => $playlist,
                'playlistEpisodes'  => $playlistEpisodes,
                'popularWeekly'     => CacheHelper::getPopularWeekly(),
                'isMobile'          => $isMobile,
            ]);
        }

        return view('stream.index', [
            'episode'           => $episode,
            'moreEpisodes'      => $moreEpisodes,
            'studioEpisodes'    => $studioEpisodes,
            'gallery'           => $gallery,
            'popularWeekly'     => CacheHelper::getPopularWeekly(),
            'isMobile'          => $isMobile,
        ]);
    }
}
