<?php

namespace LinkFiliate\Libs\Utils;

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

use LinkFiliate\App\Traits\Singleton;

/**
 * Class Banner
 *
 * Handles admin migration notices for compatible affiliate link plugins.
 *
 * @package LinkFiliate\Admin
 */
class Banner
{

    use Singleton;

    /**
     * Initialize hooks.
     */
    public function init()
    {
        add_action('admin_notices', [$this, 'show_notices']);
        add_action('wp_ajax_linkfiliate_dismiss_notice', [$this, 'dismiss_notice']);
        add_action('wp_ajax_linkfiliate_deactivate_plugin', [$this, 'deactivate_plugin']);

        add_action('admin_enqueue_scripts', function () {
            wp_localize_script('linkfiliate-admin-global', 'linkfiliateBanners', [
                'nonce'   => wp_create_nonce('linkfiliate_admin_nonce'),
                'banners' => $this->get_active_banners(),
            ]);
        });
    }

    /**
     * Returns banner configuration.
     *
     * @return array
     */
    private function get_banners(): array
    {
        return [
            'prettylinks' => [
                'name'    => 'Pretty Links',
                'slug'    => ['pretty-link/pretty-link.php', 'pretty-link/pretty-link-lite.php'],
                'url'     => admin_url('admin.php?page=linkfiliate#/import-prettylinks'),
                'message' => 'We detected Pretty Links is active on your site! You can easily migrate your affiliate links, categories, and click statistics to LinkFiliate.'
            ],
            'betterlinks' => [
                'name'    => 'BetterLinks',
                'slug'    => ['betterlinks/betterlinks.php'],
                'url'     => admin_url('admin.php?page=linkfiliate#/import-better-links'),
                'message' => 'BetterLinks plugin detected! You can migrate all your affiliate data into LinkFiliate in one click.'
            ],
            'thirstyaffiliates' => [
                'name'    => 'ThirstyAffiliates',
                'slug'    => ['thirstyaffiliates/thirstyaffiliates.php'],
                'url'     => admin_url('admin.php?page=linkfiliate#/import-thirsty-affiliates'),
                'message' => 'We found ThirstyAffiliates on your site! Easily import all links, categories, and stats into LinkFiliate.'
            ],
            'clickwhale' => [
                'name'    => 'ClickWhale',
                'slug'    => ['clickwhale/clickwhale.php'],
                'url'     => admin_url('admin.php?page=linkfiliate#/import-clickwhale'),
                'message' => 'We found ClickWhale on your site! Easily import all links, categories, and stats into LinkFiliate.'
            ],
        ];
    }

    /**
     * Display admin notices.
     *
     * @return void
     */
    public function show_notices(): void
    {
        
        foreach ($this->get_banners() as $key => $data) {
            // Check plugin active
            $is_active = false;
            foreach ($data['slug'] as $slug) {
                if (is_plugin_active($slug)) {
                    $is_active = true;
                    break;
                }
            }

            if (! $is_active) {
                continue;
            }

            // Check if dismissed
            if (get_user_meta(get_current_user_id(), "linkfiliate_dismiss_{$key}_notice", true)) {
                continue;
            }

            // Output notice
            printf(
                '<div id="linkfiliate-%1$s-notice" class="notice notice-info is-dismissible">
					<p><strong>LinkFiliate:</strong> %2$s</p>
					<p>
						<a href="%3$s" class="button button-primary">Migrate from %4$s</a>
                        <a href="#" class="button linkfiliate-deactivate-plugin" data-plugin="%1$s" style="margin-left:10px;">Deactivate %4$s</a>
						
					</p>
				</div>',
                esc_attr($key),
                esc_html($data['message']),
                esc_url($data['url']),
                esc_html($data['name'])
            );
        }
    }

    /**
     * Handle AJAX dismiss action.
     *
     * @return void
     */
    public function dismiss_notice(): void
    {
        check_ajax_referer('linkfiliate_admin_nonce', 'nonce');

        if (empty($_POST['notice'])) {
            wp_die();
        }

        $notice = sanitize_text_field(wp_unslash($_POST['notice']));

        update_user_meta(
            get_current_user_id(),
            "linkfiliate_dismiss_{$notice}_notice",
            true
        );

        wp_die();
    }

    /**
     * Handle AJAX plugin deactivation.
     *
     * @return void
     */
    public function deactivate_plugin(): void
    {
        check_ajax_referer('linkfiliate_admin_nonce', 'nonce');

        if (empty($_POST['plugin'])) {
            wp_send_json_error(['message' => 'No plugin specified']);
        }


        $plugin_key = sanitize_text_field(wp_unslash($_POST['plugin']));
        $banners = $this->get_banners();

        if (!isset($banners[$plugin_key])) {
            wp_send_json_error(['message' => 'Invalid plugin']);
        }

        foreach ($banners[$plugin_key]['slug'] as $slug) {
            if (is_plugin_active($slug)) {
                deactivate_plugins($slug);
            }
        }

        wp_send_json_success(['message' => 'Plugin deactivated successfully']);
    }

    public function get_active_banners()
{
    $output = [];

    foreach ($this->get_banners() as $key => $data) {

        // check active plugin
        $is_active = false;
        foreach ($data['slug'] as $slug) {
            if (is_plugin_active($slug)) {
                $is_active = true;
                break;
            }
        }
        if (!$is_active) continue;

        // check dismissed
        if (get_user_meta(get_current_user_id(), "linkfiliate_dismiss_{$key}_notice", true)) {
            continue;
        }

        $output[] = [
            'key'     => $key,
            'name'    => $data['name'],
            'slug'     => $data['slug'],
            'message' => $data['message'],
            'url'     => $data['url'],
        ];
    }

    return $output;
}

}

