<?php

use MemberPress\GroundLevel\Mothership\Manager\AddonsManager;

if (!defined('ABSPATH')) {
    die('You are not allowed to call this page directly.');
}

class MeprAddonsCtrl extends MeprBaseCtrl
{
    /**
     * Loads the hooks.
     *
     * @return void
     */
    public function load_hooks()
    {
        add_action('admin_enqueue_scripts', [$this, 'enqueue_scripts']);
        add_filter('wp_mail_smtp_core_get_upgrade_link', [$this, 'set_smtp_affiliate_link']);
        add_filter('monsterinsights_shareasale_id', [$this, 'set_monsterinsights_shareasale_id']);
        add_action('wp_ajax_mepr_set_affiliate_install_flag', [$this, 'ajax_set_affiliate_install_flag']);
    }

    /**
     * Routes the request.
     *
     * @return void
     */
    public static function route()
    {
        $active_tab      = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'addons';
        $registered_tabs = self::get_registered_tabs();
        $addons_manager  = memberpress()->container()->get(AddonsManager::class);

        MeprView::render('/admin/addons/ui', compact('active_tab', 'registered_tabs', 'addons_manager'));
    }

    /**
     * Get registered tabs for the add-ons page.
     *
     * @return array Array of registered tabs.
     */
    public static function get_registered_tabs()
    {
        // Default add-ons tab.
        $tabs = [
            'addons' => [
                'id'         => 'addons',
                'label'      => __('Add-ons', 'memberpress'),
                'capability' => 'install_plugins',
                'priority'   => 10,
                'callback'   => null, // Rendered in the main view.
            ],
        ];

        /**
         * Filter to register custom tabs for the add-ons page.
         *
         * Allows brands/plugins to register tabs in a structured way.
         *
         * @param array $tabs Array of tab configurations.
         *
         * Each tab should have:
         * - id (string, required): Unique tab identifier
         * - label (string, required): Tab label (translated)
         * - capability (string, optional): Required capability, default 'manage_options'
         * - priority (int, optional): Display order, default 10
         * - callback (callable, optional): Function to render tab content
         */
        $registered = apply_filters('mepr_addons_registered_tabs', []);

        // Validate and merge registered tabs.
        foreach ($registered as $tab) {
            if (!is_array($tab) || !isset($tab['id'], $tab['label'])) {
                continue;
            }

            $tab_id = sanitize_key($tab['id']);

            $tabs[$tab_id] = [
                'id'         => $tab_id,
                'label'      => $tab['label'],
                'capability' => isset($tab['capability']) ? $tab['capability'] : 'manage_options',
                'priority'   => isset($tab['priority']) ? absint($tab['priority']) : 10,
                'callback'   => isset($tab['callback']) && is_callable($tab['callback']) ? $tab['callback'] : null,
            ];
        }

        // Sort by priority.
        uasort($tabs, function ($a, $b) {
            return $a['priority'] - $b['priority'];
        });

        return $tabs;
    }

    /**
     * Enqueues the scripts.
     *
     * @param  string $hook The hook.
     * @return void
     */
    public function enqueue_scripts($hook)
    {
        if (preg_match('/_page_memberpress-addons$/', $hook)) {
            // Get active tab for conditional enqueuing.
            $active_tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'addons';

            /**
             * Allow brands to enqueue their own scripts and styles for custom tabs.
             *
             * @param string $hook       The current admin page hook.
             * @param string $active_tab The currently active tab.
             */
            do_action('mepr_addons_enqueue_scripts', $hook, $active_tab);
        }

        if (preg_match('/_page_memberpress-affiliates$/', $hook)) {
            wp_enqueue_style('mepr-sister-plugin-css', MEPR_CSS_URL . '/admin-sister-plugin.css', [], MEPR_VERSION);
        }
    }

    /**
     * Returns current plugin info.
     *
     * @param  string $main_file The main file.
     * @return string
     */
    public function curr_plugin_info($main_file)
    {
        static $curr_plugins;

        if (!isset($curr_plugins)) {
            if (!function_exists('get_plugins')) {
                require_once(ABSPATH . '/wp-admin/includes/plugin.php');
            }

            $curr_plugins = get_plugins();
            wp_cache_delete('plugins', 'plugins');
        }

        if (isset($curr_plugins[$main_file])) {
            return $curr_plugins[$main_file];
        }

        return '';
    }

    /**
     * Sets Monsterinsights shareasale id.
     *
     * @param  string $id The id.
     * @return string
     */
    public function set_monsterinsights_shareasale_id($id)
    {
        if (get_option('memberpress_installed_monsterinsights')) {
            $id = '409876';
        }

        return $id;
    }

    /**
     * Sets SMTP affiliate link.
     *
     * @param  string $link The link.
     * @return string
     */
    public function set_smtp_affiliate_link($link)
    {
        if (get_option('memberpress_installed_wp_mail_smtp')) {
            $link = 'https://shareasale.com/r.cfm?b=834775&u=409876&m=64312&urllink=wpmailsmtp%2Ecom%2Flite%2Dupgrade%2F&afftrack=MP%2DAnalytics%2DMenu%2DItem';
        }

        return $link;
    }

    /**
     * Records that an affiliate plugin was installed through MemberPress so the
     * matching affiliate link/ID filters can opt in.
     *
     * @return void
     */
    public function ajax_set_affiliate_install_flag(): void
    {
        if (!check_ajax_referer('mepr_set_affiliate_install_flag', '_ajax_nonce', false)) {
            wp_send_json_error(__('Security check failed.', 'memberpress'));
        }

        if (!current_user_can('install_plugins')) {
            wp_send_json_error(__("Sorry, you don't have permission to do this.", 'memberpress'));
        }

        $main_file = isset($_POST['main_file']) ? sanitize_text_field(wp_unslash($_POST['main_file'])) : '';

        if (empty($main_file)) {
            wp_send_json_error(__('Bad request.', 'memberpress'));
        }

        $affiliate_plugins = [
            'google-analytics-for-wordpress/googleanalytics.php' => 'monsterinsights',
            'wp-mail-smtp/wp_mail_smtp.php'                      => 'wp_mail_smtp',
        ];

        if (isset($affiliate_plugins[$main_file])) {
            update_option("memberpress_installed_{$affiliate_plugins[$main_file]}", true);
            wp_send_json_success();
        }

        wp_send_json_error();
    }

    /**
     * Affiliates.
     *
     * @return void
     */
    public static function affiliates()
    {
        $pricing_url = MeprUtils::get_link_url('affiliates_ea_pricing');

        MeprView::render('/admin/addons/affiliates', get_defined_vars());
    }
}
