<?php

namespace App\Repositories\Admin;

use App\Models\Movie;
use App\Models\MovieFile;
use App\Models\TvShow;
use App\Repositories\Interfaces\Admin\MovieInterface;
use Carbon\Carbon;
use App\Traits\ImageTrait;
use Illuminate\Http\UploadedFile;

use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use App\Jobs\ProcessVideoConversion;

class MovieRepository implements MovieInterface
{
    use ImageTrait;

    public function all()
    {
        return Movie::get();
    }

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

            $data = [
                'title' => $request['title'],
                'slug' => $request['slug'],
                'seo_title' => $request['seo_title'],
                'description' => $request['description'],
                'stars' => json_encode($request['actor']),
                'director' => json_encode($request['director']),
                'writer' => json_encode($request['writer']),
                'rating' => $request['imdb_rating'],
                'release' => $request['date'],
                'country' => json_encode($request['country']),
                'genre' => json_encode($request['genre']),
                'language' => json_encode($request['language']),
                'video_type' => $request['video_type'],
                'runtime' => $request['runtime'],
                'video_quality' => $request['video_quality'],
                'is_trending' => $request['is_trending'],
                'is_featured' => $request['is_featured'],
                'is_recommended' => $request['is_recommended'],
                'is_original' => $request['is_original'],
                'is_blockbuster' => $request['is_blockbuster'],
                'is_real_life_story' => $request['is_real_life_story'],
                'status' => $request['status'],
                'trailer' => $request['trailer_youtube_source'] ? 1 : 0,
                'trailler_youtube_source' => $request['trailer_youtube_source'],
                'enable_download' => $request['enable_download'],
                'focus_keyword' => $request['focus_keyword'],
                'meta_description' => $request['meta_description'],
                'tags' => $request['tags'],
                'imdb_rating' => $request['imdb_rating'],
                'is_tvseries' => 0,
                'total_rating' => 0,
                'today_view' => 0,
                'weekly_view' => 0,
                'monthly_view' => 0,
                'total_view' => 0,
                'last_ep_added' => Carbon::now(),
                'imdbid' => 0,
                'tmdb_id' => 0,
                'thumbnail' => isset($thumbnail) ? json_encode($thumbnail) : '',
                'poster' => isset($poster) ? json_encode($poster) : '',

                'is_free' => (int)$request['is_free'],
                'is_rental' => (int)$request['is_rental'],

                'rental_price'      => isset($request['rental_price']) ? (int)$request['rental_price'] : 0,
                'rental_duration'   => isset($request['rental_duration']) ? (int)$request['rental_duration'] : 0,
                'rental_type'   => isset($request['rental_type']) ? $request['rental_type'] : null,

                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now(),
            ];
            return Movie::create($data);
        } catch (\Exception $e) {
            throw $e;
        }
    }

    public function update($request, $id)
    {
        try {
            $movie = Movie::where('id', $id)->first();

            if (isset($request['thumbnail']) && $request['thumbnail'] instanceof UploadedFile) {
                $this->imageDelete($id, 'movie', 'thumbnail');
                $requestImage = $request['thumbnail'];
                $response = $this->saveImage($requestImage, '_movie_');
                $request['thumbnail'] = $response['images'];
            }

            if (isset($request['poster']) && $request['poster'] instanceof UploadedFile) {
                $this->imageDelete($id, 'movie', 'poster');
                $requestImage = $request['poster'];
                $response = $this->saveImage($requestImage, '_movie_');
                $request['poster'] = $response['images'];
            }

            $data = [
                'title' => $request['title'],
                'slug' => $request['slug'],
                'seo_title' => $request['seo_title'],
                'description' => $request['description'],
                'stars' => $request['actor'],
                'director' => $request['director'],
                'writer' => $request['writer'],
                'rating' => $request['imdb_rating'],
                'release' => $request['date'],
                'country' => json_encode($request['country']),
                'genre' => json_encode($request['genre']),
                'language' => json_encode($request['language']),
                'video_type' => $request['video_type'],
                'runtime' => $request['runtime'],
                'video_quality' => $request['video_quality'],
                'is_trending' => $request['is_trending'],
                'is_featured' => $request['is_featured'],
                'is_recommended' => $request['is_recommended'],
                'is_original' => $request['is_original'],
                'is_blockbuster' => $request['is_blockbuster'],
                'is_real_life_story' => $request['is_real_life_story'],
                'status' => $request['status'],
                'trailer' => $request['trailer_youtube_source'] ? 1 : 0,
                'trailler_youtube_source' => $request['trailer_youtube_source'],
                'enable_download' => $request['enable_download'],
                'focus_keyword' => $request['focus_keyword'],
                'meta_description' => $request['meta_description'],
                'tags' => $request['tags'],
                'imdb_rating' => $request['imdb_rating'],
                'is_tvseries' => 0,
                'total_rating' => 0,
                'today_view' => 0,
                'weekly_view' => 0,
                'monthly_view' => 0,
                'total_view' => 0,
                'last_ep_added' => Carbon::now(),
                'imdbid' => 0,
                'tmdb_id' => 0,
                'thumbnail' => isset($request['thumbnail']) ? json_encode($request['thumbnail']) : $movie->thumbnail,
                'poster' => isset($request['poster']) ? json_encode($request['poster']) : $movie->poster,
                'updated_at' => Carbon::now(),

                'is_free' => (int)$request['is_free'],
                'is_rental' => (int)$request['is_rental'],
                'rental_price'      => $request['is_rental'] ? (int)$request['rental_price'] : 0,
                'rental_duration'   => $request['is_rental'] ? (int)$request['rental_duration'] : 0,
                'rental_type'   => $request['is_rental'] ? $request['rental_type'] : null,
            ];
            return Movie::where('id', $id)->update($data);
        } catch (\Exception $e) {
            return false;
        }
    }

    public function file_store($request)
    {

        try {
            if(isset($request['video_file'])) {
                $file = $request['video_file'];
                $filename = uniqid() . '_' . time() . '.' . $file->getClientOriginalExtension();
                $destinationPath = public_path('uploads/videos');
    
                if (!File::exists($destinationPath)) {
                    File::makeDirectory($destinationPath, 0775, true);
                }
    
                $file->move($destinationPath, $filename);
                $relativePath = 'uploads/videos/' . $filename;
    
                $movieFile = MovieFile::create([
                    'video_id' => $request['video_id'],
                    'label' => $request['label'],
                    'file_source' => $request['source'],
                    'source_type' => $request['source'],
                    'file_url' => $relativePath,
                    'order' => $request['order'],
                    'stream_key' => Str::uuid(),
                    'created_at' => Carbon::now(),
                    'updated_at' => Carbon::now(),
                ]);
    
                // Dispatch background job for video conversion
                dispatch(new ProcessVideoConversion(
                    $movieFile,
                    public_path($relativePath),
                    $file->getClientOriginalExtension()
                ));
    
                return response()->json([
                    'status' => true,
                    'message' => 'Video uploaded and queued for conversion successfully.',
                    'data' => $movieFile
                ]);
            } else {
                $movieFile = MovieFile::create([
                    'video_id' => $request['video_id'],
                    'label' => $request['label'],
                    'file_source' => $request['source'],
                    'source_type' => $request['source'],
                    'file_url' => $request['file_url'],
                    'order' => $request['order'],
                    'stream_key' => Str::uuid(),
                    'created_at' => Carbon::now(),
                    'updated_at' => Carbon::now(),
                ]);
                return $movieFile;
            }
        } catch (\Exception $e) {
            logger()->error('Video upload or conversion queue failed', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            return response()->json([
                'status' => false,
                'message' => 'Video upload failed. Please check logs.'
            ], 500);
        }
    }



    public function file_update($request, $id)
    {
        try {
            $movieFile = MovieFile::findOrFail($id);
            // Handle local upload
            if ($request['source'] === 'local' && isset($request['video_file'])) {
                // Delete previous file if exists
                $oldFilePath = public_path($movieFile->file_url);
                if ($movieFile->file_source === 'local' && file_exists($oldFilePath)) {
                    @unlink($oldFilePath);
                }

                // Upload original file to temp folder
                $file = $request['video_file'];
                $filename = uniqid() . '_' . time() . '.' . $file->getClientOriginalExtension();
                $destinationPath = public_path('uploads/videos');

                if (!File::exists($destinationPath)) {
                    File::makeDirectory($destinationPath, 0775, true);
                }

                $file->move($destinationPath, $filename);
                $relativePath = 'uploads/videos/' . $filename;

                MovieFile::where('id', $id)->update([
                    'label' => $request['label'],
                    'file_source' => $request['source'],
                    'source_type' => $request['source'],
                    'file_url' => $relativePath,
                    'order' => $request['order'],
                    'updated_at' => Carbon::now(),
                ]);

                // Dispatch conversion job
                dispatch(new ProcessVideoConversion(
                    $movieFile,
                    public_path($relativePath),
                    $file->getClientOriginalExtension()
                ));

                return response()->json([
                    'status' => true,
                    'message' => 'Video uploaded and queued for conversion successfully.',
                    'data' => $movieFile
                ]);
            } else {
                $movieFile = MovieFile::where('id', $id)->update([
                    'label' => $request['label'],
                    'file_source' => $request['source'],
                    'source_type' => $request['source'],
                    'file_url' => $request['file_url'],
                    'order' => $request['order'],
                    'updated_at' => Carbon::now(),
                ]);
                return response()->json([
                    'status' => true,
                    'message' => 'Video uploaded and queued for conversion successfully.',
                    'data' => $movieFile
                ]);
            }
        } catch (\Exception $e) {
            logger()->error('File update failed', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);
            return false;
        }
    }


    public function make_rental_store($request, $id = null)
    {
        try {
            $data = [
                'price' => $request['price'],
                'hours' => $request['hours'],
                'note' => $request['note'],
                'updated_at' => Carbon::now(),
            ];
            if ($request['type'] === 'movie') {
                return Movie::where('id', $request['id'])->update($data);
            } elseif ($request['type'] === 'tv_show') {
                return TvShow::where('id', $request['id'])->update($data);
            }
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }
}
