<?php
/**
 * Volade Features — 3 niveaux d'accès par plugin
 *
 * guest      : base du plugin, sans compte (WP.org)
 * connected  : fonctionnalités étendues / limites plus hautes + écosystème
 * premium    : tout le premium du plugin + premium de tous les plugins V+
 *
 * @package Volade\SDK
 * @license GPL-2.0-or-later
 */

trait Volade_Features {

    /** @var array<string, array<string, array>> */
    private $plugin_features = array();

    public function init_features() {
        // Réservé aux hooks futurs.
    }

    /**
     * Déclarer les fonctionnalités d'un plugin et leur niveau requis.
     */
    public function register_features( array $features, $plugin_slug = '' ) {
        $slug = $plugin_slug ?: $this->plugin_slug;
        if ( ! $slug ) {
            return;
        }
        if ( ! isset( $this->plugin_features[ $slug ] ) ) {
            $this->plugin_features[ $slug ] = array();
        }
        $this->plugin_features[ $slug ] = array_merge( $this->plugin_features[ $slug ], $features );
    }

    private function get_feature_def( $feature, $plugin_slug = '' ) {
        $slug = $plugin_slug ?: $this->plugin_slug;
        if ( ! $slug || ! isset( $this->plugin_features[ $slug ][ $feature ] ) ) {
            return array();
        }
        return $this->plugin_features[ $slug ][ $feature ];
    }

    /**
     * Niveau d'accès courant sur ce site.
     *
     * @return string guest|connected|premium
     */
    public function get_access_level( $user_id = 0 ) {
        if ( ! $this->is_user_logged_in() ) {
            return 'guest';
        }

        if ( ! $user_id ) {
            $user = $this->get_current_user();
            $user_id = $user ? (int) $user['id'] : 0;
        }

        if ( $user_id && $this->is_premium( $user_id ) && $this->can_use_on_this_site( $user_id ) ) {
            return 'premium';
        }

        return 'connected';
    }

    public function is_guest() {
        return $this->get_access_level() === 'guest';
    }

    public function is_connected() {
        return $this->get_access_level() === 'connected';
    }

    public function has_premium_access( $user_id = 0 ) {
        return $this->get_access_level( $user_id ) === 'premium';
    }

    /**
     * Accès à une fonctionnalité du plugin courant.
     */
    public function has_access( $feature, $user_id = 0, $plugin_slug = '' ) {
        $required = $this->get_feature_def( $feature, $plugin_slug )['level'] ?? 'guest';
        return $this->access_level_meets( $this->get_access_level( $user_id ), $required );
    }

    /**
     * Limite numérique selon le niveau (ex. exports / mois). -1 = illimité.
     */
    public function get_feature_limit( $feature, $user_id = 0, $plugin_slug = '' ) {
        $level = $this->get_access_level( $user_id );
        $config = $this->get_feature_def( $feature, $plugin_slug );
        $key = $level . '_limit';

        if ( isset( $config[ $key ] ) ) {
            return (int) $config[ $key ];
        }

        if ( $level === 'premium' ) {
            return isset( $config['premium_limit'] ) ? (int) $config['premium_limit'] : -1;
        }

        if ( $level === 'connected' && isset( $config['connected_limit'] ) ) {
            return (int) $config['connected_limit'];
        }

        return isset( $config['guest_limit'] ) ? (int) $config['guest_limit'] : 0;
    }

    /**
     * Premium d'un autre plugin Volade — débloqué si V+ actif sur ce site.
     */
    public function has_ecosystem_premium( $user_id = 0 ) {
        return $this->has_premium_access( $user_id );
    }

    public function get_access_level_label( $level = '' ) {
        if ( ! $level ) {
            $level = $this->get_access_level();
        }

        $labels = array(
            'guest'     => __( 'Sans compte', 'php-compatibility-checker-by-volade' ),
            'connected' => __( 'Compte Volade', 'php-compatibility-checker-by-volade' ),
            'premium'   => __( 'V+ Premium', 'php-compatibility-checker-by-volade' ),
        );

        return $labels[ $level ] ?? $labels['guest'];
    }

