<?php
/**
 * Popout window handler for VMPlayer.
 *
 * Registers a WordPress query variable and hooks into template_redirect
 * to detect popout requests. When a popout URL is hit, this class
 * renders the popout template as a fully standalone HTML page (no
 * theme header/footer wrapping) so the popout window is clean and
 * self-contained.
 *
 * The URL pattern is home_url('/?vmplayer_popout=1&station=N'). Query
 * vars work with any permalink structure and require no rewrite rule
 * flushes. Simple and portable.
 *
 * @package VMPlayer
 */

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

/**
 * Class VMPlayer_Popout
 */
class VMPlayer_Popout {

    /**
     * Query variable that triggers popout rendering.
     */
    const QUERY_VAR = 'vmplayer_popout';

    /**
     * Plugin slug.
     *
     * @var string
     */
    private $plugin_slug;

    /**
     * Plugin version.
     *
     * @var string
     */
    private $version;

    /**
     * Constructor.
     *
     * @param string $plugin_slug Plugin slug.
     * @param string $version     Plugin version.
     */
    public function __construct( $plugin_slug, $version ) {
        $this->plugin_slug = $plugin_slug;
        $this->version     = $version;
    }

    /* ------------------------------------------------------------------
     * Query var registration
     * --------------------------------------------------------------- */

    /**
     * Add our query var to the WordPress-recognized list.
     * Without this, get_query_var() returns nothing even when the
     * URL contains the parameter.
     *
     * @param array $vars Existing query vars.
     * @return array
     */
    public function register_query_var( $vars ) {
        $vars[] = self::QUERY_VAR;
        return $vars;
    }

    /* ------------------------------------------------------------------
     * Request handling
     * --------------------------------------------------------------- */

    /**
     * Intercept template_redirect. If the current request is a popout
     * request, render the popout page and exit. Otherwise, do nothing
     * so normal WordPress rendering continues.
     *
     * @return void
     */
    public function maybe_render_popout() {
        if ( ! get_query_var( self::QUERY_VAR ) ) {
            return;
        }

        $this->render_popout_page();
        exit;
    }

    /**
     * Render the popout page as a complete standalone HTML document.
     * We output our own doctype and head so the popout is not wrapped
     * in the site's theme header/footer.
     *
     * @return void
     */
    private function render_popout_page() {
        // Resolve the station index from the query string.
        $station_index = isset( $_GET['station'] )
            ? absint( wp_unslash( $_GET['station'] ) )
            : 0;

        $stations = VMPlayer_Settings::get_stations();
        if ( empty( $stations ) ) {
            $this->render_empty_popout();
            return;
        }

        if ( ! isset( $stations[ $station_index ] ) ) {
            $station_index = 0;
        }

        $active_station = $stations[ $station_index ];
        $active_index   = $station_index;
        $settings       = VMPlayer_Settings::get_settings();

        // Fill in the packaged default logo when the admin did not
        // upload one, so the popout header, brand area, and artwork
        // slot always show a real image.
        if ( empty( $active_station['logo_url'] ) ) {
            $active_station['logo_url'] = VMPlayer_Public::get_default_logo_url();
        }
        foreach ( $stations as $key => $station_row ) {
            if ( is_array( $station_row ) && empty( $station_row['logo_url'] ) ) {
                $stations[ $key ]['logo_url'] = VMPlayer_Public::get_default_logo_url();
            }
        }

        // Expand social handles into full profile URLs for the template.
        // See VMPlayer_Shortcode::render_shortcode for the reasoning.
        if ( ! empty( $active_station['social'] ) && is_array( $active_station['social'] ) ) {
            $expanded = array();
            foreach ( $active_station['social'] as $platform => $handle ) {
                $url = VMPlayer_Settings::build_social_url( $platform, $handle );
                if ( '' !== $url ) {
                    $expanded[ $platform ] = $url;
                }
            }
            $active_station['social'] = $expanded;
        }

        // Send appropriate headers and let asset URLs work correctly.
        nocache_headers();

        // Prevent the site's theme from injecting anything.
        remove_all_actions( 'wp_head' );
        remove_all_actions( 'wp_footer' );

        // Output the standalone HTML document.
        $this->output_header( $active_station );
        include VMPLAYER_PLUGIN_DIR . 'templates/popout.php';
        $this->output_footer( $active_station, $active_index, $settings, $stations );
    }

