<?php 

class ESSB_MyAPI {
    
    /**
     * The main API address
     * @var string
     */
    private static $api_url = 'https://my.socialsharingplugin.com/wp-json/my-essb/v1/';
    
    private static $news_types = array(
        'news' => array('title' => 'New', 'color' => '#1D89F9'),
        'promo' => array('title' => 'Promo', 'color' => '#C94670'),
        'update' => array('title' => 'Update', 'color' => '#419C33'),
        'other' => array('title' => 'Other', 'color' => '#CB9C2A'),
        'guide' => array('title' => 'Blog', 'color' => '#57C5EA')
    );
    
    /**
     * Read the API endpoint and retrieve the result
     * @param string $endpoint
     * @param array $options
     * @return mixed
     */
    private static function get($endpoint = '', $options = array()) {
        
        $url = self::$api_url . $endpoint;
        
        if (count($options) > 0) {
            $url = add_query_arg($options, $url);
        }
        
        $response = wp_remote_get( $url );        
        return json_decode( wp_remote_retrieve_body( $response ) );
    }    
    
    private static function post($endpoint = '', $options = array()) {
        $url = self::$api_url . $endpoint;
        
        if (count($options) > 0) {
            $url = add_query_arg($options, $url);
        }
                
        $curl = curl_init();
        
        curl_setopt_array($curl, array (
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 2,
            CURLOPT_TIMEOUT => 10,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_HTTPHEADER => array (
                "Content-Type: application/json"
            )
        ));
        
        $response = curl_exec($curl);
        curl_close($curl);
        
        return json_decode( $response );
    }
    
    private static function output_type($type = '') {
        $r = '';
        
        if (isset(self::$news_types[$type])) {
            $r = self::$news_types[$type]['title'];
        }
        
        return $r;
    }
    
    private static function format_date_to_local($date = '') {
        $date = str_replace('-', '/', $date);
        $time = strtotime($date);
        
        return date(get_option('date_format'), $time);        
    }
    
    private static function stylesheet_feed() {
        $output = '';
        
        $output .= '.essb-admin-dashboard-widget .essb-news-typetag-update { background-color: ' . self::$news_types['update']['color'] . '; }';
        $output .= '.essb-admin-dashboard-widget .essb-news-typetag-news { background-color: ' . self::$news_types['news']['color'] . '; }';
        $output .= '.essb-admin-dashboard-widget .essb-news-typetag-promo { background-color: ' . self::$news_types['promo']['color'] . '; }';
        $output .= '.essb-admin-dashboard-widget .essb-news-typetag-other { background-color: ' . self::$news_types['other']['color'] . '; }';
        $output .= '.essb-admin-dashboard-widget .essb-news-typetag-guide { background-color: ' . self::$news_types['guide']['color'] . '; }';
        $output .= '.essb-admin-dashboard-widget .essb-news-typetag {
            display: inline-block;
            padding: 3px 5px;
            border-radius: 5px;
            font-size: 11px;
            text-transform: uppercase;
            color: #fff;
            line-height: 1em;
            margin-right: 5px;
            font-weight: 600;
        }';
        
        $output .= '.essb-admin-dashboard-widget .essb-news-row { margin-top: 10px; margin-bottom: 10px; }';
        $output .= '.essb-admin-dashboard-widget .essb-news-row .essb-news-title a { font-weight: 600; text-decoration: none; line-height: 1.4em; }';
        $output .= '.essb-admin-dashboard-widget .essb-news-row .essb-news-date { margin-left: 5px; }';
        $output .= '.essb-admin-dashboard-widget .essb-admindash-overview-logo { border-radius: 50px; }';
        
