<?php
/**
 * License Page (Freemius Integration)
 * 
 * Soft activation UI - plugin works without activation.
 * Activation only enables: premium features + priority support.
 */

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

// Security check
if ( ! current_user_can( 'manage_options' ) ) {
    wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'signwpdf-pdf-sign-fill' ) );
}

// Get Freemius state
$fs = function_exists( 'swpdf_fs' ) ? swpdf_fs() : null;
$is_freemius_loaded = ( $fs && is_object( $fs ) && method_exists( $fs, 'is_premium' ) );

// License status (single-plugin model: check if user has paid plan, not separate premium version)
$is_premium = $is_freemius_loaded && $fs->is_premium();
$is_trial = $is_freemius_loaded && method_exists( $fs, 'is_trial' ) && $fs->is_trial();
$is_free_plan = $is_freemius_loaded && method_exists( $fs, 'is_free_plan' ) && $fs->is_free_plan();
$is_registered = $is_freemius_loaded && method_exists( $fs, 'is_registered' ) && $fs->is_registered();
$has_paid_plan = $is_freemius_loaded && method_exists( $fs, 'is_paying' ) && $fs->is_paying();
// Consider activated if: has paid plan, trial, or premium (covers all license types)
$is_activated = $has_paid_plan || $is_trial || $is_premium;

// Build Freemius URLs safely
$upgrade_url = ( $fs && method_exists( $fs, 'get_upgrade_url' ) )
    ? $fs->get_upgrade_url()
    : 'https://dashboard.freemius.com/';

/**
 * Helper: Check if URL is plain plugin page without Freemius action params (loop)
 * 
 * @param string $url URL to check
 * @return bool True if it's a plain plugin page (loop), false if it has fs_action or other Freemius params
 */
function swpdf_is_plain_plugin_page_url( $url ) {
    if ( empty( $url ) ) {
        return true;
    }
    
    $parsed = wp_parse_url( $url );
    if ( empty( $parsed['query'] ) ) {
        return false;
    }
    
    parse_str( $parsed['query'], $query_params );
    
    // Base slug must be our page
    if ( ( $query_params['page'] ?? '' ) !== 'signwpdf-pdf-sign-fill' ) {
        return false;
    }
    
    // If it has fs_action or any fs_* args, it is NOT a plain loop
    foreach ( $query_params as $key => $value ) {
        if ( $key === 'fs_action' || strpos( $key, 'fs_' ) === 0 || strpos( $key, 'freemius_' ) === 0 ) {
            return false; // Has Freemius params, not a loop
        }
    }
    
    // page=pdf-sign-fill only, no fs args -> plain plugin page (loop)
    return true;
}

// Determine Manage License URL and label
$sdk_too_old_warning = '';

if ( $is_registered && $fs && method_exists( $fs, 'get_account_url' ) ) {
    // Registered: go to account page where license key can be entered
    $manage_license_url = $fs->get_account_url();
    $manage_label = __( 'Manage License', 'signwpdf-pdf-sign-fill' );
} else {
    // Not registered: show Freemius connect/opt-in screen, NOT plugin main page
    $manage_license_url = '';
    
    // Only warn if Freemius SDK is completely missing or unusable
    if ( ! $is_freemius_loaded ) {
        $sdk_too_old_warning = __( 'Freemius SDK is not loaded. Please reinstall the plugin to enable license activation.', 'signwpdf-pdf-sign-fill' );
    }
    
    // Try get_connect_url first
    if ( $fs && method_exists( $fs, 'get_connect_url' ) ) {
        $connect_url = $fs->get_connect_url();
        if ( ! swpdf_is_plain_plugin_page_url( $connect_url ) ) {
            $manage_license_url = $connect_url;
        }
    }
    
    // Fallback to get_activation_url if not already set
    if ( empty( $manage_license_url ) && $fs && method_exists( $fs, 'get_activation_url' ) ) {
        $activation_url = $fs->get_activation_url();
        if ( ! swpdf_is_plain_plugin_page_url( $activation_url ) ) {
            $manage_license_url = $activation_url;
        }
    }
    
    // Final fallback to account URL or upgrade URL
    if ( empty( $manage_license_url ) ) {
        if ( $fs && method_exists( $fs, 'get_account_url' ) ) {
            $manage_license_url = $fs->get_account_url();
        } else {
            $manage_license_url = $upgrade_url;
        }
    }
    
    $manage_label = __( 'Connect / Activate', 'signwpdf-pdf-sign-fill' );
}

// Site info
$site_url = home_url();
$site_domain = wp_parse_url( $site_url, PHP_URL_HOST );
$plugin_version = defined( 'SWPDF_VERSION' ) ? SWPDF_VERSION : '1.0.0';

