<?php

/**
 * Freemius licensing bootstrap.
 *
 * @package WPDudeProducts
 */
declare (strict_types = 1);
namespace WPDude\Products\Licensing;

/**
 * Thin wrapper around the Freemius SDK.
 *
 * Product ID and public key come from the Freemius SDK Integration snippet.
 * They may be overridden via WPDUDE_DC_FS_ID / WPDUDE_DC_FS_PUBLIC_KEY
 * or filters for staging forks.
 *
 * Accessor function is wpdude_dc_fs() (Paywall uses wpdude_dp_fs).
 */
final class Freemius {
    /**
     * Freemius instance accessor name.
     */
    public const FS_SHORTCODE = 'wpdude_dc_fs';

    /**
     * Freemius product ID (public; from Developer Dashboard).
     */
    private const PRODUCT_ID = '36574';

    /**
     * Freemius public key (public; from Developer Dashboard).
     */
    private const PUBLIC_KEY = 'pk_7f6e432a50f2067af5a93d877c2bd';

    /**
     * Singleton.
     *
     * @var self|null
     */
    private static ?self $instance = null;

    /**
     * Freemius SDK object when initialised.
     *
     * @var \Freemius|null
     */
    private $fs = null;

    /**
     * Whether Freemius was initialised with real credentials.
     */
    private bool $configured = false;

    /**
     * Get singleton.
     */
    public static function instance() : self {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Initialise Freemius early.
     */
    public function init() : void {
        $product_id = $this->get_product_id();
        $public_key = $this->get_public_key();
        if ( '' === $product_id || '' === $public_key || $this->is_placeholder( $product_id ) || $this->is_placeholder( $public_key ) ) {
            $this->configured = false;
            return;
        }
        $sdk_start = WPDUDE_DC_PATH . 'vendor/freemius/wordpress-sdk/start.php';
        if ( !file_exists( $sdk_start ) ) {
            $this->configured = false;
            return;
        }
        // Avoid double-init if Freemius already bootstrapped.
        if ( function_exists( 'fs_dynamic_init' ) && isset( $GLOBALS['wpdude_dc_fs'] ) && is_object( $GLOBALS['wpdude_dc_fs'] ) ) {
            $this->fs = $GLOBALS['wpdude_dc_fs'];
            $this->configured = true;
            return;
        }
        require_once $sdk_start;
        // Source / premium package: is_premium true so is__premium_only() wrappers work.
        // Freemius deployment sets is_premium false and strips @fs_premium_only / __premium_only
        // for the WordPress.org free build. Paying sites receive the premium package.
        //
        // Product slug (WordPress.org / text domain): dude-commerce
        // Admin parent menu slug (Menu::MENU_SLUG): dude-commerce
        $this->fs = fs_dynamic_init( array(
            'id'               => $product_id,
            'slug'             => 'dude-commerce',
            'type'             => 'plugin',
            'public_key'       => $public_key,
            'is_premium'       => false,
            'is_premium_only'  => false,
            'premium_suffix'   => 'Premium',
            'has_addons'       => false,
            'has_paid_plans'   => true,
            'is_org_compliant' => true,
            'enable_anonymous' => true,
            'menu'             => array(
                'slug'    => 'dude-commerce',
                'support' => false,
            ),
            'is_live'          => true,
        ) );
        $GLOBALS['wpdude_dc_fs'] = $this->fs;
        $this->configured = true;
        do_action( 'wpdude_dc_fs_loaded', $this->fs );
    }

    /**
     * Raw Freemius object or null.
     *
     * @return \Freemius|null
     */
    public function fs() {
        return $this->fs;
    }

    /**
     * Whether Freemius was initialised with real credentials.
     */
    public function is_configured() : bool {
        return $this->configured;
    }

    /**
     * Whether the merchant has Pro access via Freemius (no local bypasses).
     *
     * Free plan features must work when this returns false (no licence / skipped opt-in).
     * Pro unlocks when the premium package is installed and the site has a valid licence/trial.
     *
     * Uses can_use_premium_code__premium_only() so Freemius strips this gate from free builds.
     */
    public function has_pro_access() : bool {
        if ( !$this->configured || !$this->fs ) {
            return false;
        }
        return false;
    }

    /**
     * @deprecated Use Capabilities::is_pro() for feature gates.
     */
    public function can_use_premium() : bool {
        return Capabilities::instance()->is_pro();
    }

    /**
     * Product ID from constant, filter, or Freemius dashboard default.
     */
    private function get_product_id() : string {
        if ( defined( 'WPDUDE_DC_FS_ID' ) ) {
            return (string) WPDUDE_DC_FS_ID;
        }
        $filtered = (string) apply_filters( 'wpdude_dc_fs_id', self::PRODUCT_ID );
        return ( '' !== $filtered ? $filtered : self::PRODUCT_ID );
    }

    /**
     * Public key from constant, filter, or Freemius dashboard default.
     */
    private function get_public_key() : string {
        if ( defined( 'WPDUDE_DC_FS_PUBLIC_KEY' ) ) {
            return (string) WPDUDE_DC_FS_PUBLIC_KEY;
        }
        $filtered = (string) apply_filters( 'wpdude_dc_fs_public_key', self::PUBLIC_KEY );
        return ( '' !== $filtered ? $filtered : self::PUBLIC_KEY );
    }

    /**
     * Detect placeholder credential values.
     */
    private function is_placeholder( string $value ) : bool {
        $placeholders = array(
            '00000',
            'pk_xxxxxxxx',
            'YOUR_ID',
            'YOUR_PUBLIC_KEY'
        );
        return in_array( $value, $placeholders, true );
    }

}