    /**
     * Output the popout HTML head and opening body tag.
     *
     * @param array $station Active station data.
     * @return void
     */
    private function output_header( $station ) {
        $title = sprintf(
            /* translators: %s: station name */
            esc_html__( '%s - Pop Out Player', 'vmplayer' ),
            esc_html( $station['name'] )
        );

        $primary_color   = VMPlayer_Settings::sanitize_hex_color(
            VMPlayer_Settings::get_setting( 'theme_color_primary', '#a855f7' ),
            '#a855f7'
        );
        $secondary_color = VMPlayer_Settings::sanitize_hex_color(
            VMPlayer_Settings::get_setting( 'theme_color_secondary', '#3b82f6' ),
            '#3b82f6'
        );
        ?><!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo( 'charset' ); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="robots" content="noindex,nofollow">
    <title><?php echo esc_html( $title ); ?></title>
    <link rel="stylesheet" href="<?php echo esc_url( VMPLAYER_PLUGIN_URL . 'assets/css/vmplayer-popout.css?ver=' . $this->asset_version( 'assets/css/vmplayer-popout.css' ) ); ?>">
    <link rel="stylesheet" href="<?php echo esc_url( VMPLAYER_PLUGIN_URL . 'assets/css/vmplayer-frontend.css?ver=' . $this->asset_version( 'assets/css/vmplayer-frontend.css' ) ); ?>">
    <style>
        .vmplayer-popout,
        .vmplayer {
            --vmp-primary: <?php echo esc_html( $primary_color ); ?>;
            --vmp-secondary: <?php echo esc_html( $secondary_color ); ?>;
        }
    </style>
</head>
<body class="vmplayer-popout-body">
        <?php
    }

    /**
     * Output the popout HTML footer with scripts and config.
     *
     * @param array $station       Active station.
     * @param int   $station_index Active index.
     * @param array $settings      Global settings.
     * @param array $stations      All stations.
     * @return void
     */
    private function output_footer( $station, $station_index, $settings, $stations ) {
        $config = array(
            'ajaxUrl'             => admin_url( 'admin-ajax.php' ),
            'nonce'               => VMPlayer_API::create_nonce(),
            'stations'            => VMPlayer_Public::sanitize_stations_for_frontend( $stations ),
            'activeStationIndex'  => (int) $station_index,
            'defaultStationIndex' => isset( $settings['default_station'] ) ? (int) $settings['default_station'] : 0,
            'defaultLogoUrl'      => VMPlayer_Public::get_default_logo_url(),
            'refreshInterval'     => isset( $settings['metadata_refresh_interval'] )
                ? (int) $settings['metadata_refresh_interval']
                : 15,
            'enableVisualizer'    => ! empty( $settings['enable_visualizer'] ),
            'autoResume'          => ! empty( $settings['auto_resume'] ),
            'strings'             => self::get_popout_strings(),
        );
        ?>
    <script>
        window.vmplayerPopoutConfig = <?php echo wp_json_encode( $config ); ?>;
    </script>
    <script src="<?php echo esc_url( VMPLAYER_PLUGIN_URL . 'assets/js/vmplayer-visualizer.js?ver=' . $this->asset_version( 'assets/js/vmplayer-visualizer.js' ) ); ?>"></script>
    <script src="<?php echo esc_url( VMPLAYER_PLUGIN_URL . 'assets/js/vmplayer-kebab.js?ver=' . $this->asset_version( 'assets/js/vmplayer-kebab.js' ) ); ?>"></script>
    <script src="<?php echo esc_url( VMPLAYER_PLUGIN_URL . 'assets/js/vmplayer-popout.js?ver=' . $this->asset_version( 'assets/js/vmplayer-popout.js' ) ); ?>"></script>
</body>
</html>
        <?php
    }

