<?php
/**
 * Plan tier helpers and gateway routing.
 *
 * @package CatalogPilot\AiStudio
 */

namespace CatalogPilot\AiStudio;

defined( 'ABSPATH' ) || exit;

final class Pro {

	const PLAN_FREE    = 54594;
	const PLAN_STARTER = 54595;
	const PLAN_PRO     = 54597;

	public static function is_paying() : bool {
		if ( ! function_exists( 'cpais_fs' ) ) {
			return false;
		}
		$fs = cpais_fs();
		return $fs && method_exists( $fs, 'is_paying' ) ? (bool) $fs->is_paying() : false;
	}

	public static function is_trial() : bool {
		if ( ! function_exists( 'cpais_fs' ) ) {
			return false;
		}
		$fs = cpais_fs();
		return $fs && method_exists( $fs, 'is_trial' ) ? (bool) $fs->is_trial() : false;
	}

	public static function can_use_pro() : bool {
		return self::is_paying() || self::is_trial();
	}

	public static function active_plan_id() : int {
		if ( ! self::is_paying() ) {
			return self::PLAN_FREE;
		}
		$fs = cpais_fs();
		if ( $fs && method_exists( $fs, 'get_plan' ) ) {
			$plan = $fs->get_plan();
			if ( $plan && ! empty( $plan->id ) ) {
				return (int) $plan->id;
			}
		}
		return self::PLAN_FREE;
	}

	public static function gateway_base_url() : string {
		return apply_filters( 'cpais_gateway_base_url', 'https://api.wpcrypto.net' );
	}

	public static function daily_free_quota() : int {
		return (int) apply_filters( 'cpais_daily_free_quota', 20 );
	}

	public static function consume_free_quota() : bool {
		if ( self::can_use_pro() ) {
			return true;
		}
		$key   = 'cpais_quota_' . gmdate( 'Y_m_d' );
		$used  = (int) get_transient( $key );
		$limit = self::daily_free_quota();
		if ( $used >= $limit ) {
			return false;
		}
		set_transient( $key, $used + 1, DAY_IN_SECONDS );
		return true;
	}

	public static function upgrade_url() : string {
		if ( function_exists( 'cpais_fs' ) ) {
			$fs = cpais_fs();
			if ( $fs && method_exists( $fs, 'get_upgrade_url' ) ) {
				return (string) $fs->get_upgrade_url();
			}
		}
		return 'https://wpcrypto.net/';
	}

}
