<?php
// Quick Premium License Bypass for Mailster (no SDK changes required)
// Add to the beginning of includes/freemius.php
// Disable: set MAILSTER_BYPASS_LICENSE to false in mailster.php

// Disable Freemius dev mode early to prevent mock object triggering
if ( ! defined( 'WP_FS__DEV_MODE' ) ) {
    define( 'WP_FS__DEV_MODE', false );
}

// Define mock constants early to prevent Freemius SDK errors during partial loads (full list from search)
if ( ! defined( 'WP_FS__MOCK_PLAN_NAME' ) ) {
    define( 'WP_FS__MOCK_PLAN_NAME', 'professional' );
}
if ( ! defined( 'WP_FS__MOCK_PLAN_TITLE' ) ) {
    define( 'WP_FS__MOCK_PLAN_TITLE', 'Professional Plan' );
}

if ( defined( 'MAILSTER_BYPASS_LICENSE' ) && MAILSTER_BYPASS_LICENSE && ! defined( 'MAILSTER_BYPASS_DONE' ) ) {
    define( 'MAILSTER_BYPASS_DONE', true );

    if ( ! function_exists( 'is_blog_installed' ) || ! is_blog_installed() ) {
        return;
    }

    // Create global stub for $mailster_freemius (mocks full Freemius instance)
    global $mailster_freemius;
    $mailster_freemius = new class {
        // Core premium bypass methods (always premium, active license)
        public function is_paying() { return true; }
        public function is_free_plan() { return false; }
        public function has_features_enabled_license() { return true; }
        public function can_use_premium_code() { return true; }
        public function can_use_premium_code__premium_only() { return true; }
        public function has_active_valid_license( $check_expiration = true ) { return true; }
        public function is_registered() { return true; }
        public function is_trial() { return false; }
        public function is_trial_utilized() { return false; }
        public function has_api_connectivity() { return true; }

        // Mock license (prevents account page errors)
        private $_license;
        private function _get_mock_license() {
            if ( ! $this->_license ) {
                // Require entity if not loaded (defensive) — add check for class existence
                $entity_file = MAILSTER_DIR . 'includes/entities/class-fs-plugin-license.php';
                if ( file_exists( $entity_file ) && ! class_exists( 'FS_Plugin_License', false ) ) {
                    require_once $entity_file;
                }
                if ( class_exists( 'FS_Plugin_License' ) ) {
                    $this->_license = new FS_Plugin_License();
                    $this->_license->id = 1;
                    $this->_license->plan_id = 1; // Professional plan
                    $this->_license->secret_key = 'sk_premium_bypass_mailster_999';
                    $this->_license->quota = 0; // Unlimited
                    $this->_license->expiration = null; // Lifetime
                    $this->_license->is_active = true;
                    $this->_license->is_features_enabled = true;
                    $this->_license->is_expired = function() { return false; };
                    $this->_license->is_features_can = function() { return true; };
                } else {
                    // Fallback: simple stdClass if entity not loadable
                    $this->_license = (object) [
                        'id' => 1, 'plan_id' => 1, 'secret_key' => 'sk_premium_bypass_mailster_999',
                        'quota' => 0, 'expiration' => null, 'is_active' => true,
                        'is_features_enabled' => true, 'is_expired' => function() { return false; },
                        'is_features_can' => function() { return true; }
                    ];
                }
            }
            return $this->_license;
        }
        public function _get_license() { return $this->_get_mock_license(); }

        // Mock plans (shows "Professional Plan")
        private $_plans = array();
        private function _get_mock_plans() {
            if ( empty( $this->_plans ) ) {
                // Require entity if not loaded (defensive)
                $entity_file = MAILSTER_DIR . 'includes/entities/class-fs-plugin-plan.php';
                if ( file_exists( $entity_file ) && ! class_exists( 'FS_Plugin_Plan', false ) ) {
                    require_once $entity_file;
                }
                if ( class_exists( 'FS_Plugin_Plan' ) ) {
                    $mock_plan = new FS_Plugin_Plan();
                    $mock_plan->id = 1;
                    $mock_plan->name = WP_FS__MOCK_PLAN_NAME; // Use defined constant
                    $mock_plan->title = WP_FS__MOCK_PLAN_TITLE; // Use defined constant
                    $mock_plan->plugin_id = 123; // Mock plugin ID
                    $mock_plan->is_block_features = false;
                    $mock_plan->license_type = 'paid';
                    $mock_plan->pricing_id = 1;
                    $this->_plans[] = $mock_plan;
                } else {
                    // Fallback: simple stdClass
                    $this->_plans[] = (object) [
                        'id' => 1, 'name' => WP_FS__MOCK_PLAN_NAME,
                        'title' => WP_FS__MOCK_PLAN_TITLE, 'plugin_id' => 123,
                        'is_block_features' => false, 'license_type' => 'paid', 'pricing_id' => 1
                    ];
                }
            }
            return $this->_plans;
        }
        public function get_plan() { return $this->_get_mock_plans()[0]; }

        // Mock user (prevents "email not verified" or user-related errors)
        private $_user;
        private function _get_mock_user() {
            if ( ! $this->_user ) {
                // Require entity if not loaded
                $entity_file = MAILSTER_DIR . 'includes/entities/class-fs-user.php';
                if ( file_exists( $entity_file ) && ! class_exists( 'FS_User', false ) ) {
                    require_once $entity_file;
                }
                if ( class_exists( 'FS_User' ) ) {
                    $this->_user = new FS_User();
                    $this->_user->id = 1;
                    $this->_user->email = 'bypass@premium.local';
                    $this->_user->first = 'Premium';
                    $this->_user->last = 'User';
                    $this->_user->is_verified = true;
                    $this->_user->created = current_time( 'mysql' );
                    $this->_user->public_key = 'pk_076dbeeecec0cc5dac88ba6deff2a9ca';  // Realistic mock
                    $this->_user->secret_key = 'sk_8cde92b955d53d5684900b45e22a1aee';  // Realistic mock
                } else {
                    // Fallback: simple stdClass
                    $this->_user = (object) [
                        'id' => 1, 'email' => 'bypass@premium.local', 'first' => 'Premium',
                        'last' => 'User', 'is_verified' => true, 'created' => current_time( 'mysql' ),
                        'public_key' => 'pk_076dbeeecec0cc5dac88ba6deff2a9ca',
                        'secret_key' => 'sk_8cde92b955d53d5684900b45e22a1aee'
                    ];
                }
            }
            return $this->_user;
        }
        public function get_user() { return $this->_get_mock_user(); }

        // Mock site (prevents "No ID" or site-related errors; comprehensive properties)
        private $_site;
        private function _get_mock_site() {
            if ( ! $this->_site ) {
                // Require entity if not loaded
                $entity_file = MAILSTER_DIR . 'includes/entities/class-fs-site.php';
                if ( file_exists( $entity_file ) && ! class_exists( 'FS_Site', false ) ) {
                    require_once $entity_file;
                }
                if ( class_exists( 'FS_Site' ) ) {
                    $this->_site = new FS_Site();
                    $this->_site->id = 1;
                    $this->_site->site_id = 1;
                    $this->_site->blog_id = get_current_blog_id();
                    $this->_site->plugin_id = 123; // Mock plugin ID
                    $this->_site->license_id = 1;
                    $this->_site->plan_id = 1;
                    $this->_site->user_id = 1;
                    $this->_site->title = get_bloginfo( 'name' );
                    $this->_site->url = home_url();
                    $this->_site->version = MAILSTER_VERSION;
                    $this->_site->language = get_locale();
                    $this->_site->platform_version = get_bloginfo( 'version' );
                    $this->_site->sdk_version = '2.5.0'; // Mock SDK version
                    $this->_site->programming_language_version = phpversion();
                    $this->_site->is_premium = true;
                    $this->_site->is_active = true;
                    $this->_site->is_uninstalled = false;
                    $this->_site->public_key = 'pk_site_mock_abcdef123456';
                    $this->_site->secret_key = 'sk_site_mock_123456abcdef';
                    $this->_site->created = current_time( 'mysql' );
                } else {
                    // Fallback: simple stdClass
                    $this->_site = (object) [
                        'id' => 1, 'site_id' => 1, 'blog_id' => get_current_blog_id(),
                        'plugin_id' => 123, 'license_id' => 1, 'plan_id' => 1, 'user_id' => 1,
                        'title' => get_bloginfo( 'name' ), 'url' => home_url(), 'version' => MAILSTER_VERSION,
                        'language' => get_locale(), 'platform_version' => get_bloginfo( 'version' ),
                        'sdk_version' => '2.5.0', 'programming_language_version' => phpversion(),
                        'is_premium' => true, 'is_active' => true, 'is_uninstalled' => false,
                        'public_key' => 'pk_site_mock_abcdef123456', 'secret_key' => 'sk_site_mock_123456abcdef',
                        'created' => current_time( 'mysql' )
                    ];
                }
            }
            return $this->_site;
        }
        public function get_site() { return $this->_get_mock_site(); }

        // Block all API and sync (no external requests to Freemius)
        public function _sync_license() { return; }
        public function _sync_plugin_license() { return; }
        public function _fetch_payments() { return array(); }
        public function _fetch_billing() { return null; }
        public function ping() { return (object) array( 'api' => 'pong', 'timestamp' => current_time( 'mysql' ), 'is_active' => true ); }

        // Enhanced delegate for other methods (prevents breaking; blocks API calls)
        public function __call( $name, $arguments ) {
            // Block any API calls (e.g., call(), get(), post() - return bypassed response)
            if ( strpos( $name, 'call' ) === 0 || strpos( $name, 'get' ) === 0 || strpos( $name, 'post' ) === 0 || strpos( $name, 'ping' ) === 0 ) {
                return (object) array( 'success' => true, 'api' => 'bypassed' );
            }
            // Status checks (is_/has_ - true for premium)
            if ( strpos( $name, 'is_' ) === 0 || strpos( $name, 'has_' ) === 0 ) {
                return true;
            }
            // Fetch/Sync - empty data
            if ( strpos( $name, '_fetch' ) === 0 || strpos( $name, '_sync' ) === 0 ) {
                return array();
            }
            // Chainable methods (add_action/filter - return $this)
            if ( strpos( $name, 'add_' ) === 0 ) {
                return $this;
            }
            // Activation/Opt-in - disable
            if ( strpos( $name, 'opt_in' ) === 0 || strpos( $name, 'activation' ) === 0 ) {
                return false;
            }
            // Ensure _ensure_mock_objects is never called (extra safety)
            if ( $name === '_ensure_mock_objects' ) {
                return;
            }
            // Default - null to avoid errors
            return null;
        }

        // Disable activation/opt-in modes
        public function is_activation_mode() { return false; }
        public function is_activation_page() { return false; }
        public function override_i18n() { return; }

        // Public key for compatibility
        public function get_public_key() { return 'pk_mock_public_1234567890'; }
    };

    // Apply hooks to stub (hide Freemius elements, disable pricing/checkout)
    $mailster_freemius->add_action( 'hide_account_tabs', '__return_true' );
    $mailster_freemius->add_action( 'hide_freemius_powered_by', '__return_true' );
    $mailster_freemius->add_filter( 'checkout_url', function( $url ) { return ''; } ); // Disable checkout
    $mailster_freemius->add_filter( 'pricing_url', function( $url ) { return ''; } ); // Disable pricing
    $mailster_freemius->add_filter( 'connect_url', function( $url ) { return admin_url( 'admin.php?page=mailster' ); } ); // Redirect connect to main page
}

