<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Http\Requests\Website\PlayListRequest;
use App\Models\Movie;
use App\Models\MovieFile;
use App\Models\PlayList;
use Exception;
use Illuminate\Http\Request;
use App\Repositories\Interfaces\Website\PlayListRepositoryInterface;
use Illuminate\Support\Facades\Log;
class PlayListController extends Controller
{

    protected $playlistRepo;

    public function __construct(PlayListRepositoryInterface $playlistRepo)
    {
        $this->playlistRepo = $playlistRepo;
    }


    public function store(PlayListRequest $request)
    {
        try {
            $data = $request->validated();
            $playlist = $this->playlistRepo->store($data);
            if (!$playlist) {
                return redirect()->back()->with(
                    'error',
                    __('failed_to_create_playlist'),
                );
            }
            if (request()->ajax()) {
                return response()->json([
                    'message' => __('playlist_created_successfully'),
                    'data' => $playlist
                ]);
            }
            return redirect()->back()->with(
                'success',
                __('playlist_created_successfully')
            );


        } catch (Exception $e) {
            Log::error('Error creating playlist: ' . $e->getMessage(), );
            return redirect()->back()->with(
                'error',
                __('an_error_occurred_while_creating_the_playlist'),
            );

        }
    }

    public function update(
        PlayListRequest $request,
        PlayList $playlist

    ) {
        try {
            $data = $request->validated();
            $updatedPlaylist = $this->playlistRepo->update(
                $playlist,
                $data
            );

            if (!$updatedPlaylist) {
                return redirect()->back()->with(
                    'error',
                    __('failed_to_update_playlist'),
                );

            }
            return redirect()->back()->with(
                'success',
                __('playlist_updated_successfully')
            );

        } catch (Exception $e) {
            Log::error('Error updating playlist: ' . $e->getMessage(), );
            return redirect()->back()->with(
                'error',
                __('an_error_occurred_while_updating_the_playlist'),
            );

        }
    }

    public function destroy(PlayList $playlist)
    {
        try {
            $deleted = $this->playlistRepo->delete(
                $playlist
            );

            if (!$deleted) {
                return response()->json([
                    'message' => __('failed_to_delete_playlist')
                ], 400);
            }

            return response()->json([
                'message' => __('playlist_deleted_successfully')
            ], 200);
        } catch (Exception $e) {
            Log::error('Error deleting playlist: ' . $e->getMessage());
            return response()->json([
                'message' => __('an_error_occurred_while_deleting_the_playlist')
            ], 500);
        }
    }
    public function show($slug, $movie_slug = null)
    {
        $playlist = PlayList::where('slug', $slug)->first();
        if (! $playlist) {
            abort(404, __('page_not_found'));
        }

        $data['playlist_movies'] = $this->playlistRepo->getPlayListVideos($playlist);
        $playlist->loadCount('movies');
        $data['playlist_details'] = $playlist;

        $movie = null;
        if (! empty($movie_slug)) {
            $movie = $playlist->movies()->where('slug', $movie_slug)->first();
        }
        if (! $movie) {
            $movie = $playlist->movies()->orderByPivot('created_at', 'desc')->first();
        }
        if (! $movie) {
            return redirect()
                ->route('user.dashboard', ['tab' => 'playlist'])
                ->with('error_message', __('no_videos_available'));
        }

        if (! empty($movie_slug) && $movie->slug !== $movie_slug) {
            return redirect()->route('playlist.movie', [
                'playlist' => $playlist->slug,
                'slug' => $movie->slug,
            ]);
        }

        $data['movie'] = $movie;
        $data['movie_files'] = MovieFile::where('video_id', $movie->id)->orderBy('order', 'ASC')->get();
        $data['moviePlaylistIds'] = $movie->playlists->pluck('id')->toArray();

        return view('website.play_list_details', $data);
    }
    public function addMovieToPlaylist(Request $request)
    {
        try {
            $success = $this->playlistRepo->addMovieToPlaylist(
                $request->input('playlist_ids'),
                $request->input('movie_id')
            );

            if (!$success) {
                return response()->json([
                    'status' => 'error',
                    'message' => __('movie_could_not_be_added_to_playlist')
                ], 400);
            }
            return response()->json([
                'status' => 'success',
                'message' => __('movie_added_to_playlist')
            ], 200);
        } catch (Exception $e) {
            Log::error('Error adding movie to playlist: ' . $e->getMessage());
            return response()->json([
                'status' => 'error',
                'message' => __('an_error_occurred_while_adding_movie_to_playlist')
            ], 500);
        }
    }

    public function removeMovieFromPlaylist(Request $request)
    {
        try {
            $playlist = PlayList::find($request->input('playlist_id'));

            if (!$playlist) {
                return response()->json([
                    'status' => 'error',
                    'message' => __('playlist_not_found')
                ], 404);
            }

            $success = $this->playlistRepo->removeMovieFromPlaylist(
                $playlist,
                $request->input('movie_id')
            );

            if (!$success) {
                return response()->json([
                    'status' => 'error',
                    'message' => __('movie_could_not_be_removed')
                ], 400);
            }
            return response()->json([
                'status' => 'success',
                'message' => __('movie_removed_from_playlist')
            ], 200);
        } catch (Exception $e) {
            Log::error('Error removing movie from playlist: ' . $e->getMessage());
            return response()->json([
                'status' => 'error',
                'message' => __('an_error_occurred_while_removing_movie')
            ], 500);
        }
    }

    public function getPlayListIds(Movie $movie)
    {

        return response()->json([
            'playlist_ids' => $this->playlistRepo->getPlayListIds($movie),
        ]);
    }
}
