<?php

/**
 * Plugin Name: NINZ Icons for Elementor
 * Description: Adds 3700+ Solar SVG icons to Elementor icon library.
 * Version: 2.0.1
 * Author: Shakil Ansary
 * Author URI: https://shakilansary.com
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: ninz-icons-for-elementor
 */

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

// Prefixing constants to prevent conflicts
define('NINZ_ICONS_URL', plugin_dir_url(__FILE__));
define('NINZ_ICONS_PATH', plugin_dir_path(__FILE__));

function ninz_icons_get_sets()
{
    return [
        'solar-icons-linear' => [
            'label'         => esc_html__('Solar Icons Linear', 'ninz-icons-for-elementor'),
            'prefix'        => 'ninz-soli-',
            'displayPrefix' => 'ninz-soli',
            'labelIcon'     => 'ninz-soli ninz-soli-bolt-new',
            'css_handle'    => 'ninz-icons-style',
            'css_url'       => 'assets/css/solar-icons-linear.css',
            'json_url'      => 'assets/icons/solar-icons-linear/icon-json/icons.json',
        ],
        'solar-icons-bold' => [
            'label'         => esc_html__('Solar Icons Bold', 'ninz-icons-for-elementor'),
            'prefix'        => 'ninz-sobo-',
            'displayPrefix' => 'ninz-sobo',
            'labelIcon'     => 'ninz-sobo ninz-sobo-stars',
            'css_handle'    => 'solar-icons-bold-style',
            'css_url'       => 'assets/css/solar-icons-bold.css',
            'json_url'      => 'assets/icons/solar-icons-bold/icon-json/icons.json',
        ],
        'solar-icons-bold-duotone' => [
            'label'         => esc_html__('Solar Icons Bold Duotone', 'ninz-icons-for-elementor'),
            'prefix'        => 'ninz-sobd-',
            'displayPrefix' => 'ninz-sobd',
            'labelIcon'     => 'ninz-sobd ninz-sobd-stars',
            'css_handle'    => 'solar-icons-bold-duotone-style',
            'css_url'       => 'assets/css/solar-icons-bold-duotone.css',
            'json_url'      => 'assets/icons/solar-icons-bold-duotone/icon-json/icons.json',
        ],
    ];
}

function ninz_icons_get_settings()
{
    $defaults = [];

    foreach (ninz_icons_get_sets() as $id => $set) {
        $defaults[$id] = 1;
    }

    return get_option('ninz_icon_sets_settings', $defaults);
}

function ninz_icons_is_set_enabled($set_id)
{
    $settings = ninz_icons_get_settings();
    return isset($settings[$set_id]) && $settings[$set_id];
}

function ninz_icons_init()
{
    if (! did_action('elementor/loaded')) {
        add_action('admin_notices', 'ninz_icons_elementor_missing_notice');
        return;
    }

    add_filter('elementor/icons_manager/additional_tabs', 'ninz_icons_register_tab');
    add_action('wp_enqueue_scripts', 'ninz_icons_enqueue_styles');
    add_action('elementor/editor/after_enqueue_styles', 'ninz_icons_enqueue_styles');
    add_action('elementor/preview/enqueue_styles', 'ninz_icons_enqueue_styles');
}
add_action('plugins_loaded', 'ninz_icons_init');

function ninz_icons_register_tab($tabs)
{
    foreach (ninz_icons_get_sets() as $id => $set) {
        if (! ninz_icons_is_set_enabled($id)) {
            continue;
        }

        $tabs[$id] = [
            'name'          => $id,
            'label'         => $set['label'],
            'url'           => NINZ_ICONS_URL . $set['css_url'],
            'enqueue'       => [NINZ_ICONS_URL . $set['css_url']],
            'prefix'        => $set['prefix'],
            'displayPrefix' => $set['displayPrefix'],
            'labelIcon'     => $set['labelIcon'],
            'ver'           => '1.0.0',
            'fetchJson'     => NINZ_ICONS_URL . $set['json_url'],
            'native'        => false,
        ];
    }

    return $tabs;
}

