<?php

namespace App\Http\Controllers;

use SEO;
use App\Page;
use App\Split;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Http\Controllers\TMDB;
use Illuminate\Support\Facades\URL;
use Artesaos\SEOTools\Facades\SEOMeta;
use Illuminate\Pagination\LengthAwarePaginator;

class FrontendController extends Controller
{
    public function home(Request $request)
    {
        $this->getSEOMeta(
            __('seo.home_title'),
            __('seo.home_description')
        );

        if ($request->s != null) {
            $keyword = str_replace(' ', '-', $request->s);
            return redirect()->route('search', ['keyword' => $keyword]);
        }

        $tmdb = new TMDB;
        $movie_popular = $tmdb->getMovieTv('movie/popular');
        $movie_now_playing = $tmdb->getMovieTv('movie/now_playing');
        $movie_top_rated = $tmdb->getMovieTv('movie/top_rated');
        $movie_upcoming = $tmdb->getMovieTv('movie/upcoming');

        $tv_popular = $tmdb->getMovieTv('tv/popular');
        $tv_airing_today = $tmdb->getMovieTv('tv/airing_today');
        $tv_top_rated = $tmdb->getMovieTv('tv/top_rated');
        $tv_on_the_air = $tmdb->getMovieTv('tv/on_the_air');

        return view_theme('home', compact([
            'movie_popular',
            'movie_now_playing',
            'movie_top_rated',
            'movie_upcoming',
            'tv_popular',
            'tv_airing_today',
            'tv_top_rated',
            'tv_on_the_air',
        ]));
    }

    public function search($keyword, Request $request)
    {
        $page = $request->page ?? 1;
        $tmdb = new TMDB($page);
        $title = title_case(str_replace('-', ' ', $keyword));

        $data = $tmdb->getSearch($keyword);

        $data = new LengthAwarePaginator(
            block_id_lists($data->results),
            $data->total_results,
            20,
            $data->page,
            [ 'path' => route('search', ['keyword' => $keyword])]
        );

        $this->getSEOMeta($title, $title);

        return view(get_theme().'.search', compact('title', 'data'));
    }

    public function singleMovie($id, $slug = '')
    {
        if ( Str::contains($id, 'tt') ) {
            return $this->ifMovieIMDB($id);
        }

        $tmdb = new TMDB;
        $movie = $tmdb->getMovie($id);
        $backdrop = $this->randomBackdrop($movie);

        $this->getSEOMeta(
            __('seo.movie_title', ['title' => title_case($movie->title)]),
            __('seo.movie_title', ['title' => title_case($movie->title)]).' - '.$movie->overview,
            $backdrop,
            $this->getSeoKeywords($movie->keywords->keywords)
        );

        return view_theme('movie', compact([
            'movie', 'backdrop'
        ]));
    }

    public function moviePopular(Request $request)
    {
        $page = $request->page ?? 1;
        $type = 'movie';
        $tmdb = new TMDB($page);
        $data = $tmdb->getMovieTv('movie/popular');

        $data = new LengthAwarePaginator(
            block_id_lists($data->results),
            $data->total_results,
            20,
            $data->page,
            [ 'path' => route('movie.popular')]
        );

        $title = __('section.title.popular');

        $this->getSEOMeta(
            __('seo.movie_title', ['title' => title_case($title)]),
            __('seo.movie_title', ['title' => title_case($title)])
        );

        return view(get_theme().'.archive', compact('data', 'title', 'type'));
    }

    public function movieNowPlaying(Request $request)
    {
        $page = $request->page ?? 1;
        $type = 'movie';
        $tmdb = new TMDB($page);
        $data = $tmdb->getMovieTv('movie/now_playing');

        $data = new LengthAwarePaginator(
            block_id_lists($data->results),
            $data->total_results,
            20,
            $data->page,
            [ 'path' => route('movie.now.playing')]
        );

        $title = __('section.title.now_playing');

        $this->getSEOMeta(
            __('seo.movie_title', ['title' => title_case($title)]),
            __('seo.movie_title', ['title' => title_case($title)])
        );

        return view(get_theme().'.archive', compact('data', 'title', 'type'));
    }

