<?php
namespace IntentDeep\VirtualFiles\Bootstrap;

class FreemiusManager {
    private string $pluginId;
    private string $pluginSlug;
    private array $messages;
    private const ERROR_PREFIX = 'Virtual Files';

    public function __construct(
        string $pluginId,
        string $pluginSlug,
        array $messages
    ) {
        $this->pluginId = $pluginId;
        $this->pluginSlug = $pluginSlug;
        $this->messages = $messages;
    }

    /**
     * Initialize Freemius customization
     */
    public function init(): void {
        try {
            $this->addFilters();
            $this->addUrlFilters();
            $this->addProActivationHooks();
        } catch (\Exception $e) {
            intentdeep_vf_log(sprintf("%s Freemius Error: %s", self::ERROR_PREFIX, $e->getMessage()));
        }
    }

    /**
     * Add Freemius filters
     */
    private function addFilters(): void {
        add_filter('fs_connect_message_' . $this->pluginSlug, [$this, 'customConnectMessage'], 10, 6);
        add_filter('fs_plugin_icon_' . $this->pluginSlug, [$this, 'customPluginIcon']);
    }

    /**
     * Add URL filters for Freemius
     */
    private function addUrlFilters(): void {
        $mainUrl = admin_url('edit.php?post_type=idep_virtual_file&page=intentdeep_vf_settings');

        $urlFilters = [
            'connect_url',
            'after_skip_url',
            'after_connect_url',
            'after_pending_connect_url'
        ];

        foreach ($urlFilters as $filter) {
            add_filter('fs_' . $filter . '_' . $this->pluginSlug, function() use ($mainUrl) {
                return $mainUrl;
            });
        }
    }

    /**
     * Add Pro activation hooks
     */
    private function addProActivationHooks(): void {
        // Hook into premium version activation
        add_action('fs_after_premium_version_activation_' . $this->pluginSlug, [$this, 'handleProActivation']);

        // Also hook into license activation to handle upgrades
        add_action('fs_after_license_change_' . $this->pluginSlug, [$this, 'handleLicenseChange'], 10, 2);
    }

    /**
     * Handle license changes - enable Pro features when license is activated
     */
    public function handleLicenseChange($prev_license, $new_license): void {
        try {
            // Check if the new license is premium
            if (function_exists('intentdeep_vf_fs') && intentdeep_vf_fs()->can_use_premium_code__premium_only()) {
                $this->handleProActivation();
            }
        } catch (\Exception $e) {
            intentdeep_vf_log(sprintf("%s License Change Error: %s", self::ERROR_PREFIX, $e->getMessage()));
        }
    }

    /**
     * Handle Pro activation - enable Pro features by default
     */
    public function handleProActivation(): void {
        try {
            // Get current settings
            $options = get_option('intentdeep_vf_settings', []);

            if (!is_array($options)) {
                $options = [];
            }

            // Enable all file extensions for Pro users
            $all_extensions = ['txt', 'md', 'json', 'xml', 'rss', 'csv', 'yml', 'yaml', 'log'];
            $options['allowed_extensions'] = $all_extensions;

            // Set default cache expiration if not already set
            if (!isset($options['cache_expiration'])) {
                $options['cache_expiration'] = 3600;
            }

            // Update options
            update_option('intentdeep_vf_settings', $options);

            // Log the activation if debug is enabled
            intentdeep_vf_log('Virtual Files: Pro version activated - enabled all file extensions');
        } catch (\Exception $e) {
            intentdeep_vf_log(sprintf("%s Pro Activation Error: %s", self::ERROR_PREFIX, $e->getMessage()));
        }
    }

    /**
     * Customize Freemius connect message
     */
    public function customConnectMessage(
        $message,
        $userFirstName,
        $productTitle,
        $userLogin,
        $siteLink,
        $freemiusLink
    ): string {
        $break = "<br><br>";
        
        return sprintf(
            $this->messages['connect']['title'],
            $userFirstName,
            $break
        );
    }

    /**
     * Customize plugin icon
     */
    public function customPluginIcon(): string {
        // Return the file system path to the SVG logo (not URL)
        $logo_path = INTENTDEEP_VF_PLUGIN_ROOT . 'admin/assets/logo.svg';

        // Check if the logo file exists
        if (file_exists($logo_path)) {
            return $logo_path;
        }

        // Fallback to empty (WordPress default dashicon)
        return '';
    }


}