<?php

namespace App\Http\Controllers;

use App\Models\Movies\Genre;
use App\Models\Movies\Movie;
use App\Models\Movies\MovieRating;
use App\Models\Movies\WatchHistory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class MovieController extends Controller
{
    // Fetch all movies + featured, popular, newest, and top-rated movies
    public function index(Request $request)
    {
        $genres = Genre::where('is_active', true)->withCount('movies')->get();
        $featuredMovies = Movie::active()->featured()->latest()->take(8)->get();
        $popularMovies = Movie::active()->popular()->take(8)->get();
        $newestMovies = Movie::active()->newest()->take(8)->get();
        $topRatedMovies = Movie::active()->topRated()->take(8)->get();

        // If API request, return JSON response
        if ($request->wantsJson()) {
            return response()->json([
                'status' => 200,
                'message' => 'Movies fetched successfully.',
                'data' => [
                    'genres' => $genres,
                    'featured_movies' => $featuredMovies,
                    'popular_movies' => $popularMovies,
                    'newest_movies' => $newestMovies,
                    'top_rated_movies' => $topRatedMovies,
                ]
            ]);
        }

        return view('front_end.pages.movies.index', compact(
            'genres',
            'featuredMovies',
            'popularMovies',
            'newestMovies',
            'topRatedMovies'
        ));
    }

    // Show movie details with related movies
    public function show(Request $request, $slug)
    {
        $movie = Movie::where('slug', $slug)->where('is_active', true)->firstOrFail();
        $movie->increment('views_count');

        $relatedMovies = Movie::where('genre_id', $movie->genre_id)
            ->where('id', '!=', $movie->id)
            ->where('is_active', true)
            ->take(4)
            ->get();

        $userRating = Auth::check() ? MovieRating::where('movie_id', $movie->id)
            ->where('user_id', Auth::id())->first() : null;

        // If API request, return JSON response
        if ($request->wantsJson()) {
            return response()->json([
                'status' => 200,
                'message' => 'Movie details fetched successfully.',
                'data' => [
                    'movie' => $movie,
                    'related_movies' => $relatedMovies,
                    'user_rating' => $userRating,
                ]
            ]);
        }

        return view('front_end.pages.movies.show', compact('movie', 'relatedMovies', 'userRating'));
    }

    // Watch a movie (Web & API)
    public function watch(Request $request, $slug)
    {
        $movie = Movie::where('slug', $slug)->where('is_active', true)->firstOrFail();

        // Record watch history for authenticated users
        if (Auth::check()) {
            WatchHistory::updateOrCreate(
                ['user_id' => Auth::id(), 'movie_id' => $movie->id],
                ['last_watched_at' => now()]
            );
        }

        // If API request, return JSON response
        if ($request->wantsJson()) {
            return response()->json([
                'message' => 'Movie available to watch',
                'movie' => $movie,
                'stream_url' => $movie->stream_url ?? null,
            ]);
        }

        return view('front_end.pages.movies.watch', compact('movie'));
    }

    // Fetch movies by genre
    public function byGenre(Request $request, $slug)
    {
        $genre = Genre::where('slug', $slug)->where('is_active', true)->firstOrFail();
        $movies = Movie::where('genre_id', $genre->id)->where('is_active', true)->paginate(12);

        // If API request, return JSON response
        if ($request->wantsJson()) {
            return response()->json([
                'genre' => $genre,
                'movies' => $movies,
            ]);
        }

        return view('front_end.pages.movies.by_genre', compact('genre', 'movies'));
    }

    // Search movies
    public function search(Request $request)
    {
        $query = Movie::query()->where('is_active', true);

        if ($request->has('q')) {
            $query->where('title', 'like', '%' . $request->q . '%');
        }

        if ($request->has('genre')) {
            $query->where('genre_id', $request->genre);
        }

        if ($request->has('featured')) {
            $query->where('featured', true);
        }

        if ($request->has('sort')) {
            switch ($request->sort) {
                case 'popularity':
                    $query->orderBy('views_count', 'desc');
                    break;
                case 'newest':
                    $query->orderBy('created_at', 'desc');
                    break;
                case 'rating':
                    $query->withAvg('ratings', 'rating')
                        ->orderBy('ratings_avg_rating', 'desc');
                    break;
                default:
                    $query->latest();
            }
        }

        $movies = $query->paginate(12);

        // If API request, return JSON response
        if ($request->wantsJson()) {
            return response()->json([
                'status' => 200,
                'message' => 'Movies fetched successfully.',
                'data' => $movies
            ]);
        }

        return view('front_end.pages.movies.search', compact('movies'));
    }

    // Rate a movie (Authenticated Users Only)
    public function rate(Request $request, Movie $movie)
    {
        $request->validate([
            'rating' => 'required|integer|min:1|max:5',
            'review' => 'nullable|string|max:500'
        ]);

        if (!Auth::check()) {
            return $request->wantsJson()
                ? response()->json(['status' => 401, 'message' => 'Unauthorized'], 401)
                : redirect()->back()->with('error', 'You need to be logged in to rate movies.');
        }

        MovieRating::updateOrCreate(
            ['user_id' => Auth::id(), 'movie_id' => $movie->id],
            ['rating' => $request->rating, 'review' => $request->review]
        );

        return $request->wantsJson()
            ? response()->json(['status' => 200, 'message' => 'Rating submitted successfully'])
            : redirect()->back()->with('success', 'Thank you for your rating!');
    }

    /**
     * Show movie details by ID.
     */
    public function getMovieDetailById(Request $request, $id)
    {
        $movie = Movie::findOrFail($id);
        $movie->increment('views_count');

        $relatedMovies = Movie::where('genre_id', $movie->genre_id)
            ->where('id', '!=', $movie->id)
            ->where('is_active', true)
            ->take(4)
            ->get();

        $userRating = Auth::check() ? MovieRating::where('movie_id', $movie->id)
            ->where('user_id', Auth::id())->first() : null;

        // If API request, return JSON response
        if ($request->wantsJson()) {
            return response()->json([
                'status' => 200,
                'message' => 'Movie details fetched successfully.',
                'data' => [
                    'movie' => $movie,
                    'related_movies' => $relatedMovies,
                    'user_rating' => $userRating,
                ]
            ]);
        }

        return view('front_end.pages.movies.show', compact('movie', 'relatedMovies', 'userRating'));
    }
}
