<?php

namespace MovieEngine\Frontend;

if (! defined("ABSPATH")) {
    exit; // Exit if accessed directly
}

class Player {

    public function __construct() {
        add_shortcode('movie_engine_player', [$this, 'render_shortcode']);
    }

    public function render_shortcode($atts) {
        $atts = shortcode_atts([
            'id' => get_the_ID(),
        ], $atts);

        return self::render($atts['id']);
    }

    public static function render($post_id) {
        if (! $post_id) {
            $post_id = get_queried_object_id() ?: get_the_ID();
        }

        if ($post_id) {
            $views = (int) get_post_meta($post_id, '_movie_engine_views', true);
            update_post_meta($post_id, '_movie_engine_views', $views + 1);
        }

        if (!$post_id) {
            return '<div class="movie-engine-player-error me-player-error">' . esc_html__('Invalid post ID', 'cine-movie-engine') . '</div>';
        }

        if (\MovieEngine\Payments\Membership::is_restricted($post_id)) {
            $monetization_settings = get_option('movie_engine_monetization_settings', []);

            $is_premium = get_post_meta($post_id, '_movie_engine_is_premium', true);
            $is_premium = ($is_premium === '1' || $is_premium === 'yes' || $is_premium === 'true' || $is_premium === true || $is_premium === 1);

            if (get_post_type($post_id) === 'movie_engine_episode' && !$is_premium) {
                $series_id = (int) get_post_meta($post_id, '_movie_engine_series_id', true);
                if ($series_id) {
                    $series_is_premium = get_post_meta($series_id, '_movie_engine_is_premium', true);
                    $is_premium = ($series_is_premium === '1' || $series_is_premium === 'yes' || $series_is_premium === 'true' || $series_is_premium === true || $series_is_premium === 1);
                }
            }

            if (!$is_premium && !is_user_logged_in()) {
                $paywall_settings = [
                    'paywall_title' => esc_html__('Login Required', 'cine-movie-engine'),
                    'paywall_message' => esc_html__('Please login or register for a free account to watch this content.', 'cine-movie-engine'),
                    'cta_button_text' => esc_html__('Login Now', 'cine-movie-engine'),
                    'cta_button_url' => \MovieEngine\Payments\Membership::get_login_url(get_permalink($post_id)),
                ];
            } else {
                $paywall_settings = [
                    'paywall_title' => $monetization_settings['movie_engine_paywall_title'] ?? ($monetization_settings['paywall_title'] ?? 'Premium Content'),
                    'paywall_message' => $monetization_settings['movie_engine_paywall_message'] ?? ($monetization_settings['paywall_message'] ?? 'Subscribe to watch this content and thousands more!'),
                    'cta_button_text' => $monetization_settings['movie_engine_cta_button_text'] ?? ($monetization_settings['cta_button_text'] ?? 'Subscribe Now'),
                    'cta_button_url' => $monetization_settings['movie_engine_cta_button_url'] ?? ($monetization_settings['cta_button_url'] ?? ''),
                ];
            }

            $partial_duration = apply_filters('movie_engine_partial_paywall_duration', false, $post_id);


            if (!$partial_duration) {
                return self::render_paywall_message($paywall_settings, $post_id);
            }
        }

        $sources = get_post_meta($post_id, '_movie_engine_sources', true);
        $trailer = get_post_meta($post_id, '_movie_engine_trailer', true);

        $has_valid_source = false;
        if (!empty($sources) && is_array($sources)) {
            foreach ($sources as $source) {
                if (!empty($source['url'])) {
                    $has_valid_source = true;
                    break;
                }
            }
        }

        if (!$has_valid_source) {
            if ($trailer) {
                return self::render_trailer($trailer, $post_id);
            }
            return '<div class="movie-engine-player-notice">' . esc_html__('No video sources available.', 'cine-movie-engine') . '</div>';
        }

        ob_start();
        $movie_engine_post_id = $post_id;
        \MovieEngine\Utils\TemplateLoader::get_template_part('single-movie/player', '', ['movie_engine_post_id' => $post_id]);
        return ob_get_clean();
    }