    public function movieTopRated(Request $request)
    {
        $page = $request->page ?? 1;
        $type = 'movie';
        $tmdb = new TMDB($page);
        $data = $tmdb->getMovieTv('movie/top_rated');

        $data = new LengthAwarePaginator(
            block_id_lists($data->results),
            $data->total_results,
            20,
            $data->page,
            [ 'path' => route('movie.top.rated')]
        );

        $title = __('section.title.movie_top_rated');

        $this->getSEOMeta(
            __('seo.movie_title', ['title' => title_case($title)]),
            __('seo.movie_title', ['title' => title_case($title)])
        );

        return view(get_theme().'.archive', compact('data', 'title', 'type'));
    }

    public function movieUpcoming(Request $request)
    {
        $page = $request->page ?? 1;
        $type = 'movie';
        $tmdb = new TMDB($page);
        $data = $tmdb->getMovieTv('movie/upcoming');

        $data = new LengthAwarePaginator(
            block_id_lists($data->results),
            $data->total_results,
            20,
            $data->page,
            [ 'path' => route('movie.upcoming')]
        );

        $title = __('section.title.movie_upcoming');

        $this->getSEOMeta(
            __('seo.movie_title', ['title' => title_case($title)]),
            __('seo.movie_title', ['title' => title_case($title)])
        );

        return view(get_theme().'.archive', compact('data', 'title', 'type'));
    }

    public function singleTv($id, $slug = '')
    {
        if ( Str::contains($id, 'tt') ) {
            return $this->ifTvIMDB($id);
        }

        $tmdb = new TMDB;
        $tv = $tmdb->getTv($id);
        $season_info = $tmdb->getTvSeason($id, $tv->number_of_seasons);
        $season_select = $season_info->episodes;
        $backdrop = $this->randomBackdrop($tv);
        $title = $tv->name;
        $overview = $tv->overview;
        $air_date = $tv->first_air_date;

        $this->getSEOMeta(
            __('seo.tv_title', ['title' => title_case($title)]),
            __('seo.tv_title', ['title' => title_case($title)]).' - '.$overview,
            ($backdrop),
            $this->getSeoKeywords($tv->keywords->results)
        );

        return view_theme('tv', compact([
            'tv', 'backdrop', 'season_select', 'season_info', 'title', 'overview', 'air_date'
        ]));
    }

    public function tvPopular(Request $request)
    {
        $page = $request->page ?? 1;
        $type = 'tv';
        $tmdb = new TMDB($page);
        $data = $tmdb->getMovieTv('tv/popular');

        $data = new LengthAwarePaginator(
            block_id_lists($data->results),
            $data->total_results,
            20,
            $data->page,
            [ 'path' => route('tv.popular')]
        );

        $title = __('section.title.tv_popular');

        $this->getSEOMeta(
            __('seo.tv_title', ['title' => title_case($title)]),
            __('seo.tv_title', ['title' => title_case($title)])
        );

        return view(get_theme().'.archive', compact('data', 'title', 'type'));
    }

    public function tvTopRated(Request $request)
    {
        $page = $request->page ?? 1;
        $type = 'tv';
        $tmdb = new TMDB($page);
        $data = $tmdb->getMovieTv('tv/top_rated');

        $data = new LengthAwarePaginator(
            block_id_lists($data->results),
            $data->total_results,
            20,
            $data->page,
            [ 'path' => route('tv.top.rated')]
        );

        $title = __('section.title.tv_top_rated');

        $this->getSEOMeta(
            __('seo.tv_title', ['title' => title_case($title)]),
            __('seo.tv_title', ['title' => title_case($title)])
        );

        return view(get_theme().'.archive', compact('data', 'title', 'type'));
    }

    public function tvAiringToday(Request $request)
    {
        $page = $request->page ?? 1;
        $type = 'tv';
        $tmdb = new TMDB($page);
        $data = $tmdb->getMovieTv('tv/airing_today');

        $data = new LengthAwarePaginator(
            block_id_lists($data->results),
            $data->total_results,
            20,
            $data->page,
            [ 'path' => route('tv.airing.to.day')]
        );

        $title = __('section.title.tv_airing_today');

        $this->getSEOMeta(
            __('seo.tv_title', ['title' => title_case($title)]),
            __('seo.tv_title', ['title' => title_case($title)])
        );

        return view(get_theme().'.archive', compact('data', 'title', 'type'));
    }

    public function tvOnTheAir(Request $request)
    {
        $page = $request->page ?? 1;
        $type = 'tv';
        $tmdb = new TMDB($page);
        $data = $tmdb->getMovieTv('tv/on_the_air');

        $data = new LengthAwarePaginator(
            block_id_lists($data->results),
            $data->total_results,
            20,
            $data->page,
            [ 'path' => route('tv.on.the.air')]
        );

        $title = __('section.title.tv_on_the_air');

        return view(get_theme().'.archive', compact('data', 'title', 'type'));
    }