        return $output;
    }
    
    public static function get_latest_news() {
        if ( false === ( $news = get_transient('essb_api_latest_news'))) {
            $news = self::get('news');
            delete_transient('essb_api_latest_news');
            set_transient('essb_api_latest_news', $news, DAY_IN_SECONDS);
        }
        
        return $news;
    }
    
    public static function generate_news_output($news = array()) {
        $output = '';
        
        $output .= '<style>' . self::stylesheet_feed() . '</style>';
        
        foreach ($news as $obj) {                    
            $title = $obj->display_title;
            if (empty($title)) {
                $title = $obj->title;
            }
            
            $obj->url = add_query_arg ( array( 'utm_source' => 'news', 'utm_medium' => 'widget', 'utm_campaign' => $obj->type), $obj->url);
            
            $output .= '<div class="essb-news-row">';
            $type_color = isset(self::$news_types[$obj->type]) ? self::$news_types[$obj->type]['color'] : '#999';
            $output .= '<span class="essb-news-typetag essb-news-typetag-' . $obj->type . '" style="background-color:' . $type_color . '">' . self::output_type($obj->type) . '</span>';
            $output .= '<span class="essb-news-title"><a href="'. $obj->url .'" target="_blank">' . $title . '</a></span>';
            if ($obj->type == 'promo') {
                $output .= '<span class="essb-news-date">' . self::format_date_to_local($obj->period_from) . ' - ' . self::format_date_to_local($obj->period_to) . '</span>';
            }
            else {
                $output .= '<span class="essb-news-date">'.self::format_date_to_local($obj->date).'</span>';
            }
            
            $output .= '</div>';
        }        
        
        return $output;
    }
    
    /**
     * Generate an inline code verification snippet
     */
    public static function refresh_news() {
        $hash = hash ( 'sha1', ESSBActivationManager::domain() );
            
        $code = "
<script>
jQuery(document).ready(function( $ ) {
	\"use strict\";
    let options = { 'action': 'essb_update_latest_news', 'hash': '" . $hash . "' };
				$.ajax({
		            type: \"POST\",
		            url: '".esc_url(admin_url ('admin-ajax.php'))."',
		            data: options,
		            success: function (data) {
		            	console.log(data);		            	
		            }
		    	});
});
</script>
";
        echo $code;
    }
    
    
    public static function define_news_update_action() {
        $essb_settings_access = essb_option_value('essb_access');
        if (empty($essb_settings_access)) {
            $essb_settings_access = 'manage_options';
        }
        
        if (is_admin() && current_user_can($essb_settings_access)) {
            add_action ( 'wp_ajax_essb_update_latest_news', array ('ESSB_MyAPI', 'update_latest_news' ) );
        }
    }
    
    public static function update_latest_news() {
        $current_news = self::get_latest_news();
        
        if (is_array($current_news)) {
            echo '200';
        }
        else {
            echo '404';
        }
        die();
    }
    
    public static function news_update_required() {
        $r = false;
        if (!essb_option_bool_value('deactivate_appscreo')) {
            if ( false === ( $news = get_transient('essb_api_latest_news'))) {
                $r = true;
            }
        }
        
        return $r;
    }
    
    
    public static function dismiss_promotion() {
        if (isset($_GET['essb_dismiss_promo']) && $_GET['essb_dismiss_promo'] == '1') {
            if (wp_verify_nonce($_GET['_wpnonce'], 'essb_dismiss_promo')) {
                $user_id = get_current_user_id();
                set_transient('essb_promo_dismissed_' . $user_id, 1, WEEK_IN_SECONDS);
                wp_safe_redirect(remove_query_arg(array('essb_dismiss_promo', '_wpnonce')));
                exit;
            }
        }
    }

    public static function is_promotion_dismissed() {
        $user_id = get_current_user_id();
        return false !== get_transient('essb_promo_dismissed_' . $user_id);
    }

    public static function get_active_promotion() {
        if (self::is_promotion_dismissed()) {
            return false;
        }
        $news = get_transient('essb_api_latest_news');
        if (is_array($news)) {
            foreach ($news as $obj) {
                if ($obj->type == 'promo') {
                    $period_from = strtotime($obj->period_from);
                    $period_to = strtotime($obj->period_to);
                    if (time() >= $period_from && time() <= $period_to) {
                        if (!$obj->display_title || empty($obj->display_title)) {
                            $obj->display_title = $obj->title;
                        }
                        $obj->url = add_query_arg(array('utm_source' => 'news', 'utm_medium' => 'dashboard_banner', 'utm_campaign' => $obj->type), $obj->url);
                        return $obj;
                    }
                }
            }
        }
        return false;
    }

    public static function render_promotion_banner() {
        $promo = self::get_active_promotion();
        if (!$promo) {
            return '';
        }

        $dismiss_url = wp_nonce_url(add_query_arg('essb_dismiss_promo', '1'), 'essb_dismiss_promo');

        $output = '<style>
            .essb-promo-banner {
                display: flex;
                align-items: center;
                gap: 16px;
                background: linear-gradient(135deg, #C94670 0%, #e05a82 100%);
                border-radius: 6px;
                padding: 16px 20px;
                margin-bottom: 24px;
                color: #fff;
                box-shadow: 0 1px 3px rgba(201, 70, 112, .2);
            }
            .essb-promo-banner-icon {
                flex-shrink: 0;
                width: 40px;
                height: 40px;
                background: rgba(255,255,255,.2);
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 20px;
            }
            .essb-promo-banner-content {
                flex: 1;
                min-width: 0;
            }
            .essb-promo-banner-title {
                font-size: 15px;
                font-weight: 600;
                line-height: 1.3;
            }
            .essb-promo-banner-period {
                font-size: 12px;
                opacity: .85;
                margin-top: 2px;
            }
            .essb-promo-banner-action {
                flex-shrink: 0;
                text-align: center;
            }
            .essb-promo-banner-action a:first-child {
                display: inline-block;
                background: #fff;
                color: #C94670;
                font-size: 13px;
                font-weight: 600;
                padding: 8px 18px;
                border-radius: 4px;
                text-decoration: none;
                transition: background .2s;
            }
            .essb-promo-banner-action a:first-child:hover {
                background: #f5f5f5;
                color: #b33d5f;
            }
            .essb-promo-banner-dismiss {
                display: block;
                color: rgba(255,255,255,.75);
                font-size: 12px;
                text-decoration: none;
                margin-top: 6px;
                transition: color .2s;
            }
            .essb-promo-banner-dismiss:hover {
                color: #fff;
            }
            @media (max-width: 600px) {
                .essb-promo-banner { flex-wrap: wrap; }
                .essb-promo-banner-action { width: 100%; }
                .essb-promo-banner-action a { display: block; text-align: center; }
            }
        </style>';

        $output .= '<div class="essb-promo-banner">';
        $output .= '<div class="essb-promo-banner-icon"><svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg></div>';
        $output .= '<div class="essb-promo-banner-content">';
        $output .= '<div class="essb-promo-banner-title">' . esc_html($promo->display_title) . '</div>';
        $output .= '<div class="essb-promo-banner-period">' . esc_html(self::format_date_to_local($promo->period_from)) . ' &ndash; ' . esc_html(self::format_date_to_local($promo->period_to)) . '</div>';
        $output .= '</div>';
        $output .= '<div class="essb-promo-banner-action"><a href="' . esc_url($promo->url) . '" target="_blank">' . esc_html__('Learn More', 'essb') . '</a><a href="' . esc_url($dismiss_url) . '" class="essb-promo-banner-dismiss">' . esc_html__('Dismiss', 'essb') . '</a></div>';
        $output .= '</div>';

        return $output;
    }

    public static function has_promotion() {
        ESSB_MyAPI::dismiss_promotion();
        echo self::render_promotion_banner();
    }
}