// Patched mailster_freemius() function (uses stub if enabled, else original)
function mailster_freemius() {
    global $mailster_freemius;

    if ( ! isset( $mailster_freemius ) ) {
        if ( defined( 'MAILSTER_BYPASS_LICENSE' ) && MAILSTER_BYPASS_LICENSE ) {
            // Bypass enabled: return pre-created stub (no SDK load)
            return $mailster_freemius; // Already set in the if-block above
        } else {
            // Original: Include Freemius SDK
            require_once MAILSTER_DIR . 'classes/license.class.php';
            $mailster_freemius = new MailsterLicense();
            if ( get_option( 'mailster_freemius' ) ) {
                $mailster_freemius->sdk();
            }
        }
    }

    return $mailster_freemius;
}

// Original hooks (only apply if not bypassed; but since stub handles them, they chain safely)
if ( ! ( defined( 'MAILSTER_BYPASS_LICENSE' ) && MAILSTER_BYPASS_LICENSE ) ) {
    // These will only run if bypass is off
    mailster_freemius()->add_filter( 'plugin_icon', 'mailster_freemius_custom_icon' );
    // ... (all other original hooks below remain unchanged)
}

mailster_freemius()->add_filter( 'plugin_icon', 'mailster_freemius_custom_icon' );
function mailster_freemius_custom_icon() {
    return MAILSTER_DIR . 'assets/img/opt-in.png';
}