    public function singleTVSeason($id, $season, $slug = '')
    {
        if ( Str::contains($id, 'tt') ) {
            return $this->ifTvIMDB($id);
        }

        $tmdb = new TMDB;
        $tv = $tmdb->getTv($id);
        $season_info = $tmdb->getTvSeason($id, $season);
        $season_select = $season_info->episodes;

        $slug_title = str_slug($tv->name);

        if (empty($slug) || $slug != $slug_title) {
            return redirect()->route('tv.single.season', [
                'id' => $tv->id,
                'season' => $season,
                'slug' => $slug_title,
            ]);
        }

        $backdrop = $this->randomBackdrop($tv);
        $title = $tv->name.' '.$season_info->name;
        $overview = empty($season_info->overview) ? $tv->overview : $season_info->overview;
        $air_date = !empty($season_info->air_date) ? $season_info->air_date : $tv->first_air_date;

        $this->getSEOMeta(
            __('seo.tv_title', ['title' => title_case($title)]),
            __('seo.tv_title', ['title' => title_case($title)]).' - '.$overview,
            $backdrop,
            $this->getSeoKeywords($tv->keywords->results)
        );

        return view_theme('tv', compact([
            'tv', 'backdrop', 'season_select', 'season_info', 'season', 'title', 'overview', 'air_date'
        ]));
    }

    public function singleTVSeasonEpisode($id, $season, $episode, $slug = '')
    {
        if ( Str::contains($id, 'tt') ) {
            return $this->ifTvIMDB($id);
        }

        $tmdb = new TMDB;
        $tv = $tmdb->getTv($id);
        $season_info = $tmdb->getTvSeason($id, $season);
        $season_select = $season_info->episodes;
        $episode_info = $tmdb->getTvSeasonEpisode($id, $season, $episode);


        $slug_title = str_slug($tv->name);

        if (empty($slug) || $slug != $slug_title) {
            return redirect()->route('tv.single.season.episode', [
                'id' => $tv->id,
                'season' => $season,
                'episode' => $episode,
                'slug' => $slug_title,
            ]);
        }

        $backdrop = $episode_info->still_path != null ? $episode_info->still_path : $this->randomBackdrop($tv);
        $title = "{$tv->name} {$season_info->name} {$episode_info->name}";
        $overview = empty($episode_info->overview) ? $tv->overview : $episode_info->overview;
        $air_date = !empty($episode_info->air_date) ? $episode_info->air_date : $season_info->air_date;

        $this->getSEOMeta(
            __('seo.tv_title', ['title' => title_case($title)]),
            __('seo.tv_title', ['title' => title_case($title)]).' - '.$overview,
            $backdrop,
            $this->getSeoKeywords($tv->keywords->results)
        );

        return view_theme('tv', compact([
            'tv', 'backdrop', 'season_select', 'season_info', 'episode_info', 'season', 'title', 'overview', 'air_date'
        ]));
    }

    public function peoplePopular(Request $request)
    {
        $page = $request->page ?? 1;
        $tmdb = new TMDB($page);
        $type = 'people';

        $data = $tmdb->getPeoplePopular($page);

        $data = new LengthAwarePaginator(
            block_id_lists($data->results),
            $data->total_results,
            20,
            $data->page,
            [ 'path' => route('people.popular')]
        );

        $title = __('section.title.popular_people');

        $this->getSEOMeta(
            title_case($title),
            title_case($title)
        );

        return view(get_theme().'.archive', compact('data', 'title', 'type'));
    }

    public function people($id)
    {
        $tmdb = new TMDB;
        $data = $tmdb->getPeople($id);

        $title = $data->name;

        $this->getSEOMeta(
            title_case($title),
            title_case($title)
        );

        return view(get_theme().'.people', compact('data', 'title'));
    }

