<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Models\Anime;
use App\Models\Watchlist;
use App\Models\AnimeRating;
use App\Models\ContinueWatching;
use App\Models\AnimeFollow;

class AnimeController extends Controller
{
    public function show(Anime $anime)
    {
        abort_unless($anime->is_published, 404);

        $anime->load([
            'genres',
            'seasons' => fn($q) => $q->orderBy('season_number'),
            'seasons.episodes' => fn($q) => $q->where('is_published', true)->orderBy('episode_number'),
        ]);

        $related = Anime::whereHas('genres', fn($q) =>
            $q->whereIn('genres.id', $anime->genres->pluck('id'))
        )
        ->where('id', '!=', $anime->id)
        ->where('is_published', true)
        ->take(10)
        ->get();

        // Auth kullanıcı verileri
        $userWatchlist  = null;
        $userRating     = null;
        $continueEp     = null;
        $userFollowing  = false;

        if (auth()->check()) {
            $userWatchlist = Watchlist::where('user_id', auth()->id())
                ->where('anime_id', $anime->id)->first();
            $userRating = AnimeRating::where('user_id', auth()->id())
                ->where('anime_id', $anime->id)->value('rating');
            $continueEp = ContinueWatching::where('user_id', auth()->id())
                ->where('anime_id', $anime->id)
                ->where('percent_complete', '<', 95)
                ->first();
            $userFollowing = AnimeFollow::where('user_id', auth()->id())
                ->where('anime_id', $anime->id)->exists();
        }

        // Sosyal: Bu animeyi listeleyen son kullanıcılar
        $watchers = Watchlist::where('anime_id', $anime->id)
            ->when(auth()->id(), fn($q) => $q->where('user_id', '!=', auth()->id()))
            ->with('user:id,name,username,avatar')
            ->latest()
            ->limit(8)
            ->get()
            ->map(fn($w) => $w->user)
            ->filter();
        $watcherCount = Watchlist::where('anime_id', $anime->id)->count();

        return view('frontend.anime', compact('anime', 'related', 'userWatchlist', 'userRating', 'continueEp', 'userFollowing', 'watchers', 'watcherCount'));
    }
}