add_action( 'load-toplevel_page_mailster', 'mailster_freemius_load_page' );
function mailster_freemius_load_page() {
    // Skip Freemius CSS if bypassed
    if ( defined( 'MAILSTER_BYPASS_LICENSE' ) && MAILSTER_BYPASS_LICENSE ) {
        return;
    }
    $suffix = SCRIPT_DEBUG ? '' : '.min';
    wp_enqueue_style( 'freemius-style', MAILSTER_URI . 'assets/css/freemius-style' . $suffix . '.css', array(), MAILSTER_VERSION );
}

mailster_freemius()->add_action( 'after_account_connection', 'mailster_freemius_install' );
function mailster_freemius_install() {
    mailster()->install();
}

mailster_freemius()->add_action( 'after_uninstall', 'mailster_on_uninstall' );

mailster_freemius()->add_action( 'hide_account_tabs', '__return_true' );
mailster_freemius()->add_action( 'hide_freemius_powered_by', '__return_true' );

mailster_freemius()->add_filter( 'license_key', 'mailster_legacy_license_key' );
function mailster_legacy_license_key( $key ) {
    $key = trim( $key );

    // Handle an Envato License
    if ( preg_match( '/[a-f0-9]{8}\-[a-f0-9]{4}\-4[a-f0-9]{3}\-(8|9|a|b)[a-f0-9]{3}\-[a-f0-9]{12}/', $key ) ) {
        $is_marketing_allowed = null;
        $email                = null;

        if ( isset( $_POST['is_marketing_allowed'] ) ) {
            $is_marketing_allowed = $_POST['is_marketing_allowed'] === 'true';
        }

        if ( isset( $_POST['fs_email'] ) ) {
            $email = $_POST['fs_email'];
        }

        $response = mailster( 'convert' )->convert( $email, $key, $is_marketing_allowed );

        if ( is_wp_error( $response ) ) {
            set_transient( 'mailster_last_legacy_key_error', $response, 10 );
        } else {
            $key = $response->data->secret_key;
        }
    }

    return $key;
}

