<?php
/**
 * Volade Premium — Tiers, site limits, checkout Stripe, upsell
 *
 * @package Volade\SDK
 * @license GPL-2.0-or-later
 */

trait Volade_Premium {

	private $tiers = array(
		'free'   => array(
			'label'         => 'Gratuit',
			'site_limit'    => 0,
			'price_monthly' => 0,
			'price_yearly'  => 0,
		),
		'solo'   => array(
			'label'         => 'V+ Solo',
			'site_limit'    => 1,
			'price_monthly' => 799,
			'price_yearly'  => 7900,
		),
		'pro'    => array(
			'label'         => 'V+ Pro',
			'site_limit'    => 5,
			'price_monthly' => 1490,
			'price_yearly'  => 14900,
		),
		'agency' => array(
			'label'         => 'V+ Agence',
			'site_limit'    => -1,
			'price_monthly' => 1990,
			'price_yearly'  => 19900,
		),
	);

	public function init_premium() {
		add_action( 'wp_ajax_volade_checkout', array( $this, 'ajax_checkout' ) );
		add_action( 'wp_ajax_volade_sync_subscription', array( $this, 'ajax_sync_subscription' ) );
		add_action( 'admin_init', array( $this, 'maybe_register_current_site' ) );
	}

	/**
	 * V+ : licence multi-sites + premium écosystème sur ce site.
	 * Sans compte ou compte gratuit : plugin utilisable (niveau guest / connected).
	 */
	public function can_use_on_this_site( $user_id = 0 ) {
		if ( ! $this->is_user_logged_in() ) {
			return true;
		}

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

		if ( ! $user_id || ! $this->is_premium( $user_id ) ) {
			return true;
		}

		return $this->is_site_registered( $user_id ) || $this->can_activate_site( $user_id );
	}