    public function get_upgrade_target_for_feature( $feature, $plugin_slug = '' ) {
        $required = $this->get_feature_def( $feature, $plugin_slug )['level'] ?? 'guest';
        $current = $this->get_access_level();

        if ( $this->access_level_meets( $current, $required ) ) {
            return '';
        }

        return $required === 'premium' ? 'premium' : 'connected';
    }

    /**
     * Mode discret wp.org : pas de gros CTA upsell pour les visiteurs sans compte.
     */
    public function use_discreet_guest_upsell() {
        return $this->is_guest();
    }

    /**
     * Encart upsell dans l'admin du plugin.
     */
    public function render_access_gate( $feature, $args = array(), $plugin_slug = '' ) {
        if ( $this->has_access( $feature, 0, $plugin_slug ) ) {
            return;
        }

        $target = $this->get_upgrade_target_for_feature( $feature, $plugin_slug );
        $defaults = array(
            'connected' => __( 'Connectez votre compte Volade pour débloquer cette fonctionnalité (ou des limites plus hautes).', 'php-compatibility-checker-by-volade' ),
            'premium'   => __( 'Passez à V+ Premium pour débloquer cette fonctionnalité — et le premium de tous les plugins Volade.', 'php-compatibility-checker-by-volade' ),
        );
        $message = $args['message'] ?? ( $defaults[ $target ] ?? $defaults['connected'] );

        if ( $this->use_discreet_guest_upsell() ) {
            $auth_url = admin_url( 'admin.php?page=volade-auth' );
            ?>
            <p class="volade-muted volade-access-gate-discreet">
                <?php echo esc_html( $message ); ?>
                <a href="<?php echo esc_url( $auth_url ); ?>"><?php esc_html_e( 'Compte Volade (optionnel)', 'php-compatibility-checker-by-volade' ); ?></a>
            </p>
            <?php
            return;
        }

        $cta = $target === 'premium'
            ? admin_url( 'admin.php?page=volade-premium' )
            : admin_url( 'admin.php?page=volade-auth' );
        $cta_label = $target === 'premium'
            ? __( 'Voir V+ Premium', 'php-compatibility-checker-by-volade' )
            : __( 'Créer un compte gratuit', 'php-compatibility-checker-by-volade' );

        ?>
        <div class="volade-card volade-access-gate">
            <p><?php echo esc_html( $message ); ?></p>
            <a href="<?php echo esc_url( $cta ); ?>" class="volade-btn volade-btn-primary volade-btn-sm">
                <?php echo esc_html( $cta_label ); ?>
            </a>
        </div>
        <?php
    }

    public function get_access_model_summary() {
        return array(
            'guest' => array(
                'label'       => $this->get_access_level_label( 'guest' ),
                'description' => __( 'Fonctionnalités de base du plugin. Aucun compte requis.', 'php-compatibility-checker-by-volade' ),
            ),
            'connected' => array(
                'label'       => $this->get_access_level_label( 'connected' ),
                'description' => __( 'Fonctionnalités étendues, limites plus hautes, XP, badges, discover et parrainage.', 'php-compatibility-checker-by-volade' ),
            ),
            'premium' => array(
                'label'       => $this->get_access_level_label( 'premium' ),
                'description' => __( 'Tout le premium de ce plugin + le premium de tous les plugins Volade + licence multi-sites.', 'php-compatibility-checker-by-volade' ),
            ),
        );
    }

    private function access_level_rank( $level ) {
        $ranks = array( 'guest' => 0, 'connected' => 1, 'premium' => 2 );
        return $ranks[ $level ] ?? 0;
    }

    private function access_level_meets( $current, $required ) {
        return $this->access_level_rank( $current ) >= $this->access_level_rank( $required );
    }

    public function rest_access_status( $request ) {
        $user = $this->get_current_user();
        $level = $this->get_access_level();

        return rest_ensure_response( array(
            'access_level'       => $level,
            'access_level_label' => $this->get_access_level_label( $level ),
            'is_guest'           => $level === 'guest',
            'is_connected'       => $level === 'connected',
            'is_premium'         => $level === 'premium',
            'has_ecosystem_premium' => $this->has_ecosystem_premium(),
            'user_id'            => $user ? (int) $user['id'] : 0,
            'model'              => $this->get_access_model_summary(),
        ) );
    }
}
