<?php
/**
 * License gate — thin adapter on top of the Freemius SDK.
 *
 * Why Freemius and not our own license server? Freemius handles
 * licensing, license-key validation, automatic updates, customer billing,
 * EU VAT/MOSS compliance, refunds and the affiliate program — all of that
 * comes for free with the SDK. We just have to ask the SDK whether the
 * current install is paying.
 *
 * If the SDK isn't loaded yet (because the user hasn't completed the
 * Freemius account setup or the SDK files aren't in place), this class
 * falls back to "free tier — Pro modules off" gracefully so the rest of
 * the plugin keeps working.
 *
 * See FREEMIUS_SETUP.md for the one-time configuration.
 *
 * @package Brainwerk SEO Suite
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Seoforge_License {

    public static function register( Seoforge_Loader $loader ) {
        // No cron of our own — Freemius runs its own. This only wires the
        // audit-log listener for license/plan changes (below).
        $fs = self::fs();
        if ( $fs && method_exists( $fs, 'add_action' ) ) {
            $fs->add_action( 'after_license_change', array( __CLASS__, 'audit_license_change' ) );
        }
    }

    /** Fired by the Freemius SDK whenever the license/plan state changes. */
    public static function audit_license_change() {
        if ( class_exists( 'Seoforge_Audit' ) ) {
            Seoforge_Audit::log( 'license_activated', array(
                'object_type' => 'license',
                'summary'     => sprintf( 'License tier is now "%s".', self::tier() ),
            ) );
        }
    }

    /** True when the current install has an active paid plan. */
    public static function is_pro() {
        // Self-host override: unlock Pro on your own site without the Freemius
        // licensing flow (e.g. an internal / school install of your own plugin).
        // Add `define( 'SEOFORGE_FORCE_PRO', true );` to wp-config.php.
        if ( defined( 'SEOFORGE_FORCE_PRO' ) && SEOFORGE_FORCE_PRO ) {
            return true;
        }
        $fs = self::fs();
        if ( ! $fs ) {
            return false;
        }
        // `is_paying()` is true for any active paid license regardless of
        // whether we're running the Free or Premium build. The
        // `__premium_only` variant is intentionally false in the Free build
        // (that's the suffix's whole purpose), so it's the wrong gate here.
        return (bool) $fs->is_paying();
    }

    /** Small inline "Pro" badge markup for use next to headings/labels. */
    public static function pro_badge() {
        return '<span class="seoforge-badge seoforge-badge-pro">' . esc_html__( 'Pro', 'brainwerk-seo-suite' ) . '</span>';
    }

    /** Returns the active plan name (lowercased) or 'free'. */
    public static function tier() {
        if ( defined( 'SEOFORGE_FORCE_PRO' ) && SEOFORGE_FORCE_PRO ) {
            return 'pro';
        }
        $fs = self::fs();
        if ( ! $fs || ! $fs->is_paying() ) {
            return 'free';
        }
        $plan = $fs->get_plan();
        if ( $plan && isset( $plan->name ) ) {
            return strtolower( $plan->name );
        }
        return 'starter';
    }

    /**
     * Lightweight read-only state for the License view.
     */
    public static function get() {
        $fs   = self::fs();
        $tier = self::tier();
        $base = array(
            'tier'         => $tier,
            'status'       => $fs && $fs->is_paying() ? 'active' : 'inactive',
            'is_configured'=> (bool) $fs,
            'key'          => '',
            'sites_used'   => 0,
            'sites_max'    => 0,
            'expires_at'   => '',
            'last_checked' => '',
            'account_url'  => '',
            'pricing_url'  => 'https://seoforge.brainwerk.at/',
        );
        if ( ! $fs ) {
            return $base;
        }
        try {
            $license = $fs->_get_license();
            if ( $license ) {
                $base['key']        = isset( $license->secret_key ) ? (string) $license->secret_key : '';
                $base['sites_used'] = isset( $license->activated ) ? (int) $license->activated : 0;
                $base['sites_max']  = isset( $license->quota ) ? (int) $license->quota : 0;
                $base['expires_at'] = isset( $license->expiration ) ? (string) $license->expiration : '';
            }
            $base['account_url'] = $fs->get_account_url();
            $base['pricing_url'] = $fs->get_upgrade_url();
        } catch ( \Throwable $e ) {
            // Freemius API can be moody during boot — never fatal here.
        }
        return $base;
    }

    /** Resolve the global Freemius instance for Brainwerk SEO Suite. */
    private static function fs() {
        if ( function_exists( 'seoforge_fs' ) ) {
            try {
                return seoforge_fs();
            } catch ( \Throwable $e ) {
                return null;
            }
        }
        return null;
    }
}