mailster_freemius()->add_action( 'connect/after_license_input', 'mailster_add_link_for_envato' );
function mailster_add_link_for_envato() {
    // Skip if bypassed (no connect page needed)
    if ( defined( 'MAILSTER_BYPASS_LICENSE' ) && MAILSTER_BYPASS_LICENSE ) {
        return;
    }

    $is_envato = get_option( 'mailster_envato' );

    $email = get_option( 'mailster_email' );
    if ( ! $email ) {
        $user  = wp_get_current_user();
        $email = $user->user_email;
    }

    ?>
    <script>
        jQuery && jQuery(document).ready(function ($) {
            var is_envato = <?php echo $is_envato ? 'true' : 'false'; ?>;
            $('#fs_license_key').on('change', function(){
                if (is_envato || this.value.match(/[a-f0-9]{8}\-[a-f0-9]{4}\-4[a-f0-9]{3}\-(8|9|a|b)[a-f0-9]{3}\-[a-f0-9]{12}/)) {
                    $('.is-envato').show();
                    $('.show-license-resend-modal').hide();
                } else {
                    $('.is-envato').hide();
                    $('.show-license-resend-modal').show();
                }
            }).trigger('change');
            is_envato && $('#fs_license_key').attr('placeholder', '<?php esc_html_e( 'Envato Purchase Code', 'mailster' ); ?>' )
            $('#fs_email').on('change', function(){
                $.ajaxSetup({data:{fs_email:$(this).val()}});
            }).trigger('change');

        });
    </script>
    <style>.is-envato{display: none;}#fs_connect .fs-license-key-container{width: 330px}</style>
    <div class="fs-license-key-container is-envato">
        <span><?php printf( esc_html__( 'Please enter the email address for your %s', 'mailster' ), '<a href="' . mailster_url( 'https://mailster.co/account/' ) . '" target="_blank">' . esc_html__( 'Freemius Account', 'mailster' ) . '</a>' ); ?></span>
        <input id="fs_email" name="fs_email" type="email" required placeholder="<?php esc_attr_e( 'Email address', 'mailster' ); ?>" value="<?php echo esc_attr( $email ); ?>">
        <span>(<?php esc_html_e( 'will be used if no account is assigned to your license', 'mailster' ); ?>)</span>
    </div>
    <div class="fs-license-key-container is-envato">
        <a href="<?php echo mailster_url( 'https://kb.mailster.co/where-is-my-purchasecode/' ); ?>" target="_blank"><?php esc_html_e( "Can't find your license key?", 'mailster' ); ?></a>
        <?php if ( get_option( 'mailster_setup' ) ) : ?>
        <a class="alignright" href="<?php echo esc_url( add_query_arg( 'mailster_use_freemius', 0 ) ); ?>"><?php esc_html_e( 'Back to Migration', 'mailster' ); ?></a>
        <?php endif; ?>
    </div>
    <?php
}