    private static function render_paywall_message($settings, $post_id = 0) {
        $ppv = ['sale_price' => 0, 'rent_price' => 0, 'rent_duration' => 48, 'currency' => \MovieEngine\Payments\Membership::get_currency_symbol()];
        if (class_exists('\MovieEnginePro\Payments\Membership')) {
            $ppv = \MovieEnginePro\Payments\Membership::get_ppv_data($post_id);
        }

        ob_start();
        \MovieEngine\Utils\TemplateLoader::get_template_part('global/paywall', '', [
            'post_id' => $post_id,
            'title'   => $settings['paywall_title'] ?? esc_html__('Premium Content', 'cine-movie-engine'),
            'message' => $settings['paywall_message'] ?? esc_html__('Please subscribe to watch this content.', 'cine-movie-engine'),
            'btn_text' => $settings['cta_button_text'] ?? esc_html__('Subscribe Now', 'cine-movie-engine'),
            'btn_url' => !empty($settings['cta_button_url']) ? $settings['cta_button_url'] : \MovieEngine\Payments\Membership::get_pricing_url(),
            'ppv'     => $ppv,
        ]);
        return ob_get_clean();
    }

    private static function render_trailer($trailer_url, $post_id = 0) {
        if (! $trailer_url) {
            return '';
        }

        ob_start();
        \MovieEngine\Utils\TemplateLoader::get_template_part('global/trailer-player', '', [
            'trailer_url' => $trailer_url,
            'post_id'     => $post_id
        ]);
        return ob_get_clean();
    }