function ninz_icons_enqueue_styles()
{
    foreach (ninz_icons_get_sets() as $id => $set) {
        if (! ninz_icons_is_set_enabled($id)) {
            continue;
        }

        wp_enqueue_style(
            $set['css_handle'],
            NINZ_ICONS_URL . $set['css_url'],
            [],
            '1.0.0'
        );
    }
}

function ninz_icons_elementor_missing_notice()
{
    $message = sprintf(
        /* translators: %s: Elementor link */
        esc_html__('Ninz Icons requires %s to be installed and activated.', 'ninz-icons-for-elementor'),
        '<a href="' . esc_url('https://elementor.com') . '" target="_blank">Elementor</a>'
    );

    printf(
        '<div class="notice notice-warning is-dismissible"><p><strong>%s</strong> %s</p></div>',
        esc_html__('Ninz Icons:', 'ninz-icons-for-elementor'),
        wp_kses_post($message)
    );
}

function ninz_icons_admin_menu()
{
    add_options_page(
        esc_html__('Ninz Icons', 'ninz-icons-for-elementor'),
        esc_html__('Ninz Icons', 'ninz-icons-for-elementor'),
        'manage_options',
        'ninz-icons',
        'ninz_icons_admin_page'
    );
}
add_action('admin_menu', 'ninz_icons_admin_menu');

function ninz_icons_admin_page()
{
    if (! current_user_can('manage_options')) {
        return;
    }

    $settings = ninz_icons_get_settings();
?>
    <div class="wrap">
        <h1><?php esc_html_e('Ninz Icons', 'ninz-icons-for-elementor'); ?></h1>
        <p><?php esc_html_e('Toggle individual icon sets on or off. Disabled sets will be hidden from the Elementor icon library.', 'ninz-icons-for-elementor'); ?>
        </p>
        <div class="niadm-cards" id="niadm-cards">
            <?php foreach (ninz_icons_get_sets() as $id => $set) : ?>
                <div class="niadm-card <?php echo ! empty($settings[$id]) ? 'niadm-card--enabled' : 'niadm-card--disabled'; ?>"
                    data-set-id="<?php echo esc_attr($id); ?>">
                    <div class="niadm-card__left">
                        <div class="niadm-card__preview">
                            <i class="<?php echo esc_attr($set['labelIcon']); ?>"></i>
                        </div>
                        <h3 class="niadm-card__title"><?php echo esc_html($set['label']); ?></h3>
                    </div>
                    <div class="niadm-card__toggle">
                        <label class="niadm-toggle-switch">
                            <input type="checkbox" <?php checked(! empty($settings[$id])); ?>>
                            <span class="niadm-toggle-slider"></span>
                        </label>
                        <span
                            class="niadm-card__status <?php echo ! empty($settings[$id]) ? 'niadm-card__status--enabled' : 'niadm-card__status--disabled'; ?>">
                            <?php echo ! empty($settings[$id]) ? esc_html__('Enabled', 'ninz-icons-for-elementor') : esc_html__('Disabled', 'ninz-icons-for-elementor'); ?>
                        </span>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
<?php
}

function ninz_icons_admin_enqueue($hook)
{
    if ($hook !== 'settings_page_ninz-icons') {
        return;
    }

    $deps = [];

    foreach (ninz_icons_get_sets() as $id => $set) {
        wp_enqueue_style(
            $set['css_handle'],
            NINZ_ICONS_URL . $set['css_url'],
            [],
            '1.0.0'
        );

        $deps[] = $set['css_handle'];
    }

    wp_enqueue_style(
        'ninz-icons-admin-toggle',
        NINZ_ICONS_URL . 'assets/css/admin-toggle.css',
        $deps,
        '1.0.0'
    );

    wp_enqueue_script(
        'ninz-icons-admin-toggle',
        NINZ_ICONS_URL . 'assets/js/admin-toggle.js',
        [],
        '1.0.0',
        true
    );

    wp_localize_script('ninz-icons-admin-toggle', 'ninzIconsData', [
        'ajaxUrl' => admin_url('admin-ajax.php'),
        'nonce'   => wp_create_nonce('ninz_icons_toggle_nonce'),
    ]);
}
add_action('admin_enqueue_scripts', 'ninz_icons_admin_enqueue');