mailster_freemius()->add_filter( 'permission_list', 'mailster_update_permission' );
function mailster_update_permission( $permissions ) {

    $permissions[] = array(
        'id'         => 'helpscout',
        'icon-class' => 'dashicons dashicons-sos',
        'tooltip'    => esc_html__( 'If you agree third-party scripts are loaded to provide you with help.', 'mailster' ),
        'label'      => 'Help Scout (' . esc_html__( 'optional', 'mailster' ) . ')',
        'desc'       => esc_html__( 'Loading Help Scout\'s beacon for easy support access', 'mailster' ),
        'optional'   => true,
        'priority'   => 20,
    );

    $list = wp_list_pluck( $permissions, 'id' );
    if ( $key = array_search( 'extensions', $list ) ) {
        $permissions[ $key ]['default'] = true;
    }

    return $permissions;
}

mailster_freemius()->add_filter( 'opt_in_error_message', 'mailster_freemius_opt_in_error_message' );
function mailster_freemius_opt_in_error_message( $error ) {

    $last_error = get_transient( 'mailster_last_legacy_key_error' );
    if ( $last_error ) {
        $error = $last_error->get_error_message();
        delete_transient( 'mailster_last_legacy_key_error' );
    }
    return $error;
}

// Change length of license keys to accept Envato (36 chars + whitespace)
mailster_freemius()->add_filter( 'license_key_maxlength', 'mailster_license_key_maxlength' );
function mailster_license_key_maxlength( $length ) {
    return 40;
}

mailster_freemius()->add_filter( 'checkout_url', 'mailster_freemius_checkout_url' );
function mailster_freemius_checkout_url( $url ) {
    // If bypassed, always return empty (no checkout)
    if ( defined( 'MAILSTER_BYPASS_LICENSE' ) && MAILSTER_BYPASS_LICENSE ) {
        return '';
    }

    if ( empty( $url ) ) {
        return $url;
    }

    if ( mailster_freemius()->is_whitelabeled() ) {
        return mailster_url( 'https://mailster.co/go/buy' );
    }

    return add_query_arg(
        array(
            'page'          => 'mailster-pricing',
            'checkout'      => 'true',
            'plan_id'       => 22867,
            'billing_cycle' => 'annual',
            'post_type'     => 'newsletter',
        ),
        admin_url( 'edit.php' )
    );
}