	public function is_site_registered( $user_id = 0, $site_url = '' ) {
		if ( ! $user_id ) {
			$user = $this->get_current_user();
			if ( ! $user ) {
				return false;
			}
			$user_id = $user['id'];
		}

		global $wpdb;
		$site_url = $site_url ?: home_url();

		return (bool) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT id FROM {$wpdb->prefix}volade_sites WHERE user_id = %d AND site_url = %s AND is_active = 1 LIMIT 1",
				$user_id,
				$site_url
			)
		);
	}

	public function maybe_register_current_site() {
		if ( ! is_admin() || ! $this->is_user_logged_in() || ! $this->is_premium() ) {
			return;
		}

		$user = $this->get_current_user();
		if ( ! $user ) {
			return;
		}

		if ( $this->is_site_registered( $user['id'] ) ) {
			return;
		}

		$this->register_site( $user['id'] );
	}

	public function get_tier( $user_id = 0 ) {
		if ( ! $user_id ) {
			$user = $this->get_current_user();
			if ( ! $user ) {
				return 'free';
			}
			$user_id = $user['id'];
		}

		$cache = get_transient( 'volade_tier_' . $user_id );
		if ( false !== $cache ) {
			return $cache;
		}

		$tier = 'free';
		global $wpdb;

		$sub = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT plan, status, current_period_end FROM {$wpdb->prefix}volade_subscriptions WHERE user_id = %d AND status = 'active' LIMIT 1",
				$user_id
			)
		);

		if ( $sub ) {
			if ( $sub->current_period_end && strtotime( $sub->current_period_end ) < time() ) {
				$wpdb->update(
					"{$wpdb->prefix}volade_subscriptions",
					array( 'status' => 'expired' ),
					array( 'user_id' => $user_id )
				);
			} else {
				$tier = $sub->plan;
			}
		}

		if ( $tier === 'free' ) {
			$api = Volade_API::get_instance();
			if ( $api ) {
				$remote = $api->get( '/subscription/status', array( 'user_id' => $user_id ) );
				if ( ! is_wp_error( $remote ) && ! empty( $remote['tier'] ) && $remote['tier'] !== 'free' ) {
					$tier = $remote['tier'];
					$this->store_subscription( $user_id, $tier, $remote );
				}
			}
		}

		set_transient( 'volade_tier_' . $user_id, $tier, HOUR_IN_SECONDS );
		return $tier;
	}

	public function is_premium( $user_id = 0 ) {
		return $this->get_tier( $user_id ) !== 'free';
	}

	public function get_site_limit( $user_id = 0 ) {
		$tier = $this->get_tier( $user_id );
		return $this->tiers[ $tier ]['site_limit'] ?? 0;
	}

	public function can_activate_site( $user_id = 0 ) {
		if ( ! $user_id ) {
			$user = $this->get_current_user();
			if ( ! $user ) {
				return false;
			}
			$user_id = $user['id'];
		}

		if ( ! $this->is_premium( $user_id ) ) {
			return false;
		}

		$limit = $this->get_site_limit( $user_id );
		if ( $limit === -1 ) {
			return true;
		}

		global $wpdb;
		$active = (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM {$wpdb->prefix}volade_sites WHERE user_id = %d AND is_active = 1",
				$user_id
			)
		);

		return $active < $limit;
	}

	public function register_site( $user_id = 0, $site_url = '' ) {
		if ( ! $user_id ) {
			$user = $this->get_current_user();
			if ( ! $user ) {
				return new WP_Error( 'not_logged_in', __( 'Vous devez être connecté.', 'core-version-switcher-by-volade' ) );
			}
			$user_id = $user['id'];
		}

		if ( ! $this->is_premium( $user_id ) ) {
			return new WP_Error( 'not_premium', __( 'Abonnement V+ requis pour la licence multi-sites.', 'core-version-switcher-by-volade' ) );
		}

		global $wpdb;
		$site_url = $site_url ?: home_url();

		$existing = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT id FROM {$wpdb->prefix}volade_sites WHERE user_id = %d AND site_url = %s LIMIT 1",
				$user_id,
				$site_url
			)
		);

		if ( $existing ) {
			$wpdb->update(
				"{$wpdb->prefix}volade_sites",
				array(
					'is_active'    => 1,
					'plugin_slug'  => $this->plugin_slug ?? '',
					'wp_version'   => get_bloginfo( 'version' ),
					'php_version'  => PHP_VERSION,
					'activated_at' => current_time( 'mysql' ),
				),
				array( 'id' => $existing )
			);
			return (int) $existing;
		}

		if ( ! $this->can_activate_site( $user_id ) ) {
			return new WP_Error( 'site_limit', __( 'Limite de sites atteinte. Passez à une formule V+ supérieure.', 'core-version-switcher-by-volade' ) );
		}

		$wpdb->insert(
			"{$wpdb->prefix}volade_sites",
			array(
				'user_id'      => $user_id,
				'site_url'     => $site_url,
				'plugin_slug'  => $this->plugin_slug ?? '',
				'wp_version'   => get_bloginfo( 'version' ),
				'php_version'  => PHP_VERSION,
				'is_active'    => 1,
				'activated_at' => current_time( 'mysql' ),
			)
		);

		$this->log_event(
			$user_id,
			'site_activated',
			array(
				'site_url' => $site_url,
				'plugin'   => $this->plugin_slug ?? '',
			)
		);

		return $wpdb->insert_id;
	}

	public function get_active_sites_count( $user_id = 0 ) {
		if ( ! $user_id ) {
			$user = $this->get_current_user();
			if ( ! $user ) {
				return 0;
			}
			$user_id = $user['id'];
		}

		global $wpdb;
		return (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM {$wpdb->prefix}volade_sites WHERE user_id = %d AND is_active = 1",
				$user_id
			)
		);
	}

	public function get_tier_label( $tier = '' ) {
		if ( ! $tier ) {
			$tier = $this->get_tier();
		}
		return $this->tiers[ $tier ]['label'] ?? __( 'Gratuit', 'core-version-switcher-by-volade' );
	}

	public function get_tier_price( $tier, $period = 'monthly' ) {
		if ( ! isset( $this->tiers[ $tier ] ) ) {
			return 0;
		}
		$key = $period === 'yearly' ? 'price_yearly' : 'price_monthly';
		return $this->tiers[ $tier ][ $key ] ?? 0;
	}

	public function get_tier_price_display( $tier, $period = 'monthly' ) {
		$cents = $this->get_tier_price( $tier, $period );
		if ( $cents === 0 ) {
			return __( 'Gratuit', 'core-version-switcher-by-volade' );
		}
		if ( $period === 'yearly' ) {
			return number_format( $cents / 100, 0, ',', ' ' ) . ' €';
		}
		return number_format( $cents / 100, 2, ',', ' ' ) . ' €';
	}

	public function get_checkout_url( $tier, $period = 'monthly', $return_url = '' ) {
		$api = Volade_API::get_instance();
		if ( ! $api ) {
			return '';
		}

		if ( ! $return_url ) {
			$return_url = admin_url( 'admin.php?page=volade-premium' );
		}

		$user = $this->get_current_user();
		if ( ! $user ) {
			return '';
		}

		$response = $api->post(
			'/checkout/create',
			array(
				'tier'       => $tier,
				'period'     => $period,
				'user_id'    => $user['id'],
				'user_email' => $user['email'],
				'return_url' => $return_url,
			)
		);

		if ( is_wp_error( $response ) || empty( $response['url'] ) ) {
			return '';
		}

		return $response['url'];
	}

	public function get_portal_url() {
		$api = Volade_API::get_instance();
		if ( ! $api ) {
			return '';
		}

		$user = $this->get_current_user();
		if ( ! $user ) {
			return '';
		}

		$response = $api->post(
			'/checkout/portal',
			array(
				'user_id'    => $user['id'],
				'user_email' => $user['email'],
				'return_url' => admin_url( 'admin.php?page=volade-premium' ),
			)
		);

		if ( is_wp_error( $response ) || empty( $response['url'] ) ) {
			return '';
		}

		return $response['url'];
	}

	private function store_subscription( $user_id, $plan, $data ) {
		global $wpdb;
		delete_transient( 'volade_tier_' . $user_id );
		$wpdb->replace(
			"{$wpdb->prefix}volade_subscriptions",
			array(
				'user_id'                => $user_id,
				'plan'                   => $plan,
				'status'                 => 'active',
				'stripe_subscription_id' => $data['stripe_subscription_id'] ?? '',
				'stripe_customer_id'     => $data['stripe_customer_id'] ?? '',
				'current_period_start'   => $data['period_start'] ?? current_time( 'mysql' ),
				'current_period_end'     => $data['period_end'] ?? null,
				'created_at'             => current_time( 'mysql' ),
			)
		);
	}

	public function ajax_checkout() {
		check_ajax_referer( 'volade_nonce', 'nonce' );
		$user = $this->get_current_user();
		if ( ! $user ) {
			wp_send_json_error( __( 'Non authentifié.', 'core-version-switcher-by-volade' ) );
		}

		$tier   = sanitize_text_field( $_POST['tier'] ?? '' );
		$period = sanitize_text_field( $_POST['period'] ?? 'monthly' );

		if ( ! isset( $this->tiers[ $tier ] ) || $tier === 'free' ) {
			wp_send_json_error( __( 'Formule invalide.', 'core-version-switcher-by-volade' ) );
		}

		$url = $this->get_checkout_url( $tier, $period );
		if ( ! $url ) {
			wp_send_json_error( __( 'Paiement indisponible. Réessayez plus tard.', 'core-version-switcher-by-volade' ) );
		}

		wp_send_json_success( array( 'url' => $url ) );
	}

	public function ajax_sync_subscription() {
		check_ajax_referer( 'volade_nonce', 'nonce' );
		$user = $this->get_current_user();
		if ( ! $user ) {
			wp_send_json_error( __( 'Non authentifié.', 'core-version-switcher-by-volade' ) );
		}

		delete_transient( 'volade_tier_' . $user['id'] );
		$tier = $this->get_tier( $user['id'] );

		wp_send_json_success(
			array(
				'tier'       => $tier,
				'is_premium' => $tier !== 'free',
				'site_limit' => $this->get_site_limit( $user['id'] ),
				'sites_used' => $this->get_active_sites_count( $user['id'] ),
				'label'      => $this->get_tier_label( $tier ),
			)
		);
	}

	public function get_all_tiers() {
		return $this->tiers;
	}

	public function render_premium_upsell_badge() {
		$user = $this->get_current_user();
		if ( ! $user ) {
			return;
		}

		if ( $this->is_premium( $user['id'] ) ) {
			return;
		}
		?>
		<div class="volade-card volade-upsell-card">
			<div class="volade-upsell-inner">
				<span class="volade-upsell-icon">⭐</span>
				<div class="volade-upsell-text">
					<strong><?php $this->_e( 'V+ Premium' ); ?></strong>
					<span><?php $this->_e( 'Fonctionnalités premium + tous les plugins Volade sur plus de sites.' ); ?></span>
				</div>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=volade-premium' ) ); ?>" class="volade-btn volade-btn-primary">
					<?php $this->_e( 'Voir les formules' ); ?>
				</a>
			</div>
		</div>
		<?php
	}

	public function render_plugin_sidebar() {
		if ( ! is_admin() ) {
			return;
		}

		$user = $this->get_current_user();
		if ( ! $user && $this->use_discreet_guest_upsell() ) {
			return;
		}
		?>
		<div class="volade-plugin-sidebar">
			<div class="volade-sidebar-header">
				<strong>Volade</strong>
				<?php if ( $user ) : ?>
					<span class="volade-sidebar-user"><?php echo esc_html( $user['pseudo'] ); ?></span>
				<?php endif; ?>
			</div>
			<?php if ( ! $user ) : ?>
				<p><?php $this->_e( 'Connectez un compte Volade gratuit pour débloquer des limites plus élevées, l\'XP et les badges.' ); ?></p>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=volade-auth' ) ); ?>" class="volade-btn volade-btn-primary volade-btn-sm">
					<?php $this->_e( 'Se connecter' ); ?>
				</a>
			<?php else : ?>
				<?php if ( $this->is_premium( $user['id'] ) ) : ?>
					<p class="volade-sidebar-plan">
						<?php echo esc_html( $this->get_tier_label() ); ?>
						— <?php echo (int) $this->get_active_sites_count( $user['id'] ); ?> /
						<?php echo $this->get_site_limit( $user['id'] ) === -1 ? '∞' : (int) $this->get_site_limit( $user['id'] ); ?>
						<?php $this->_e( 'sites utilisés' ); ?>
					</p>
				<?php else : ?>
					<?php $this->render_premium_upsell_badge(); ?>
				<?php endif; ?>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=volade-discover' ) ); ?>" class="volade-btn volade-btn-secondary volade-btn-sm">
					<?php $this->_e( 'Découvrir les plugins' ); ?>
				</a>
			<?php endif; ?>
		</div>
		<?php
	}
}
