<?php
if (!defined('ABSPATH')) exit;

class HPIXLSecuricheck_Promo_Banner
{

    const HPIXL_SECURICHECK_REMOTE_CONFIG_URL = 'https://wp-securicheck.com/remote-config/securicheck-free.json';
    const HPIXL_SECURICHECK_TRANSIENT_KEY = 'securicheck_remote_promo_cle';
    const HPIXL_SECURICHECK_TRANSIENT_TTL = HOUR_IN_SECONDS;

    private static $config = null;

    public static function init()
    {
        if (!is_admin()) return;

        //add_action('admin_notices', [__CLASS__, 'render'], 1);
        add_action('in_admin_header', [__CLASS__, 'render'], 10);
    }


    public static function render()
    {
        // 1️⃣ Ne rien afficher si la version Pro est active
        if (self::is_securicheck_pro_active()) {
            return;
        }

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

        /* verifie si on a déjà fermé la baniere */

        $user_id = get_current_user_id();

        // Vérifier si la bannière est temporairement cachée
        $hidden_until = (int) get_user_meta(
            $user_id,
            'securicheck_promo_banner_hidden_until',
            true
        );

        if ($hidden_until && time() < $hidden_until) {
            return; // On n’affiche PAS la bannière
        }

        /* affiche la baniere*/

        $config = self::get_remote_config();
        if (empty($config)) return;

        // Vérifie activation globale
        if (empty($config['global_enabled'])) return;

        // Vérifie si la promo banner est activée
        if (empty($config['promo_banner']['enabled'])) return;

        $banner = $config['promo_banner'];

        // Vérifie la date de début / fin
        $now = time();
        if (!empty($banner['start_date']) && strtotime($banner['start_date']) > $now) return;
        if (!empty($banner['end_date'])) {
            //date de fin à 23h59 le jour même
            $end_timestamp = strtotime($banner['end_date'] . ' 23:59:59');
            if ($end_timestamp < $now) {
                return;
            }
        }

        // Vérifie les conditions
        $conditions = $banner['conditions'] ?? [];
        if (!empty($conditions['min_wp_version']) && version_compare(get_bloginfo('version'), $conditions['min_wp_version'], '<')) return;
        if (!empty($conditions['admin_only']) && !is_admin()) return;

        // Calcul des jours restants
        $remaining_days = 0;
        if (!empty($banner['end_date'])) {
            $remaining_days = max(0, ceil((strtotime($banner['end_date']) - $now) / DAY_IN_SECONDS));
        }

        //format date fin
        $dt = new DateTime($banner['end_date']);
        $dateFin = $dt->format('d/m/Y');

        // Prépare les données pour la vue
        $config = [
            'titre'          => $banner['content']['titre'] ?? '',
            'message'          => $banner['content']['message'] ?? '',
            'promotion'          => $banner['content']['promotion'] ?? '',
            'code_promotion'       => $banner['content']['code_promotion'] ?? '',
            'cta_label'      => $banner['content']['cta']['label'] ?? '',
            'cta_url'        => $banner['content']['cta']['url'] ?? '',
            'date_fin'        => $dateFin ?? '',
            'remaining_days' => $remaining_days,
            'background_image' => $banner['content']['background_image'] ?? '',
            'plugin_logo'      => $banner['content']['plugin_logo'] ?? ''
        ];

        $view_file = HPIXL_SECURICHECK_PLUGIN_PATH . '/admin/promo-banner-view.php';
        if (file_exists($view_file)) include $view_file;
    }

    private static function get_remote_config()
    {
        if (self::$config !== null) return self::$config;

        $cached = get_transient(self::HPIXL_SECURICHECK_TRANSIENT_KEY);
        if ($cached !== false) {
            self::$config = $cached;
            return self::$config;
        }

        $response = wp_remote_get(self::HPIXL_SECURICHECK_REMOTE_CONFIG_URL, ['timeout' => 5]);
        if (is_wp_error($response)) return null;

        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        if (!is_array($data)) return null;

        set_transient(self::HPIXL_SECURICHECK_TRANSIENT_KEY, $data, self::HPIXL_SECURICHECK_TRANSIENT_TTL);
        self::$config = $data;
        return self::$config;
    }

    private static function is_securicheck_pro_active(): bool
    {
        if (!function_exists('is_plugin_active')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        return is_plugin_active(HPIXL_SECURICHECK_PREMIUM_PLUGIN_NAME);
    }
}