    public static function get_player_data($post_id) {
        $sources = get_post_meta($post_id, '_movie_engine_sources', true);

        if (empty($sources) || ! is_array($sources)) {
            $sources = [];
        }

        if (empty($sources)) {
            return [];
        }

        $settings = get_option('movie_engine_player_settings', []);

        if (isset($settings['multi_sources']) && $settings['multi_sources'] == '0') {
            $sources = array_slice($sources, 0, 1);
        }

        if (!empty($settings['randomize_sources']) && count($sources) > 1) {
            shuffle($sources);
        }

        $use_proxy = ! empty($settings['movie_engine_hide_video_url']) || ! empty($settings['hide_video_url']);
        $get_quality_label = function ($q) {
            $q = (string) $q;
            $clean_q = preg_replace('/[^0-9]/', '', $q);
            if (empty($clean_q)) return $q;
            return $clean_q . 'p';
        };

        $quality_display_labels = [
            '2160' => '2160p (4K)',
            '1440' => '1440p (2K)',
            '1080' => '1080p (HD)',
            '720'  => '720p',
            '480'  => '480p',
            '360'  => '360p',
            '240'  => '240p',
            '144'  => '144p',
            'HD'   => 'HD (label)',
        ];

        $get_quality_display_label = function ($q) use ($quality_display_labels, $get_quality_label) {
            $q = trim((string) ($q ?? ''));
            if ($q === '') return 'HD';
            if (isset($quality_display_labels[$q])) return $quality_display_labels[$q];
            $clean = preg_replace('/[^0-9]/', '', $q);
            if ($clean !== '' && isset($quality_display_labels[$clean])) return $quality_display_labels[$clean];
            return $get_quality_label($q);
        };

        $parse_quality_size = function ($q) {
            if (empty($q)) return 720;
            $q = preg_replace('/\s+/', '', strtolower((string) $q));
            if (preg_match('/^(\d+)/', $q, $m)) return (int) $m[1];
            if (in_array($q, ['hd', 'high'], true)) return 720;
            return 720;
        };

        $is_stream_source = function ($url, $type) {
            $type = (string) ($type ?? '');
            $url = (string) ($url ?? '');
            return ($type === 'hls' || $type === 'dash') || (strpos($url, '.m3u8') !== false || strpos($url, '.mpd') !== false);
        };

        $mp4_groups = [];
        foreach ($sources as $index => $source) {
            if (empty($source['url'])) continue;
            $url = trim($source['url']);
            if (empty($url) || strpos($url, '#') === 0 || !filter_var($url, FILTER_VALIDATE_URL)) continue;

            $type = ! empty($source['type']) ? $source['type'] : 'iframe';
            $is_iframe = ($type === 'iframe' || $type === 'embed' || $type === 'youtube' || strpos($url, 'youtube.com') !== false || strpos($url, 'youtu.be') !== false);
            $is_stream = $is_stream_source($url, $type);

            if (! $is_iframe && ! $is_stream) {
                $name = ! empty($source['name']) ? $source['name'] : 'Server 1';
                $size = $parse_quality_size($source['quality'] ?? 'HD');
                if ($use_proxy) {
                    $nonce = wp_create_nonce('wp_rest');
                    $url = rest_url('movie-engine/v1/stream/' . $post_id) . '?index=' . $index . '&_wpnonce=' . $nonce;
                }
                if (is_ssl() && strpos($url, 'http:') === 0) $url = str_replace('http://', 'https://', $url);
                if (! isset($mp4_groups[$name])) {
                    $mp4_groups[$name] = ['name' => $name, 'lang' => $source['lang'] ?? 'en', 'variants' => [], 'type' => $type];
                }
                $mp4_groups[$name]['variants'][] = [
                    'url'   => $url,
                    'size'  => $size,
                    'label' => $get_quality_display_label($source['quality'] ?? 'HD')
                ];
            }
        }

        $global_pools = [];
        foreach ($mp4_groups as $group) {
            $lang = $group['lang'] ?? 'en';
            if (! isset($global_pools[$lang])) {
                $global_pools[$lang] = [];
            }
            foreach ($group['variants'] as $v) {
                $global_pools[$lang][] = $v;
            }
        }
        foreach ($global_pools as &$pool) {
            usort($pool, function ($a, $b) {
                return $b['size'] - $a['size'];
            });
        }

        $all_qualities_global = [];
        foreach ($mp4_groups as $group) {
            foreach ($group['variants'] as $v) {
                $all_qualities_global[] = $v;
            }
        }
        usort($all_qualities_global, function ($a, $b) {
            return $b['size'] - $a['size'];
        });

        $language_labels = self::get_language_labels();

        $player_sources = [];
        $mp4_added = [];
        foreach ($sources as $index => $source) {
            if (empty($source['url'])) continue;
            $url = trim($source['url']);
            if (empty($url) || strpos($url, '#') === 0 || !filter_var($url, FILTER_VALIDATE_URL)) continue;

            $type = ! empty($source['type']) ? $source['type'] : 'iframe';
            $is_iframe = ($type === 'iframe' || $type === 'embed' || $type === 'youtube' || strpos($url, 'youtube.com') !== false || strpos($url, 'youtu.be') !== false);

            if (! $is_iframe) {
                $name = ! empty($source['name']) ? $source['name'] : 'Server 1';
                $is_stream = $is_stream_source($url, $type);

                if ($is_stream) {
                    if ($use_proxy && in_array($type, ['video_file', 'hls', 'direct'], true)) {
                        $nonce = wp_create_nonce('wp_rest');
                        $url = rest_url('movie-engine/v1/stream/' . $post_id) . '?index=' . $index . '&_wpnonce=' . $nonce;
                    }
                    if (is_ssl() && strpos($url, 'http:') === 0) $url = str_replace('http://', 'https://', $url);
                    $player_sources[] = [
                        'name'         => $name,
                        'url'          => $url,
                        'lang'         => $source['lang'] ?? 'en',
                        'quality'      => $source['quality'] ?? 'HD',
                        'type'         => $type,
                        'source_index' => $index,
                    ];
                } elseif (isset($mp4_added[$name])) {
                    continue;
                } else {
                    $mp4_added[$name] = true;
                    $group = $mp4_groups[$name];
                    $lang = $group['lang'] ?? 'en';
                    $variants = $group['variants'];
                    usort($variants, function ($a, $b) {
                        return $b['size'] - $a['size'];
                    });
                    $first = $variants[0];

                    $all_qualities = (count($all_qualities_global) > 1)
                        ? $all_qualities_global
                        : (isset($global_pools[$lang]) && ! empty($global_pools[$lang]) ? $global_pools[$lang] : (count($variants) > 0 ? $variants : null));
                    $player_sources[] = [
                        'name'             => $name,
                        'url'              => $first['url'],
                        'lang'             => $lang,
                        'quality'          => $first['label'],
                        'type'             => $group['type'],
                        'quality_variants' => $all_qualities,
                        'source_index'     => $index,
                    ];
                }
            } else {
                if ($use_proxy && in_array($type, ['video_file', 'hls', 'direct'], true)) {
                    $nonce = wp_create_nonce('wp_rest');
                    $url = rest_url('movie-engine/v1/stream/' . $post_id) . '?index=' . $index . '&_wpnonce=' . $nonce;
                }
                if (is_ssl() && strpos($url, 'http:') === 0) $url = str_replace('http://', 'https://', $url);
                $player_sources[] = [
                    'name'         => ! empty($source['name']) ? $source['name'] : 'Server ' . (count($player_sources) + 1),
                    'url'          => $url,
                    'lang'         => ! empty($source['lang']) ? $source['lang'] : 'en',
                    'quality'      => ! empty($source['quality']) ? $source['quality'] : 'HD',
                    'type'         => $type,
                    'source_index' => $index,
                ];
            }
        }

        $langs_seen = [];
        $language_variants = [];
        foreach ($sources as $index => $source) {
            if (empty($source['url'])) continue;
            $raw_url = trim($source['url']);
            if (empty($raw_url) || strpos($raw_url, '#') === 0 || ! filter_var($raw_url, FILTER_VALIDATE_URL)) continue;

            $type = ! empty($source['type']) ? $source['type'] : 'iframe';
            $is_iframe = ($type === 'iframe' || $type === 'embed' || $type === 'youtube' || strpos($raw_url, 'youtube.com') !== false || strpos($raw_url, 'youtu.be') !== false);
            if ($is_iframe || $is_stream_source($raw_url, $type)) continue;

            $code = $source['lang'] ?? 'en';
            if (! isset($langs_seen[$code])) {
                $langs_seen[$code] = true;
                $url = $raw_url;
                if ($use_proxy) {
                    $nonce = wp_create_nonce('wp_rest');
                    $url = rest_url('movie-engine/v1/stream/' . $post_id) . '?index=' . $index . '&_wpnonce=' . $nonce;
                }
                if (is_ssl() && strpos($url, 'http:') === 0) {
                    $url = str_replace('http://', 'https://', $url);
                }
                if (is_ssl() && strpos($raw_url, 'http:') === 0) {
                    $raw_url = str_replace('http://', 'https://', $raw_url);
                }
                $language_variants[] = [
                    'code'        => $code,
                    'label'       => $language_labels[$code] ?? ucfirst($code),
                    'url'         => $url,
                    'direct_url'  => $raw_url,
                    'source_index' => $index,
                ];
            }
        }
        if (count($language_variants) > 1) {
            foreach ($player_sources as $idx => $s) {
                if (! empty($s['url']) && ! in_array($s['type'] ?? '', ['iframe', 'embed', 'youtube', 'iframe_embed'], true)) {
                    $player_sources[$idx]['language_variants'] = $language_variants;
                }
            }
        }

        return $player_sources;
    }

