<?php

use App\Option;
use App\Language;
use GeoIp2\Database\Reader;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
use App\Http\Controllers\Admin\TemplateController;

if (! function_exists('is_serialized')) {
    function is_serialized( $data, $strict = true ) {
        // If it isn't a string, it isn't serialized.
        if ( ! is_string( $data ) ) {
            return false;
        }
        $data = trim( $data );
        if ( 'N;' == $data ) {
            return true;
        }
        if ( strlen( $data ) < 4 ) {
            return false;
        }
        if ( ':' !== $data[1] ) {
            return false;
        }
        if ( $strict ) {
            $lastc = substr( $data, -1 );
            if ( ';' !== $lastc && '}' !== $lastc ) {
                return false;
            }
        } else {
            $semicolon = strpos( $data, ';' );
            $brace     = strpos( $data, '}' );
            // Either ; or } must exist.
            if ( false === $semicolon && false === $brace ) {
                return false;
            }
            // But neither must be in the first X characters.
            if ( false !== $semicolon && $semicolon < 3 ) {
                return false;
            }
            if ( false !== $brace && $brace < 4 ) {
                return false;
            }
        }
        $token = $data[0];
        switch ( $token ) {
            case 's':
                if ( $strict ) {
                    if ( '"' !== substr( $data, -2, 1 ) ) {
                        return false;
                    }
                } elseif ( false === strpos( $data, '"' ) ) {
                    return false;
                }
                // Or else fall through.
            case 'a':
            case 'O':
                return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
            case 'b':
            case 'i':
            case 'd':
                $end = $strict ? '$' : '';
                return (bool) preg_match( "/^{$token}:[0-9.E+-]+;$end/", $data );
        }
        return false;
    }
}

if (! function_exists('asset_admin')) {
    function asset_admin($path, $secure = null) {
        return app('url')->asset('/engine/resources/views/'.$path, $secure);
    }
}

if (! function_exists('asset_theme')) {
    function asset_theme($path, $secure = null) {
        return asset('/themes/'.get_theme().'/'.$path, $secure);
    }
}

if (! function_exists('get_setting')) {
    function get_setting($string) {
        if (alreadyInstalled()) {
            return Option::getSetting($string);
        }

        return config("mopie.{$string}");
    }
}

if (! function_exists('get_site_name')) {
    function get_site_name() {
        if (alreadyInstalled()) {
            return Option::getSetting('site_name');
        }

        return config('mopie.site_name');
    }
}

if (! function_exists('get_theme')) {
    function get_theme() {
        if (alreadyInstalled()) {
            return Option::getSetting('theme');
        }

        return config('mopie.theme');
    }
}

if (! function_exists('get_tmdb_key')) {
    function get_tmdb_key() {
        if (alreadyInstalled()) {
            return Option::getSetting('tmdb_key');
        }

        return config('mopie.tmdb_key');
    }
}

if (! function_exists('get_default_language')) {
    function get_default_language() {
        if (alreadyInstalled()) {
            return Option::getSetting('default_lang');
        }

        return config('mopie.default_lang');
    }
}

if (! function_exists('do_template')) {
    function do_template(String $string, Array $data) {
        $templateController = new TemplateController();
        return $templateController->progress($string, $data);
    }
}

if (! function_exists('is_cache') ) {
    function is_cache() {
        if (alreadyInstalled()) {
            return Option::getSetting('is_cache');
        }

        return config('mopie.is_cache');
    }
}

if (! function_exists('get_cache_expired') ) {
    function get_cache_expired() {
        if (alreadyInstalled()) {
            return Option::getSetting('cache_expired');
        }

        return config('mopie.cache_expired');
    }
}

if (! function_exists('view_theme')) {
    function view_theme($name, $data = []) {
        return view(get_theme().'.'.$name, $data);
    }
}

if (! function_exists('mopie_route')) {
    function mopie_route($name, $parameters = [], $absolute = true)
    {
        if (isset($_REQUEST['sub_id'])) {
            if (is_array($parameters)) {
                return app('url')->route($name, array_merge(['sub_id' => $_REQUEST['sub_id']], $parameters), $absolute);
            }

            return app('url')->route($name, ['sub_id' => $_REQUEST['sub_id']], $absolute);
        }

        return app('url')->route($name, $parameters, $absolute);
    }
}

if (! function_exists('block_id_lists')) {
    function block_id_lists(array $results) {
        $block_movie = alreadyInstalled() ? Option::getSetting('block_movie') : config('mopie.block_movie');
        $block_tv = alreadyInstalled() ? Option::getSetting('block_tv') : config('mopie.block_tv');
        $block = array_merge($block_movie, $block_tv);
        $results = collect($results)->whereNotIn('id', $block);

        return $results->all();
    }
}

if (! function_exists('str_slug')) {
    function str_slug(string $string) {
        return Str::slug($string);
    }
}

if (! function_exists('to_year')) {
    function to_year($release_date) {
        if (! empty($release_date)) {
            return Str::before($release_date, '-');
        }

        return false;
    }
}

if (! function_exists('img_poster')) {
    function img_poster($path, $size = 'w300') {
        if (empty($path)) {
            return asset_theme('assets/no-poster.png');
        }

        return '//i0.wp.com/image.tmdb.org/t/p/'.$size.$path;
    }
}