// Get diagnostics
$debug_info = "Plugin Version: {$plugin_version}\n";
$debug_info .= "WordPress Version: " . get_bloginfo( 'version' ) . "\n";
$debug_info .= "PHP Version: " . phpversion() . "\n";
$debug_info .= "Site URL: {$site_url}\n";
$debug_info .= "Multisite: " . ( is_multisite() ? 'Yes' : 'No' ) . "\n";
$debug_info .= "SSL: " . ( is_ssl() ? 'Yes' : 'No' ) . "\n";
if ( $is_freemius_loaded ) {
    $debug_info .= "License Status: " . ( ( $has_paid_plan || $is_premium ) ? 'Premium Active' : ( $is_trial ? 'Trial' : 'Free Plan' ) ) . "\n";
    $debug_info .= "Premium Features: " . ( swpdf_is_premium_active() ? 'Yes' : 'No' ) . "\n";
    $debug_info .= "Premium Support: " . ( swpdf_premium_support_enabled() ? 'Yes' : 'No' ) . "\n";
} else {
    $debug_info .= "License Status: Freemius SDK not loaded\n";
    $debug_info .= "Premium Features: No\n";
    $debug_info .= "Premium Support: No\n";
}
?>

<div class="wrap psf-license-wrap">
    <h1><?php esc_html_e( 'signwpdf PDF Sign & Fill — License', 'signwpdf-pdf-sign-fill' ); ?></h1>
    
    <!-- Important Notice -->
    <div class="notice notice-info" style="margin: 20px 0;">
        <p>
            <strong><?php esc_html_e( '✓ Activation is optional.', 'signwpdf-pdf-sign-fill' ); ?></strong>
            <?php esc_html_e( 'This plugin works fully without activation. Free version updates are delivered automatically through WordPress.org. Activation only enables premium features and priority support.', 'signwpdf-pdf-sign-fill' ); ?>
        </p>
    </div>
    
    <?php if ( ! $is_freemius_loaded ) : ?>
    <!-- Freemius SDK Not Loaded Warning -->
    <div class="notice notice-warning" style="margin: 20px 0;">
        <p>
            <strong><?php esc_html_e( 'License System Not Available', 'signwpdf-pdf-sign-fill' ); ?></strong><br>
            <?php esc_html_e( 'The Freemius SDK is not installed. Please upload the Freemius SDK to enable license management. The plugin will continue to work normally without it.', 'signwpdf-pdf-sign-fill' ); ?>
        </p>
        <p>
            <strong><?php esc_html_e( 'Installation:', 'signwpdf-pdf-sign-fill' ); ?></strong>
            <?php esc_html_e( 'Upload the Freemius SDK folder to:', 'signwpdf-pdf-sign-fill' ); ?>
            <code>/wp-content/plugins/pdf-sign-fill/freemius/</code>
        </p>
    </div>
    <?php endif; ?>
    
    <!-- License Status Card -->
    <div class="psf-license-card">
        <div class="psf-license-header">
            <h2><?php esc_html_e( 'License Status', 'signwpdf-pdf-sign-fill' ); ?></h2>
            <span class="psf-status-badge <?php echo esc_attr( $is_activated ? 'active' : 'none' ); ?>">
                <?php 
                if ( $has_paid_plan || $is_premium ) {
                    esc_html_e( 'Premium Active', 'signwpdf-pdf-sign-fill' );
                } elseif ( $is_trial ) {
                    esc_html_e( 'Trial Active', 'signwpdf-pdf-sign-fill' );
                } else {
                    esc_html_e( 'Free Plan', 'signwpdf-pdf-sign-fill' );
                }
                ?>
            </span>
        </div>
        
        <div class="psf-license-body">
            <?php if ( $is_freemius_loaded ) : ?>
                
                <?php if ( ! $is_activated ) : ?>
                    <!-- Not Activated View -->
                    <p style="margin: 15px 0;">
                        <?php esc_html_e( 'You are currently using the free version of signwpdf PDF Sign & Fill. All core features are available.', 'signwpdf-pdf-sign-fill' ); ?>
                    </p>
                    <p>
                        <?php esc_html_e( 'Upgrade to premium to unlock:', 'signwpdf-pdf-sign-fill' ); ?>
                    </p>
                    <ul style="margin: 10px 0 20px 20px; list-style: disc;">
                        <li><?php esc_html_e( 'Priority support with faster response times', 'signwpdf-pdf-sign-fill' ); ?></li>
                        <li><?php esc_html_e( 'Access to premium-only features', 'signwpdf-pdf-sign-fill' ); ?></li>
                    </ul>
                    <p class="description">
                        <?php esc_html_e( 'Note: Free version updates are always delivered automatically through WordPress.org — no license required.', 'signwpdf-pdf-sign-fill' ); ?>
                    </p>
                    
                    <?php if ( ! empty( $sdk_too_old_warning ) ) : ?>
                        <div class="notice notice-error inline" style="margin: 15px 0; padding: 10px;">
                            <p><strong><?php esc_html_e( 'SDK Update Required:', 'signwpdf-pdf-sign-fill' ); ?></strong> <?php echo esc_html( $sdk_too_old_warning ); ?></p>
                        </div>
                    <?php endif; ?>
                    
                    <p class="submit">
                        <?php if ( ! empty( $upgrade_url ) ) : ?>
                            <a href="<?php echo esc_url( $upgrade_url ); ?>" class="button button-primary button-large">
                                <?php esc_html_e( 'Upgrade to Premium', 'signwpdf-pdf-sign-fill' ); ?>
                            </a>
                        <?php endif; ?>
                        <?php if ( ! empty( $manage_license_url ) ) : ?>
                            <a href="<?php echo esc_url( $manage_license_url ); ?>" class="button button-secondary">
                                <?php echo esc_html( $manage_label ); ?>
                            </a>
                        <?php endif; ?>
                    </p>
                    
                <?php else : ?>
                    <!-- Activated View -->
                    <table class="form-table psf-status-table" role="presentation">
                        <tbody>
                            <tr>
                                <th scope="row"><?php esc_html_e( 'Plan', 'signwpdf-pdf-sign-fill' ); ?></th>
                                <td>
                                    <strong>
                                        <?php 
                                        if ( $has_paid_plan || $is_premium ) {
                                            esc_html_e( 'Premium', 'signwpdf-pdf-sign-fill' );
                                        } elseif ( $is_trial ) {
                                            esc_html_e( 'Trial', 'signwpdf-pdf-sign-fill' );
                                        }
                                        ?>
                                    </strong>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e( 'Activated Domain', 'signwpdf-pdf-sign-fill' ); ?></th>
                                <td><code><?php echo esc_html( $site_domain ); ?></code></td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e( 'Premium Features', 'signwpdf-pdf-sign-fill' ); ?></th>
                                <td>
                                    <span class="psf-status-ok">
                                        <span class="dashicons dashicons-yes-alt"></span>
                                        <?php esc_html_e( 'Enabled', 'signwpdf-pdf-sign-fill' ); ?>
                                    </span>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e( 'Premium Support', 'signwpdf-pdf-sign-fill' ); ?></th>
                                <td>
                                    <span class="psf-status-ok">
                                        <span class="dashicons dashicons-yes-alt"></span>
                                        <?php esc_html_e( 'Enabled', 'signwpdf-pdf-sign-fill' ); ?>
                                    </span>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                    
                    <p class="submit">
                        <?php if ( ! empty( $manage_license_url ) ) : ?>
                            <a href="<?php echo esc_url( $manage_license_url ); ?>" class="button button-primary">
                                <span class="dashicons dashicons-admin-users" style="margin-top: 3px;"></span>
                                <?php esc_html_e( 'Manage License & Account', 'signwpdf-pdf-sign-fill' ); ?>
                            </a>
                        <?php endif; ?>
                    </p>
                <?php endif; ?>
                
            <?php else : ?>
                <!-- Freemius Not Loaded -->
                <p style="margin: 15px 0; color: #d97706;">
                    <?php esc_html_e( 'License management is not available because the Freemius SDK is not installed.', 'signwpdf-pdf-sign-fill' ); ?>
                </p>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- This Site Info Card -->
    <div class="psf-license-card" style="margin-top: 20px;">
        <div class="psf-license-header">
            <h2><?php esc_html_e( 'Site Information', 'signwpdf-pdf-sign-fill' ); ?></h2>
        </div>
        <div class="psf-license-body">
            <table class="form-table" role="presentation">
                <tbody>
                    <tr>
                        <th scope="row"><?php esc_html_e( 'Site URL', 'signwpdf-pdf-sign-fill' ); ?></th>
                        <td>
                            <code><?php echo esc_html( $site_url ); ?></code>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e( 'Plugin Version', 'signwpdf-pdf-sign-fill' ); ?></th>
                        <td><code><?php echo esc_html( $plugin_version ); ?></code></td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e( 'WordPress Version', 'signwpdf-pdf-sign-fill' ); ?></th>
                        <td><code><?php echo esc_html( get_bloginfo( 'version' ) ); ?></code></td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e( 'PHP Version', 'signwpdf-pdf-sign-fill' ); ?></th>
                        <td><code><?php echo esc_html( phpversion() ); ?></code></td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    
    <!-- Diagnostics Panel -->
    <div class="psf-license-card" style="margin-top: 20px;">
        <details class="psf-diagnostics-details">
            <summary class="psf-license-header" style="cursor: pointer;">
                <h2 style="display: inline;"><?php esc_html_e( 'Support Diagnostics', 'signwpdf-pdf-sign-fill' ); ?></h2>
                <span class="dashicons dashicons-arrow-down-alt2" style="float: right; margin-top: 2px;"></span>
            </summary>
            <div class="psf-license-body">
                <p class="description" style="margin-bottom: 15px;">
                    <?php esc_html_e( 'Copy this information when requesting support.', 'signwpdf-pdf-sign-fill' ); ?>
                </p>
                <textarea id="psf-debug-info" readonly class="large-text code" rows="12"><?php echo esc_textarea( trim( $debug_info ) ); ?></textarea>
                <p style="margin-top: 15px;">
                    <button type="button" class="button button-secondary" id="psf-copy-diagnostics">
                        <span class="dashicons dashicons-clipboard" style="margin-top: 3px;"></span>
                        <?php esc_html_e( 'Copy Diagnostics', 'signwpdf-pdf-sign-fill' ); ?>
                    </button>
                </p>
            </div>
        </details>
    </div>
    
</div>
