<?php
namespace App\Repositories\Website;

use App\Models\Movie;
use App\Models\PlayList;
use App\Repositories\Interfaces\Website\PlayListRepositoryInterface;
use App\Traits\ImageTrait;
use Exception;
use Illuminate\Support\Facades\Log;

class PlayListRepository implements PlayListRepositoryInterface
{
    use ImageTrait;
    public function all()
    {
        return PlayList::withMovieCount()->get();
    }

    public function find($id)
    {
        return PlayList::withMovieCount()->findOrFail($id);
    }

    public function store($request)
    {
        try {
            if (isset($request['thumbnail'])) {
                $requestImage = $request['thumbnail'];
                $response = $this->saveImage($requestImage, '_movie_');

                $thumbnail = $response['images'];
            }
            $data = [
                'user_id' => $request['user_id'] ?? auth()->user()->id,
                'name' => $request['name'],
                'slug' => slugify($request['name']),
                'thumbnail' => !empty($thumbnail) ? json_encode($thumbnail) : null,
            ];

            return PlayList::create($data);
        } catch (Exception $e) {
            Log::error('play list store:' . $e->getMessage());

            throw $e;
        }
    }

    public function update($playlist, $request)
    {
        try {
            if (isset($request['thumbnail'])) {
                $this->deleteImage(json_decode($playlist->thumbnail, true));

                $requestImage = $request['thumbnail'];
                $response = $this->saveImage($requestImage, '_movie_');

                $thumbnail = $response['images'];
            }
            $data = [
                'user_id' => $request['user_id'] ?? auth()->user()->id,
                'slug' => slugify($request['name']),
                'name' => $request['name'] ?? $playlist->name,
                'thumbnail' => !empty($thumbnail) ? json_encode($thumbnail) : $playlist->thumbnail,
            ];

            $playlist->update($data);
            return $playlist;
        } catch (Exception $e) {
            Log::error('play list update:' . $e->getMessage());

            throw $e;
        }
    }

    public function delete($playlist)
    {
        try {
            if ($playlist->thumbnail) {
                $this->deleteImage(json_decode($playlist->thumbnail, true));
            }

            return $playlist->delete();
        } catch (Exception $e) {
            Log::error('play list delete:' . $e->getMessage());

            throw $e;
        }
    }
    public function getPlayListVideos($playlist)
    {
        return $playlist->movies;
    }
    public function addMovieToPlaylist($playlistIds, $movieId)
    {
        try {
            $movie = Movie::find($movieId);
            $movie->playLists()->sync($playlistIds);
            foreach ($playlistIds as $playlistId) {
                $playlist = PlayList::find($playlistId);
                $this->updatePlaylistThumbnail($playlist);
            }

            return true;
        } catch (Exception $e) {
            Log::error('Error adding movie to playlist: ' . $e->getMessage(), );
            throw $e;
        }
    }

    public function removeMovieFromPlaylist($playlist, $movieId)
    {
        try {

            $playlist->movies()->detach($movieId);

            $this->updatePlaylistThumbnail($playlist);

            return true;

        } catch (Exception $e) {
            Log::error('Error removing movie from playlist: ' . $e->getMessage(), );
            throw $e;
        }
    }
    private function updatePlaylistThumbnail($playlist)
    {
        $latestMovie = $playlist->movies()
            ->orderBy('pivot_created_at', 'desc')
            ->first();

        $playlist->thumbnail = $latestMovie ? $latestMovie->thumbnail : null;
        $playlist->save();
    }

    public function getPlayListIds($movie)
    {
        return $movie?->playLists->pluck('id')->toArray() ?? [];
    }

}