    public function genre($id, $slug = '', Request $request)
    {
        $page = $request->page ?? 1;
        $tmdb = new TMDB;
        $type = 'movie';

        $data = $tmdb->getGenreMovies($id, $page);

        $data = new LengthAwarePaginator(
            block_id_lists($data->results),
            $data->total_results,
            20,
            $data->page,
            [ 'path' => route('genre', ['id' => $id, 'slug' => $slug])]
        );

        if (str_slug($this->findNameGenre($id)) != str_slug($slug)) {
            return redirect(mopie_route('genre', ['id' => $id, 'slug' => str_slug($this->findNameGenre($id))]));
        }

        $title = title_case( __('section.title.movie_genre')).' "'.title_case(str_replace('-', ' ', $this->findNameGenre($id))).'"';

        $this->getSEOMeta(
            __('seo.movie_title', ['title' => title_case($title)]),
            __('seo.movie_title', ['title' => title_case($title)])
        );

        return view(get_theme().'.archive', compact('data', 'title', 'type'));
    }

    public function genreLists()
    {
        $tmdb = new TMDB;
        $data = $tmdb->getGenreLists();

        $genre = $data->genres;
        return $genre;
    }

    public function keyword($id, $slug = '', Request $request)
    {
        $page = $request->page ?? 1;
        $tmdb = new TMDB($page);
        $type = 'movie';

        $data = $tmdb->getKeywordMovie($id);

        $data = new LengthAwarePaginator(
            block_id_lists($data->results),
            $data->total_results,
            20,
            $data->page,
            [ 'path' => route('keyword', ['id' => $id, 'slug' => $slug])]
        );

        $title = title_case( str_replace('-', ' ', $slug) );

        // $this->getSEOMeta(
        //     __('seo.movie_title', ['title' => title_case($title)]),
        //     __('seo.movie_title', ['title' => title_case($title)])
        // );

        return view(get_theme().'.archive', compact('data', 'title', 'type'));
    }

    public function loading()
    {
        $split = Split::all();
        $offers = $split->filter(function($value) {
            return empty($value->country);
        });

        if(! empty(get_country_code()) ) {
            $offers = $split->filter(function($value) {
                return in_array(get_country_code(), $value->country);
            });
        }

        if ( $offers->isEmpty() ) {
            $offers = $split->filter(function($value) {
                return empty($value->country);
            });
        }

        $url_offer_register = $offers->first()->link_reg;
        $url_offer_play = $offers->first()->link_play;

        return view(get_theme().'.loading', compact(['url_offer_register', 'url_offer_play']));
    }

    public function pages(Page $page)
    {
        return view(get_theme().'.page', compact('page'));
    }

    private function findNameGenre($id)
    {
        foreach ($this->genreLists() as $data) {
            if ($data->id == $id) {
                $name = $data->name;
            }
        }

        return $name;
    }

    private function ifMovieIMDB($id)
    {
        $tmdb = new TMDB;
        $imdb = $tmdb->getImdbMovie($id);

        return redirect()->route('movie.single', [
            'id' => $imdb->id,
            'slug' => str_slug($imdb->original_title),
        ]);
    }

    private function ifTvIMDB($id)
    {
        $tmdb = new TMDB;
        $imdb = $tmdb->getImdbTv($id);

        if (!empty($imdb->tv_episode_results)) {
            $results = $imdb->tv_episode_results[0];
            return redirect()->route('tv.single.season.episode', [
                'id' => $results->show_id,
                'season' => $results->season_number,
                'episode' => $results->episode_number,
                'slug' => str_slug($results->name),
            ]);
        }

        $results = $imdb->tv_results[0];
        return redirect()->route('tv.single', [
            'id' => $results->id,
            'slug' => str_slug($results->original_name),
        ]);
    }

    private function randomBackdrop($path)
    {
        if (! empty($path->images->backdrops)) {
            $path = Arr::random($path->images->backdrops);
            return $path->file_path;
        }

        return $path->backdrop_path;
    }

    private function getSEOMeta($title, $description = '', $img = '', $keyword = [])
    {
        SEO::setTitle($title);
        SEO::setCanonical(URL::current());
        (empty($description))?:SEO::setDescription($description);
        (empty($img))?:SEO::addImages($img);
        (empty($keyword))?:\SEOMeta::addKeyword($keyword);

        $this->getHrefLang();
    }

    private function getSeoKeywords($data = [])
    {
        $kwList = [];

        foreach ($data as $data) {
            $kwList[] = $data->name;
        }

        return $kwList;
    }

    private function getHrefLang()
    {
        $hrefLang = [];

        foreach (get_locales() as $key => $value) {
            $replaceLang = str_replace(request()->segment(1), $key, request()->path());
            $url = request()->root().'/'.$replaceLang;
            $hrefLang[] = SEO::metatags()->addAlternateLanguage($key, $url);
        }

        return $hrefLang;
    }
}