    /**
     * Language labels for player (matches metabox dropdown).
     */
    public static function get_language_labels() {
        return [
            'en'    => esc_html__('English', 'cine-movie-engine'),
            'es'    => esc_html__('Spanish', 'cine-movie-engine'),
            'fr'    => esc_html__('French', 'cine-movie-engine'),
            'de'    => esc_html__('German', 'cine-movie-engine'),
            'it'    => esc_html__('Italian', 'cine-movie-engine'),
            'pt'    => esc_html__('Portuguese', 'cine-movie-engine'),
            'ru'    => esc_html__('Russian', 'cine-movie-engine'),
            'tr'    => esc_html__('Turkish', 'cine-movie-engine'),
            'zh'    => esc_html__('Chinese', 'cine-movie-engine'),
            'jp'    => esc_html__('Japanese', 'cine-movie-engine'),
            'hi'    => esc_html__('Hindi', 'cine-movie-engine'),
            'multi' => esc_html__('Multi-Audio', 'cine-movie-engine'),
        ];
    }


    public static function get_subtitle_data($post_id) {
        $subtitles = get_post_meta($post_id, '_movie_engine_subtitles', true);

        if (empty($subtitles) || ! is_array($subtitles)) {
            return [];
        }

        $site_host = wp_parse_url(site_url(), PHP_URL_HOST);
        $subtitle_tracks = [];
        foreach ($subtitles as $index => $subtitle) {
            if (empty($subtitle['src'])) {
                continue;
            }
            $src = $subtitle['src'];
            $url_host = wp_parse_url($src, PHP_URL_HOST);
            if ($url_host && $url_host !== $site_host) {
                $src = add_query_arg(
                    '_wpnonce',
                    wp_create_nonce('wp_rest'),
                    rest_url('movie-engine/v1/subtitle/' . (int) $post_id . '/' . (int) $index)
                );
            }
            $subtitle_tracks[] = [
                'label'    => ! empty($subtitle['label']) ? $subtitle['label'] : esc_html__('Unknown', 'cine-movie-engine'),
                'srclang'  => ! empty($subtitle['srclang']) ? $subtitle['srclang'] : esc_html__('en', 'cine-movie-engine'),
                'src'      => $src,
                'default'  => ! empty($subtitle['default']),
            ];
        }

        return $subtitle_tracks;
    }
}
