<?php

defined( 'ABSPATH' ) || exit();

class Radio_Player_Admin {
    /** @var null */
    private static $instance = null;

    public $admin_pages = [];

    public function __construct() {
        add_action( 'admin_menu', [ $this, 'admin_menu' ] );
        add_action( 'admin_init', [ $this, 'init_update' ] );

        add_action( 'admin_notices', [ $this, 'display_notices' ] );

        // handle offer notice dismiss
        add_action( 'wp_ajax_rp_dismiss_offer_notice', [ $this, 'dismiss_offer_notice' ] );

        // Hide proxy player addon notice
        add_action( 'wp_ajax_rp_hide_radio_player_proxy_addon_notice', [ $this, 'hide_proxy_player_addon_notice' ] );

        add_action( 'wp_ajax_rp_hide_radio_player_ads_update_notice', [ $this, 'hide_ads_update_notice' ] );
        add_action( 'wp_ajax_rp_hide_radio_player_proxy_update_notice', [ $this, 'hide_proxy_update_notice' ] );
    }

    public function hide_proxy_player_addon_notice() {
        update_option( 'radio_player_proxy_addon_notice', 'off' );
        wp_send_json_success();
    }

    public function hide_ads_update_notice() {
        update_option( 'radio_player_ads_update_notice', 'off' );
        wp_send_json_success();
    }

    public function hide_proxy_update_notice() {
        update_option( 'radio_player_proxy_update_notice', 'off' );
        wp_send_json_success();
    }

    public function display_notices() {

        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        // Offer Notice
        if ( ! radio_player()->is_pro_active() ) {
            $offer = $this->get_offer_notice();

            if ( ! empty( $offer ) ) {
                $offer_html = $offer['html'];

                radio_player()->add_notice( 'info radio-player-offer-notice', $offer_html );

                return;
            }
        }

        // Proxy Player Update Notice
        if ('off' != get_option( 'radio_player_proxy_update_notice' ) &&  defined( 'RADIO_PLAYER_PROXY_VERSION' ) && version_compare( RADIO_PLAYER_PROXY_VERSION, '1.0.6', '<' ) ) {

            ob_start();
            include RADIO_PLAYER_INCLUDES . '/views/notice/radio-player-proxy-update.php';
            $notice_html = ob_get_clean();

            radio_player()->add_notice( 'warning  radio-player-proxy-update-notice', $notice_html );

            return;
        }

        // Ads Player Update Notice
        if ( 'off' != get_option( 'radio_player_ads_update_notice' ) && defined( 'RADIO_PLAYER_ADS_VERSION' ) && version_compare( RADIO_PLAYER_ADS_VERSION, '1.0.8', '<' ) ) {

            ob_start();
            include RADIO_PLAYER_INCLUDES . '/views/notice/radio-player-ads-update.php';
            $notice_html = ob_get_clean();

            radio_player()->add_notice( 'warning  radio-player-ads-update-notice', $notice_html );

            return;
        }

        // Proxy Player Promo Notice
        if ( $this->is_radio_player_admin_page() && 'off' != get_option( 'radio_player_proxy_addon_notice' ) && ! function_exists( 'rpp_fs' ) ) {

            ob_start();
            include RADIO_PLAYER_INCLUDES . '/views/notice/radio-player-proxy-addon.php';
            $notice_html = ob_get_clean();

            radio_player()->add_notice( 'info  radio-player-proxy-addon-notice', $notice_html );

            return;
        }

    }

    public function get_offer_notice() {

        $offer = get_transient( 'radio_player_offer_notice' );

        if ( false === $offer ) {
            // URL of the API on your server that returns offer data.
            $api_url = 'https://softlabbd.com/offers.php?plugin=radio-player';

            // Send GET request to your server to get offer data.
            $response = wp_remote_get( $api_url );

            // Check for errors.
            if ( is_wp_error( $response ) ) {
                return;
            }

            // Parse the response body.
            $offer_json = wp_remote_retrieve_body( $response );
            $offer      = json_decode( $offer_json, true );

            // Ensure we have an array and sanitize expected fields before saving.
            if ( is_array( $offer ) ) {
                if ( isset( $offer['start_date'] ) ) {
                    $offer['start_date'] = sanitize_text_field( $offer['start_date'] );
                }
                if ( isset( $offer['end_date'] ) ) {
                    $offer['end_date'] = sanitize_text_field( $offer['end_date'] );
                }
                if ( isset( $offer['html'] ) ) {
                    // Allow safe HTML (same tags allowed in post content).
                    $offer['html'] = wp_kses( $offer['html'], [
                            'a'      => [
                                    'href'   => [],
                                    'title'  => [],
                                    'target' => [],
                                    'class'  => [],
                            ],
                            'strong' => [],
                            'em'     => [],
                            'br'     => [],
                            'p'      => [],
                            'span'   => [ 'class' => [] ],
                            'div'    => [ 'class' => [] ],
                            'img'    => [
                                    'src'    => [],
                                    'alt'    => [],
                                    'width'  => [],
                                    'height' => [],
                                    'class'  => [],
                            ],
                            'h4'     => [ 'class' => [], ],
                            'h3'     => [ 'class' => [], ],
                            'i'      => [ 'class' => [] ],
                            'style'  => [],
                    ] );
                }
            }

            set_transient( 'radio_player_offer_notice', $offer, DAY_IN_SECONDS );

        }

        if ( empty( $offer ) ) {
            return;
        }

        if ( ! empty( $offer['dismissed'] ) ) {
            return;
        }

        $start_date   = strtotime( $offer['start_date'] );
        $end_date     = strtotime( $offer['end_date'] );
        $current_date = strtotime( gmdate( 'Y-m-d' ) );

        if ( $current_date < $start_date || $current_date > $end_date ) {
            return false;
        }

        return $offer;

    }