    /**
     * Render a friendly empty state when no stations are configured.
     * Users would hit this only if the popout URL is bookmarked and
     * stations were deleted after.
     *
     * @return void
     */
    private function render_empty_popout() {
        nocache_headers();
        remove_all_actions( 'wp_head' );
        remove_all_actions( 'wp_footer' );
        ?><!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo( 'charset' ); ?>">
    <title><?php esc_html_e( 'VMPlayer', 'vmplayer' ); ?></title>
    <style>
        body { background: #0a0a0f; color: #f8fafc; font-family: -apple-system, BlinkMacSystemFont, sans-serif; padding: 2em; text-align: center; }
    </style>
</head>
<body>
    <p><?php esc_html_e( 'No stations configured.', 'vmplayer' ); ?></p>
</body>
</html>
        <?php
    }

    /**
     * Popout-specific translatable strings.
     *
     * @return array
     */
    private static function get_popout_strings() {
        return array(
            'popOutPlayer' => esc_html__( 'POP OUT PLAYER', 'vmplayer' ),
            'onAir'        => esc_html__( 'ON AIR', 'vmplayer' ),
            'nowPlaying'   => esc_html__( 'NOW PLAYING', 'vmplayer' ),
            'streamingVia' => esc_html__( 'STREAMING VIA', 'vmplayer' ),
            'followUs'     => esc_html__( 'FOLLOW US', 'vmplayer' ),
            'supports'     => esc_html__( 'Supports:', 'vmplayer' ),
            'play'         => esc_html__( 'Play', 'vmplayer' ),
            'pause'        => esc_html__( 'Pause', 'vmplayer' ),
            'mute'         => esc_html__( 'Mute', 'vmplayer' ),
            'unmute'       => esc_html__( 'Unmute', 'vmplayer' ),
            'previous'     => esc_html__( 'Previous station', 'vmplayer' ),
            'next'         => esc_html__( 'Next station', 'vmplayer' ),
            'dock'         => esc_html__( 'Dock back to main player', 'vmplayer' ),
            'minimize'     => esc_html__( 'Minimize to compact bar', 'vmplayer' ),
            'restore'      => esc_html__( 'Restore full player', 'vmplayer' ),
            'close'        => esc_html__( 'Close pop-out', 'vmplayer' ),
            'menu'         => esc_html__( 'More options', 'vmplayer' ),
            'share'        => esc_html__( 'Share', 'vmplayer' ),
            'switchMount'  => esc_html__( 'Switch Quality', 'vmplayer' ),
            'settings'     => esc_html__( 'Player Settings', 'vmplayer' ),
            'about'        => esc_html__( 'About', 'vmplayer' ),
            'copyLink'     => esc_html__( 'Copy link', 'vmplayer' ),
            'linkCopied'   => esc_html__( 'Link copied!', 'vmplayer' ),
            'shareFB'      => esc_html__( 'Share on Facebook', 'vmplayer' ),
            'shareTwitter' => esc_html__( 'Share on X', 'vmplayer' ),
            'shareEmail'   => esc_html__( 'Share via email', 'vmplayer' ),
            'enableViz'    => esc_html__( 'Show visualizer', 'vmplayer' ),
            'enableAR'     => esc_html__( 'Auto-resume when pop-out closes', 'vmplayer' ),
            /* translators: 1: current station number, 2: total station count */
            'stationOf'    => esc_html__( 'Station %1$d of %2$d', 'vmplayer' ),
        );
    }

    /* ------------------------------------------------------------------
     * Utility
     * --------------------------------------------------------------- */

    /**
     * Build a filemtime-based asset version. Same pattern used by
     * public and admin classes so cache busts consistently across the
     * plugin whenever a file changes on disk.
     *
     * @param string $relative_path Path relative to plugin root.
     * @return string
     */
    private function asset_version( $relative_path ) {
        $full_path = VMPLAYER_PLUGIN_DIR . $relative_path;
        if ( file_exists( $full_path ) ) {
            return $this->version . '.' . filemtime( $full_path );
        }
        return $this->version;
    }
}
