<?php

namespace MovieEngine\Monetization;

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

class Affiliate {

    public function __construct() {
        add_action('movie_engine_before_player', [$this, 'render_affiliate_buttons_before']);
        add_action('movie_engine_after_player', [$this, 'render_affiliate_buttons_after']);
    }

    public function render_affiliate_buttons_before() {
        $this->render_buttons('before_player');
    }

    public function render_affiliate_buttons_after() {
        $this->render_buttons('after_player');
    }

    private function render_buttons($position) {
        $settings = get_option('movie_engine_monetization_settings', []);

        if (empty($settings['movie_engine_enable_affiliates']) && empty($settings['enable_affiliates'])) {
            return;
        }

        $target_position = $settings['movie_engine_button_position'] ?? ($settings['button_position'] ?? 'after_player');

        if ($target_position !== $position) {
            return;
        }

        $post_id = get_the_ID();
        $links = get_post_meta($post_id, '_movie_engine_affiliate_links', true);

        if (get_post_type($post_id) === 'movie_engine_episode' && (empty($links) || !is_array($links))) {
            $series_id = get_post_meta($post_id, '_movie_engine_series_id', true);
            if ($series_id) {
                $links = get_post_meta($series_id, '_movie_engine_affiliate_links', true);
                $title = urlencode(get_the_title($series_id));
                $year = get_post_meta($series_id, '_movie_engine_year', true);
            }
        }

        if (!is_array($links)) {
            $links = [];
        }

        if (!isset($title)) {
            $title = urlencode(get_the_title($post_id));
        }
        if (!isset($year)) {
            $year = get_post_meta($post_id, '_movie_engine_year', true);
        }

        echo '<div class="movie-engine-affiliate-buttons">';


        if (!empty($settings['movie_engine_enable_amazon']) || !empty($settings['enable_amazon'])) {
            $url = $links['amazon'] ?? '';
            $tag = $settings['movie_engine_amazon_tag'] ?? ($settings['amazon_tag'] ?? '');


            if ($url) {
                if (!filter_var($url, FILTER_VALIDATE_URL)) {
                    $url = "https://www.amazon.com/dp/{$url}?tag={$tag}";
                } elseif ($tag) {
                    $url = add_query_arg('tag', $tag, $url);
                }
                $button_text = $settings['movie_engine_amazon_button_text'] ?? ($settings['amazon_button_text'] ?? esc_html__('Buy on Amazon', 'cine-movie-engine'));
                $this->render_button($url, $button_text, 'amazon', 'fa-brands fa-amazon');
            } elseif ($tag) {
                $url = "https://www.amazon.com/s?k={$title}&tag={$tag}";
                $button_text = $settings['movie_engine_amazon_button_text'] ?? ($settings['amazon_button_text'] ?? esc_html__('Buy on Amazon', 'cine-movie-engine'));
                $this->render_button($url, $button_text, 'amazon', 'fa-brands fa-amazon');
            }
        }

        // Settings enable key => [ label, meta key in post (saved by metabox) ]
        $services = [
            'netflix'      => [esc_html__('Netflix', 'cine-movie-engine'),    'netflix'],
            'amazon_prime' => [esc_html__('Prime Video', 'cine-movie-engine'), 'prime'],
            'disney_plus'  => [esc_html__('Disney+', 'cine-movie-engine'),     'disney'],
            'hulu'         => [esc_html__('Hulu', 'cine-movie-engine'),        'hulu'],
            'hbo_max'      => [esc_html__('HBO Max', 'cine-movie-engine'),     'hbo'],
            'apple_tv'     => [esc_html__('Apple TV+', 'cine-movie-engine'),   'apple'],
        ];

        foreach ($services as $settings_key => [$label, $meta_key]) {
            if (!empty($settings['movie_engine_enable_' . $settings_key]) || !empty($settings['enable_' . $settings_key])) {
                $url = $links[$meta_key] ?? '';

                if (empty($url)) {
                    $template = $settings['movie_engine_' . $settings_key . '_url'] ?? ($settings[$settings_key . '_url'] ?? '');
                    if (!empty($template)) {
                        $url = str_replace(['{title}', '{year}'], [$title, $year], $template);
                    }
                }

                if ($url) {
                    $text = sprintf(
                        /* translators: 1: streaming service name (e.g. Netflix) */
                        __('Watch on %s', 'cine-movie-engine'),
                        $label
                    );

                    $css_class = str_replace(['amazon_', '_plus', '_max', '_tv'], '', $settings_key);
                    $this->render_button($url, $text, $css_class, 'fa-solid fa-play');
                }
            }
        }


        if (!empty($settings['movie_engine_enable_tickets']) || !empty($settings['enable_tickets'])) {
            $url = $links['tickets'] ?? '';

            if (empty($url)) {
                $template = $settings['movie_engine_ticket_url_template'] ?? ($settings['ticket_url_template'] ?? '');
                if (!empty($template)) {
                    $url = str_replace(['{title}', '{year}'], [$title, $year], $template);
                }
            }

            if ($url) {
                $text = $settings['movie_engine_ticket_button_text'] ?? ($settings['ticket_button_text'] ?? esc_html__('Buy Tickets', 'cine-movie-engine'));
                $this->render_button($url, $text, 'tickets', 'fa-solid fa-ticket');
            }
        }
        echo '</div>';
    }

    private function render_button($url, $text, $class, $icon) {
?>
        <a href="<?php echo esc_url($url); ?>" class="movie-engine-affiliate-btn <?php echo esc_attr($class); ?>" target="_blank" rel="nofollow noopener">
            <span class=" <?php echo esc_attr($icon); ?>"></span>
            <?php echo esc_html($text); ?>
        </a>
<?php
    }
}