    public function dismiss_offer_notice() {
        $offer = get_transient( 'radio_player_offer_notice' );

        if ( false !== $offer ) {
            $offer['dismissed'] = true;
            set_transient( 'radio_player_offer_notice', $offer, 3 * DAY_IN_SECONDS );
        }
    }

    public function init_update() {

        if ( ! class_exists( 'Radio_Player_Update' ) ) {
            include RADIO_PLAYER_INCLUDES . '/class-update.php';
        }

        $updater = new Radio_Player_Update();

        if ( $updater->needs_update() ) {
            $updater->perform_updates();
        }

        //do redirect to welcome page on first activation
        if ( get_option( 'radio_player_do_activation_redirect', false ) ) {
            delete_option( 'radio_player_do_activation_redirect' );
            wp_safe_redirect( admin_url( 'admin.php?page=radio-player-getting-started' ) );
            exit;
        }

    }

    /**
     * Add admin menu
     * @since 1.0.0
     */
    public function admin_menu() {

        $slug       = 'radio-player';
        $capability = 'manage_options';

        $this->admin_pages['players_page'] = add_menu_page(
                esc_html__( 'Radio Player', 'radio-player' ),
                esc_html__( 'Radio Player', 'radio-player' ),
                $capability,
                $slug,
                [ $this, 'render_radio_player_page' ],
                RADIO_PLAYER_ASSETS . '/images/play.svg',
                57
        );

        // All players page
        $this->admin_pages['players_page'] = add_submenu_page( $slug, esc_html__( 'All Players', 'radio-player' ), esc_html__( 'All Players', 'radio-player' ), $capability, 'radio-player' );

        // Getting started page
        $this->admin_pages['getting_started_page'] = add_submenu_page( $slug, esc_html__( 'Getting Started - Radio Player', 'radio-player' ), esc_html__( 'Getting Started', 'radio-player' ), $capability, 'radio-player-getting-started', [
                $this,
                'render_getting_started_page',
        ] );

        // Settings page
        $this->admin_pages['settings_page'] = add_submenu_page( $slug, esc_html__( 'Settings - Radio Player', 'radio-player' ), esc_html__( 'Settings', 'radio-player' ), $capability, 'radio-player-settings', [
                $this,
                'render_settings_page',
        ], 10 );

        // Upgrade Menu Page - Only if Pro is not active
        if ( ! radio_player()->is_pro_active() ) {
            $this->admin_pages['upgrade_page'] =
                    add_submenu_page(
                            $slug,
                            esc_html__( 'Upgrade to Pro - Radio Player', 'radio-player' ),
                            '<i class="radio-player-icon icon-pro"></i>' . esc_html__( 'Upgrade', 'radio-player' ),
                            $capability,
                            'https://softlabbd.com/radio-player-pricing/?utm_source=free_plugin&utm_medium=admin_menu&utm_campaign=radio_player',
                            '',
                            '99'
                    );
        }

        $this->admin_pages = apply_filters( 'radio_player/admin_pages', $this->admin_pages, $slug, $capability );

    }

    public function render_radio_player_page() { ?>
        <div id="radio-player-app"></div>
        <?php
    }

    /**
     * Get started page callback
     *
     * @since 1.0.0
     */
    public function render_getting_started_page() {
        include RADIO_PLAYER_INCLUDES . '/views/getting-started/index.php';
    }

    public function render_settings_page() { ?>
        <div id="radio-player-settings" class="radio-player-settings"></div>
    <?php }

    public function is_radio_player_admin_page() {
        $admin_pages = $this->admin_pages;

        global $current_screen;

        if ( is_object( $current_screen ) && in_array( $current_screen->id, $admin_pages ) ) {
            return true;
        }

        return false;
    }

    /**
     * @return Radio_Player_Admin|null
     */
    public static function instance() {
        if ( is_null( self::$instance ) ) {
            self::$instance = new self();
        }

        return self::$instance;
    }
}


Radio_Player_Admin::instance();