mailster_freemius()->add_filter( 'pricing_url', 'mailster_freemius_pricing_url' );
function mailster_freemius_pricing_url( $url ) {
    // If bypassed, always return empty (no pricing)
    if ( defined( 'MAILSTER_BYPASS_LICENSE' ) && MAILSTER_BYPASS_LICENSE ) {
        return '';
    }

    if ( empty( $url ) ) {
        return $url;
    }

    if ( mailster_freemius()->is_whitelabeled() ) {
        return mailster_url( 'https://mailster.co/go/buy' );
    }

    $url = add_query_arg( array( 'id' => 'mailster-plugin' ), $url );

    $utms = preg_grep( '/^utm_/', array_keys( $_GET ) );
    $utms = array_intersect_key( $_GET, array_flip( $utms ) );
    if ( $utms ) {
        $url = add_query_arg( $utms, $url );
    }

    return $url;
}

mailster_freemius()->add_action( 'after_license_change', 'mailster_freemius_after_license_change_handler', 10, 2 );
function mailster_freemius_after_license_change_handler( $plan_change_desc, FS_Plugin_Plan $plan ) {

    if ( 'changed' !== $plan_change_desc ) {
        return;
    }

    mailster_remove_notice( 'mailster-workflow-limit-reached' );
    mailster_remove_notice( 'mailster-notice-legacy_promo' );

    return;
}

function mailster_freemius_upgrade_license( $args = array(), $label = null, $class = 'button button-primary' ) {
    // If bypassed, return empty button (no upgrade needed)
    if ( defined( 'MAILSTER_BYPASS_LICENSE' ) && MAILSTER_BYPASS_LICENSE ) {
        return '<span class="' . esc_attr( $class ) . '">Premium Activated</span>';
    }

    $license = mailster_freemius()->_get_license();

    $args = wp_parse_args(
        $args,
        array( 'license_key' => $license->secret_key )
    );
    return mailster_freemius_checkout_button( $args, $label, $class );
}

function mailster_freemius_checkout_button( $args = array(), $label = null, $class = 'button button-primary' ) {
    // If bypassed, return empty (no checkout)
    if ( defined( 'MAILSTER_BYPASS_LICENSE' ) && MAILSTER_BYPASS_LICENSE ) {
        return '';
    }

    $public_key = mailster_freemius()->get_public_key();
    $license    = mailster_freemius()->_get_license();

    $is_ajax = defined( 'DOING_AJAX' ) && DOING_AJAX;

    // TODO: check if coupon code works
    $popup = false;

    if ( ! $label ) {
        $label = __( 'Buy License', 'mailster' );
    }

    $default = array(
        'plugin_id'  => $license->plugin_id,
        'public_key' => $public_key,
    );

    $args = wp_parse_args( $args, $default );

    $args = apply_filters( 'mailster_freemius_args', $args );

    $button_id = 'FS-buy-button-' . uniqid();

    $url_args = array_filter(
        $args,
        function ( $key ) {
            return ! in_array( $key, array( 'public_key', 'plugin_id', 'sandbox', 'dl_endpoint', 'license_key' ) );
        },
        ARRAY_FILTER_USE_KEY
    );

    $return = ' <a href="' . add_query_arg( $url_args, mailster_freemius()->checkout_url() ) . '" class="' . esc_attr( $class ) . '" id="' . esc_attr( $button_id ) . '">' . esc_html( $label ) . '</a>';

    if ( $popup ) {

        wp_enqueue_script( 'freemius-button-checkout', 'https://checkout.freemius.com/js/v1/', array(), 'v1', true );
        wp_add_inline_script(
            'freemius-button-checkout',
            'document.getElementById("' . esc_attr( $button_id ) . '").addEventListener("click", (e) => {
        e.preventDefault(); new FS.Checkout(' . json_encode( $args ) . ').open({
            track: function(event, data){console.warn(event, data);},
            purchaseCompleted: function(data){console.warn("purchaseCompleted", data);},
            cancel: function(data){console.warn("cancel", data);},
            success: function(data){console.warn("success", data);window.location = location.href + (location.href.includes("?") ? "&refresh_license=1" : "?refresh_license=1")},
        });});'
        );
        // append the script on ajax requests
        if ( $is_ajax ) {
            ob_start();
            wp_print_scripts( 'freemius-button-checkout' );
            $return .= ob_get_clean();

        }
    }

    return $return;
}