if (! function_exists('img_backdrop')) {
    function img_backdrop($path, $size = 'w780')
    {
        if (empty($path)) {
            return asset_theme('assets/no-backdrop.png');
        }
        return '//i0.wp.com/image.tmdb.org/t/p/'.$size.$path;
    }
}

if (! function_exists('get_locales')) {
    function get_locales() {
        if (alreadyInstalled()) {
            return Language::all()->pluck('name', 'locale')->all();
        }

        return config('app.locales');
    }
}

if (! function_exists('title_case')) {
    function title_case(string $string) {
        return Str::title($string);
    }
}

if (! function_exists('genre_comma')) {
    function genre_comma(array $genres) {
        $genres_list = [];

        foreach ($genres as $data) {
            $genres_list[] = '<a href="'.mopie_route('genre', ['id' => $data->id, 'slug' => str_slug($data->name)]).'" title="'.$data->name.'">'.$data->name.'</a>';
        }

        return implode(', ',$genres_list);
    }
}

if (! function_exists('star_comma')) {
    function star_comma(array $star, int $count = 5) {
        $stars = [];

        foreach (collect($star)->take($count) as $data) {
            $stars[] = '<a href="'.mopie_route('people.single', ['id' => $data->id]).'" title="'.$data->name.'">'.$data->name.'</a>';
        }

        return implode(', ',$stars);
    }
}

if (! function_exists('director_comma')) {
    function director_comma(array $director, int $count = 5) {
        $directors = [];

        foreach (collect($director)->take($count) as $data) {
            $directors[] = '<a href="'.mopie_route('people.single', ['id' => $data->id]).'" title="'.$data->name.'">'.$data->name.'</a>';
        }

        return implode(', ',$directors);
    }
}

if (! function_exists('localeFromRequest')) {
    function localeFromRequest($segment = 0) {
        $url = request()->getUri();
        return getLocaleFromUrl($url, $segment);
    }
}

if (! function_exists('getLocaleFromUrl')) {
    function getLocaleFromUrl($url, $segment = 0) {
        return parseUrl($url, $segment)['locale'];
    }
}

if (! function_exists('parseUrl')) {
    function parseUrl($url, $segment = 0) {
        $parsedUrl             = parse_url($url);
        $parsedUrl['segments'] = array_values(array_filter(explode('/', $parsedUrl['path']), 'strlen'));
        $localeCandidate       = Arr::get($parsedUrl['segments'], $segment, false);
        $parsedUrl['locale']   = in_array($localeCandidate, array_keys(get_locales())) ? $localeCandidate : null;
        $parsedUrl['query']    = Arr::get($parsedUrl, 'query', false);
        $parsedUrl['fragment'] = Arr::get($parsedUrl, 'fragment', false);
        unset($parsedUrl['path']);

        return $parsedUrl;
    }
}

if (! function_exists('localize')) {
    function localize($url, $locale, $segment = 0) {
        $cleanUrl  = cleanUrl($url, $segment);
        $parsedUrl = parseUrl($cleanUrl, $segment);
        // Check if there are enough segments, if not return url unchanged:
        if (count($parsedUrl['segments']) >= $segment) {
            array_splice($parsedUrl['segments'], $segment, 0, $locale);
        }
        return pathFromParsedUrl($parsedUrl);
    }
}

if (! function_exists('cleanUrl')) {
    function cleanUrl($url, $segment = 0) {
        $parsedUrl = parseUrl($url, $segment);
        // Remove locale from segments:
        if ($parsedUrl['locale']) {
            unset($parsedUrl['segments'][$segment]);
            $parsedUrl['locale'] = false;
        }
        return pathFromParsedUrl($parsedUrl);
    }
}

if (! function_exists('pathFromParsedUrl')) {
    function pathFromParsedUrl($parsedUrl) {
        $path = '/' . implode('/', $parsedUrl['segments']);
        if ($parsedUrl['query']) {
            $path .= "?{$parsedUrl['query']}";
        }
        if ($parsedUrl['fragment']) {
            $path .= "#{$parsedUrl['fragment']}";
        }
        return $path;
    }
}

if (! function_exists('get_country_code')) {
    function get_country_code() {
        $ip = request()->ip();

        if ( $ip !== '127.0.0.1' ) {
            $reader = new Reader(app_path('geo-country.mmdb'));
            $record = $reader->country($ip);

            return strtolower($record->country->isoCode);
        }

        return '';
    }
}

if (! function_exists('auto_redirect')) {
    function auto_redirect() {
        if (alreadyInstalled()) {
            return Option::getSetting('auto_redirect');
        }

        return config('mopie.auto_redirect');
    }
}

if (! function_exists('max_limit_page_sitemap')) {
    function max_limit_page_sitemap() {
        if (alreadyInstalled()) {
            return Option::getSetting('max_limit_page_sitemap');
        }

        return config('mopie.max_limit_page_sitemap');
    }
}

if (! function_exists('already_installed')) {
    function alreadyInstalled() {
        return Storage::disk('installed')->exists('.installed');
    }
}

if (! function_exists('get_browser_lang')) {
    function get_browser_lang() {
        $ip = request()->ip();

        if ($ip !== '127.0.0.1') {
            return substr(request()->server('HTTP_ACCEPT_LANGUAGE'), 0, 2);
        }
    }
}
