<?php

namespace App\Http\Controllers\Admin;

use App\DataTables\Admin\EpisodeDataTable;
use App\DataTables\Admin\EpisodeDownloadDataTable;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\EpisodeDownloadRequest;
use App\Http\Requests\Admin\EpisodeRequest;
use App\Models\Episode;
use App\Models\EpisodeDownload;
use App\Models\Season;
use App\Models\TvShow;
use App\Repositories\Interfaces\Admin\EpisodeInterface;
use App\Traits\ImageTrait;
use Illuminate\Support\Facades\File;

class EpisodeController extends Controller
{
    protected $episodes;
    use ImageTrait;

    public function __construct(EpisodeInterface $episodes)
    {
        $this->episodes = $episodes;
    }

    public function index(EpisodeDataTable $dataTable)
    {
        $seriesList = TvShow::orderBy('title')->get();
        $seasonList = Season::orderBy('order')->get();
        $selectedSeriesId = request()->get('series_id', '');
        $selectedSeasonId = request()->get('season_id', '');
        return $dataTable->render('admin.tv_show.episode.index', compact('seriesList', 'seasonList', 'selectedSeriesId', 'selectedSeasonId'));
    }

    public function add()
    {
        $page_data['seasons'] = Season::where('status', 1)->get();
        $page_data['tv_series'] = TvShow::where('status', 1)->get();
        return view('admin.tv_show.episode.add', $page_data);
    }

    public function store(EpisodeRequest $request)
    {
        if (isDemoMode()) {
            session()->flash('toastr_error', 'This action is disabled in demo mode.');
            return redirect()->back();
        }
        $this->episodes->store($request->all());
        session()->flash('toastr_success', 'episode_created_successfully.');
        return redirect()->back();
    }

    public function edit($id)
    {
        $data['episode'] = Episode::with('subtitles')->findOrFail($id);
        $data['subtitles'] = $data['episode']->subtitles;
        return view('admin.tv_show.episode.edit', $data);
    }

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

    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.episode.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, 'episode', 'poster');
        $episode_details = Episode::where('id', $id);
        $episode = $episode_details->first();

        if (!$episode) {
            return response()->json([
                'title'     => __('error'),
                'status'    => 'error',
                'message'   => __('episode_not_found'),
                'is_reload' => false,
            ]);
        }

        if ($episode->file_url) {
            delete_stored_movie_file($episode->source_type, $episode->file_url);
        }

        // Delete converted video folder: /public/uploads/videos/{slugified-label}-{id}
        $folderName = $episode->id;
        $convertedPath = public_path("uploads/episodes/{$folderName}");

        if (File::exists($convertedPath)) {
            File::deleteDirectory($convertedPath);
        }

        $episodeDelete = $episode_details->delete();
        if ($episodeDelete) {
            $data = [
                'title' => __('success'),
                'status' => true,
                'message' => __('episode_deleted_successfully'),
                'is_reload' => true,
            ];
            return $data;
        }
        return false;
    }
}
