<?php

namespace MovieEngine\Monetization;

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

class AdManager {

    protected $settings;
    protected static $rendered_slots = [];

    public function __construct() {
        $this->settings = get_option('movie_engine_monetization_settings', []);

        if (empty($this->settings['movie_engine_enable_ads']) && empty($this->settings['enable_ads'])) {
            return;
        }

        $payment_settings = get_option('movie_engine_payments_settings', []);
        $hide_for_premium = !empty($payment_settings['movie_engine_hide_for_premium']) || !empty($payment_settings['hide_for_premium']);

        if ($hide_for_premium && \MovieEngine\Payments\Membership::is_premium()) {
            return;
        }
        add_action('wp_head', [$this, 'inject_global_script'], 20);
        add_action('wp_body_open', [$this, 'render_header_ad']);
        add_action('movie_engine_before_single_movie_wrapper', [$this, 'render_header_ad']);
        add_action('movie_engine_before_single_series_wrapper', [$this, 'render_header_ad']);
        add_action('movie_engine_before_single_episode_wrapper', [$this, 'render_header_ad']);
        add_action('wp_footer', [$this, 'render_footer_ad']);
        add_action('movie_engine_after_single_movie_wrapper', [$this, 'render_footer_ad']);
        add_action('movie_engine_after_single_series_wrapper', [$this, 'render_footer_ad']);
        add_action('movie_engine_after_single_episode_wrapper', [$this, 'render_footer_ad']);
        add_shortcode('movie_engine_ad_sidebar', [$this, 'render_sidebar_ad']);
        add_action('movie_engine_ad_header', [$this, 'render_header_ad']);
        add_action('movie_engine_ad_footer', [$this, 'render_footer_ad']);
    }



    public static function should_show_ads($post_id = null) {
        $settings = get_option('movie_engine_monetization_settings', []);

        if (empty($settings['movie_engine_enable_ads']) && empty($settings['enable_ads'])) {
            return false;
        }

        $payment_settings = get_option('movie_engine_payments_settings', []);
        $hide_for_premium = !empty($payment_settings['movie_engine_hide_for_premium']) || !empty($payment_settings['hide_for_premium']);

        if ($hide_for_premium) {
            $user_id = get_current_user_id();

            $show_for_admin = !empty($settings['movie_engine_show_ads_for_admin']) || !empty($settings['show_ads_for_admin']);
            if (current_user_can('manage_options') && $show_for_admin) {
                return true;
            }

            if (\MovieEngine\Payments\Membership::is_premium(null, true)) {
                return false;
            }

            if (!$post_id) {
                $post_id = get_the_ID();
            }

            if ($post_id && $user_id && is_singular(['movie_engine_movie', 'movie_engine_series', 'movie_engine_episode'])) {
                if (\MovieEngine\Payments\PPV::has_purchased($user_id, $post_id) || \MovieEngine\Payments\PPV::has_active_rental($user_id, $post_id)) {
                    return false;
                }
            }
        }

        return true;
    }

    public function inject_global_script() {
        if (!self::should_show_ads()) return;

        $script = $this->settings['movie_engine_global_ad_script'] ?? ($this->settings['global_ad_script'] ?? '');
        if (!empty($script)) {
            echo "<!-- MovieEngine Global Ad Script -->\n";
            echo $script . "\n"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            echo "<!-- End MovieEngine Global Ad Script -->\n";
        }
    }

    public function render_sidebar_ad() {
        if (!self::should_show_ads()) return '';

        ob_start();
        self::render_slot('sidebar');
        return ob_get_clean();
    }

    public function inject_content_ads($content) {
        if (!self::should_show_ads()) return $content;

        if (!is_singular(['movie_engine_movie', 'movie_engine_series', 'movie_engine_episode'])) {
            return $content;
        }

        $before_ad = $this->get_slot_html('before_content');
        $after_ad  = $this->get_slot_html('after_content');

        return $before_ad . $content . $after_ad;
    }


    public static function render_slot($slot_id) {
        if (isset(static::$rendered_slots[$slot_id])) {
            return;
        }

        if (!self::should_show_ads()) {
            return;
        }

        $instance = new static();
        $html = $instance->get_slot_html($slot_id);

        if (!empty($html)) {
            echo $html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            static::$rendered_slots[$slot_id] = true;
        }
    }

    public function render_header_ad() {
        self::render_slot('header');
    }

    public function render_footer_ad() {
        self::render_slot('footer');
    }

    public function render_sidebar_ad_manual() {
        return $this->get_slot_html('sidebar');
    }


    protected function get_slot_html($slot_id) {
        $p = 'movie_engine_';
        $s = $this->settings;

        $enable = !empty($s[$p . $slot_id . '_enable']) || !empty($s[$slot_id . '_enable']);
        if (!$enable) return '';

        $is_mobile = wp_is_mobile();

        $show_desktop = !isset($s[$p . $slot_id . '_desktop']) && !isset($s[$slot_id . '_desktop'])
            ? true
            : (!empty($s[$p . $slot_id . '_desktop']) || !empty($s[$slot_id . '_desktop']));

        $show_mobile = !isset($s[$p . $slot_id . '_mobile']) && !isset($s[$slot_id . '_mobile'])
            ? true
            : (!empty($s[$p . $slot_id . '_mobile']) || !empty($s[$slot_id . '_mobile']));

        if ($is_mobile && !$show_mobile) return '';
        if (!$is_mobile && !$show_desktop) return '';

        $code = '';
        if ($is_mobile) {
            $code = $s[$p . $slot_id . '_code_mobile'] ?? ($s[$slot_id . '_code_mobile'] ?? '');
        }

        if (empty($code)) {
            $code = $s[$p . $slot_id . '_code'] ?? ($s[$slot_id . '_code'] ?? '');
        }

        if (empty($code)) return '';

        $html = "\n<!-- MovieEngine Ad: " . esc_html($slot_id) . " -->\n";
        $html .= '<div class="movie-engine-ad-slot me-ad-' . esc_attr($slot_id) . '">';
        $html .= $code;
        $html .= '</div>' . "\n";

        return $html;
    }
}
