<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\MovieRequest;
use Exception;
use App\Repositories\Interfaces\Admin\MovieInterface;
use App\DataTables\Admin\MovieDataTable;
use App\DataTables\Admin\MovieFileDataTable;
use App\Http\Requests\Admin\RentRequest;
use App\Http\Requests\Admin\VideoFileRequest;
use App\Models\Category;
use App\Models\Country;
use App\Models\Genre;
use App\Models\Movie;
use App\Models\MovieFile;
use App\Models\Subtitle;
use App\Models\MovieLanguage;
use App\Models\Star;
use App\Models\TvShow;
use App\Models\VideoQuality;
use App\Traits\ImageTrait;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\File;

class MovieController extends Controller
{
    protected $movies;
    use ImageTrait;

    public function __construct(MovieInterface $movies)
    {
        $this->movies = $movies;
    }

    public function index(MovieDataTable $dataTable)
    {
        return $dataTable->render('admin.movies.index');
    }

    public function add()
    {
        $page_data['categories'] = Category::get();
        $page_data['stars'] = Star::get();
        $page_data['countries'] = Country::get();
        $page_data['genres'] = Genre::where('status', 1)->get();
        $page_data['languages'] = MovieLanguage::where('status', 1)->get();
        $page_data['video_qualities'] = VideoQuality::where('status', 1)->get();
        return view('admin.movies.add', $page_data);
    }

    public function store(MovieRequest $request)
    {
        if (isDemoMode()) {
            session()->flash('toastr_error', 'This action is disabled in demo mode.');
            return redirect()->route('admin.movies');
        }
        $this->movies->store($request->all());
        session()->flash('toastr_success', 'movie_create_successful!');
        return redirect()->route('admin.movies');
    }

    public function update(MovieRequest $request, $id)
    {
        if (isDemoMode()) {
            session()->flash('toastr_error', 'This action is disabled in demo mode.');
            return redirect()->route('admin.movies');
        }
        $this->movies->update($request->all(), $id);
        session()->flash('toastr_success', 'movie_update_successful!');
        return redirect()->route('admin.movies');
    }

    public function edit($id)
    {
        $page_data['categories'] = Category::get();
        $page_data['stars'] = Star::get();
        $page_data['countries'] = Country::get();
        $page_data['genres'] = Genre::where('status', 1)->get();
        $page_data['languages'] = MovieLanguage::where('status', 1)->get();
        $page_data['video_qualities'] = VideoQuality::where('status', 1)->get();
        $page_data['movie'] = Movie::where('id', $id)->first();
        return view('admin.movies.edit', $page_data);
    }

    public function delete($id)
    {
        if (isDemoMode()) {
            $data = [
                'status'    => 'error',
                'message'   => 'This action is disabled in demo mode.',
                'title'     => __('error'),
                'is_reload' => false,
            ];
            return response()->json($data);
        }
        if(!auth()->user()->can('admin.movie.delete')){
            $data = [
                'status'    => 'error',
                'message'   => __('you_are_not_authorized_to_perform_this_action'),
                'title'     => __('error'),
                'is_reload' => false,
            ];
            return response()->json($data);
        }
        $this->imageDelete($id, 'movie', 'poster');
        $this->imageDelete($id, 'movie', 'thumbnail');
        $movieDelete = Movie::where('id', $id)->delete();
        if ($movieDelete) {
            $data = [
                'title' => __('Success'),
                'status' => true,
                'message' => __('movie_delete_successfully'),
                'is_reload' => true,
            ];
            return $data;
        }
        return false;
    }

    public function upload_download_list(MovieFileDataTable $dataTable, $movie_id)
    {
        $movie = Movie::with('subtitles')->find($movie_id);
        $page_data['movie_id'] = $movie_id;
        $page_data['type'] = 'movie';
        $page_data['movie'] = $movie;
        $page_data['subtitles'] = $movie ? $movie->subtitles : collect();

        return $dataTable->with('movie_id', $movie_id)->render('admin.movies.video.index', $page_data);
    }

    public function file_add($movie_id)
    {
        $page_data['movie_id'] = $movie_id;
        return view('admin.movies.video.add', $page_data);
    }

    public function file_store(VideoFileRequest $request)
    {
        if (isDemoMode()) {
            session()->flash('toastr_error', 'This action is disabled in demo mode.');
            return redirect()->back();
        }
        try {
            $this->movies->file_store($request->all());
            session()->flash('toastr_success', __('movie_file_created_successfully'));
            return redirect()->back();
        } catch (Exception $e) {
            Log::error($e->getMessage());
            return response()->json(array('status' => 500, 'message' => $e->getMessage()));
        }
    }

    public function file_update(VideoFileRequest $request, $id)
    {
        if (isDemoMode()) {
            session()->flash('toastr_error', 'This action is disabled in demo mode.');
            return redirect()->back();
        }
        $update = $this->movies->file_update($request->all(), $id);

        if($update) {
            session()->flash('toastr_success', __('movie_file_update_successfully'));
        } else {
            session()->flash('toastr_error', __('movie_file_update_failed'));
        }
        return redirect()->back();
    }

    public function file_edit($id)
    {
        $data['file'] = MovieFile::where('id', $id)->first();
        return view('admin.movies.video.edit', $data);
    }

    public function file_delete($id)
    {
        if (isDemoMode()) {
            $data = [
                'status'    => 'error',
                'message'   => 'This action is disabled in demo mode.',
                'title'     => __('error'),
                'is_reload' => false,
            ];
            return response()->json($data);
        }
        $delete = $this->movies->file_delete($id);

        if($delete) {
            return [
                'title' => __('success'),
                'status' => true,
                'message' => __('movie_file_deleted_successfully'),
                'is_reload' => true,
            ];
        } else {
            return [
                'title' => __('error'),
                'status' => false,
                'message' => __('something_wrong'),
                'is_reload' => true,
            ];
        }
        
    }


    public function make_rental($type, $id)
    {
        try {
            if ($type == 'movie') {
                $page_data['video'] = Movie::findOrFail($id);
            } elseif ($type === 'tv_show') {
                $page_data['video'] = TvShow::findOrFail($id);
            }
            $page_data['type'] = $type;
            return view('admin.movies.rental.add', $page_data);
        } catch (Exception $e) {
            Log::error($e->getMessage());
            return response()->json(['status' => 'error', 'message' => $e->getMessage()], 500);
        }
    }

    public function make_rental_store(RentRequest $request)
    {
        if (isDemoMode()) {
            $data = [
                'status'    => 'error',
                'message'   => 'This action is disabled in demo mode.',
                'title'     => __('error'),
                'is_reload' => false,
            ];
            return response()->json($data);
        }
        try {
            $this->movies->make_rental_store($request->all());
            $data = [
                'status' => 'success',
                'message' => __('video_rental_successfully'),
                'title' => __('success'),
                'is_reload' => true,
            ];
            return response()->json($data);
        } catch (Exception $e) {
            $data = [
                'status' => 'error',
                'message' => __('video_rental_failed') . ': ' . $e->getMessage(),
                'title' => __('error'),
                'is_reload' => true,
            ];
            return response()->json($data);
        }
    }
}