function ninz_icons_ajax_toggle()
{
    check_ajax_referer('ninz_icons_toggle_nonce', 'nonce');

    if (! current_user_can('manage_options')) {
        wp_send_json_error(['message' => 'Unauthorized']);
    }

    $set_id   = isset($_POST['set_id']) ? sanitize_key($_POST['set_id']) : '';
    $enabled  = ! empty($_POST['enabled']) ? 1 : 0;

    $all_sets = ninz_icons_get_sets();

    if (! isset($all_sets[$set_id])) {
        wp_send_json_error(['message' => 'Invalid set']);
    }

    $settings       = ninz_icons_get_settings();
    $settings[$set_id] = $enabled;
    update_option('ninz_icon_sets_settings', $settings);

    wp_send_json_success([
        'set_id'  => $set_id,
        'enabled' => $enabled,
    ]);
}
add_action('wp_ajax_ninz_toggle_icon_set', 'ninz_icons_ajax_toggle');

define('NINZ_ICONS_REVIEW_URL', 'https://wordpress.org/support/plugin/ninz-icons-for-elementor/reviews/#new-post');

function ninz_icons_review_notice()
{
    if (! current_user_can('manage_options')) {
        return;
    }

    $user_id = get_current_user_id();
    $dismissed = get_user_meta($user_id, 'ninz_icons_review_dismissed', true);

    if ($dismissed) {
        return;
    }

?>
    <div class="notice notice-info is-dismissible niadm-review-notice"
        data-nonce="<?php echo esc_attr(wp_create_nonce('ninz_review_dismiss')); ?>">
        <p>
            <?php esc_html_e('Liked our icons? Please leave a review', 'ninz-icons-for-elementor'); ?>
            <a href="<?php echo esc_url(NINZ_ICONS_REVIEW_URL); ?>" target="_blank" class="button button-primary"
                style="margin-left:10px;">
                <?php esc_html_e('Leave a Review', 'ninz-icons-for-elementor'); ?>
            </a>
        </p>
    </div>
<?php
}
add_action('admin_notices', 'ninz_icons_review_notice');

function ninz_icons_dismiss_review_notice()
{
    check_ajax_referer('ninz_review_dismiss', 'nonce');

    if (! current_user_can('manage_options')) {
        wp_send_json_error();
    }

    $user_id = get_current_user_id();
    update_user_meta($user_id, 'ninz_icons_review_dismissed', 1);

    wp_send_json_success();
}
add_action('wp_ajax_ninz_dismiss_review', 'ninz_icons_dismiss_review_notice');

function ninz_icons_review_notice_script()
{
    if (! current_user_can('manage_options')) {
        return;
    }

    $user_id = get_current_user_id();
    if (get_user_meta($user_id, 'ninz_icons_review_dismissed', true)) {
        return;
    }
?>
    <script>
        (function() {
            var notice = document.querySelector('.niadm-review-notice');
            if (!notice) return;
            var btn = notice.querySelector('.notice-dismiss');
            if (!btn) return;
            btn.addEventListener('click', function() {
                var data = new FormData();
                data.append('action', 'ninz_dismiss_review');
                data.append('nonce', notice.dataset.nonce);
                fetch(ajaxurl, {
                    method: 'POST',
                    body: data
                });
            });
        })();
    </script>
<?php
}
add_action('admin_footer', 'ninz_icons_review_notice_script');
