<?php

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

define( 'RAP_VERSION', '7.1.0' );

// List of WordPress.org authors to fetch plugins from.
define( 'RAP_AUTHORS', array( 'softtent', 'webangon' ) ); // Customize as needed.

require_once ICON_ELEM_DIR . 'admin/class-rap-plugin-fetcher.php';
require_once ICON_ELEM_DIR . 'admin/class-rap-plugin-installer.php';

/**
 * Register admin menu page.
 */
function rap_add_admin_menu() {
    add_menu_page(
        __( 'Icon Element Panel', 'iconelement' ),
        __( 'Icon Element', 'iconelement' ),
        'manage_options',
        'iconelement',
        'rap_render_admin_page',
        'dashicons-admin-generic',
        30
    );
}
add_action( 'admin_menu', 'rap_add_admin_menu' );

/**
 * Render container for React app.
 */
function rap_render_admin_page() {
    ?>
    <div class="wrap">
        <div class="rap-page-wrap">
            <div id="rap-root"></div>
        </div>
    </div>
    <?php
}

/**
 * Get all icon sets with metadata.
 *
 * @return array
 */
function rap_get_icon_sets() {
    return array(
        // Free (28)
        array(
            'id'      => 'ie-material-design',
            'name'    => 'Material Design (931 icons)',
            'pro'     => false,
            'preview' => 'https://material.io/resources/icons/?style=baseline',
        ),
        array(
            'id'      => 'ie-academic',
            'name'    => 'Academic (73 icons)',
            'pro'     => false,
            'preview' => 'https://jpswalsh.github.io/academicons/',
        ),
        array(
            'id'      => 'ie-phosphor-light',
            'name'    => 'Phosphor light (931 icons)',
            'pro'     => false,
            'preview' => 'https://phosphoricons.com/?weight=%22light%22',
        ),
        array(
            'id'      => 'ie-metrize',
            'name'    => 'Metrize (299 icons)',
            'pro'     => false,
            'preview' => 'http://www.alessioatzeni.com/metrize-icons/',
        ),
        array(
            'id'      => 'ie-captain',
            'name'    => 'Captain (374 icons)',
            'pro'     => false,
            'preview' => 'https://mariodelvalle.github.io/CaptainIconWeb/',
        ),
        array(
            'id'      => 'ie-ionicons',
            'name'    => 'Ionicons (695 icons)',
            'pro'     => false,
            'preview' => 'https://ionicons.com/',
        ),
        array(
            'id'      => 'ie-dripicons-icons',
            'name'    => 'Dripicons Icons (199 icons)',
            'pro'     => false,
            'preview' => 'http://demo.amitjakhu.com/dripicons/',
        ),
        array(
            'id'      => 'ie-simpline',
            'name'    => 'Simpline (188 icons)',
            'pro'     => false,
            'preview' => 'https://github.com/thesabbir/simple-line-icons',
        ),
        array(
            'id'      => 'ie-wppagebuilder',
            'name'    => 'Wp Pagebuilder (344 icons)',
            'pro'     => false,
            'preview' => 'https://builder.themeum.com/wppbicon/',
        ),
        array(
            'id'      => 'ie-elementor',
            'name'    => 'Elementor (386 icons)',
            'pro'     => false,
            'preview' => 'https://elementor.github.io/elementor-icons/',
        ),
        array(
            'id'      => 'ie-vscode',
            'name'    => 'VsCode Icon (411 icons)',
            'pro'     => false,
            'preview' => 'https://www.figma.com/community/file/768673354734944365',
        ),
        array(
            'id'      => 'ie-elusive',
            'name'    => 'Elusive (298 icons)',
            'pro'     => false,
            'preview' => 'http://elusiveicons.com/icons/',
        ),
        array(
            'id'      => 'ie-obicon',
            'name'    => 'Obicon (107 icons)',
            'pro'     => false,
            'preview' => 'https://ob-cloud.github.io/obicon-iot/',
        ),
        array(
            'id'      => 'ie-webicon',
            'name'    => 'Web icon (169 icons)',
            'pro'     => false,
            'preview' => 'https://github.com/thecreation/web-icons',
        ),
        array(
            'id'      => 'ie-feather',
            'name'    => 'Feather (265 icons)',
            'pro'     => false,
            'preview' => 'https://feathericons.com/',
        ),
        array(
            'id'      => 'ie-iconsaxbold',
            'name'    => 'Iconsax Bold (904 icons)',
            'pro'     => false,
            'preview' => 'https://iconsax.io/',
        ),
        array(
            'id'      => 'ie-tutor',
            'name'    => 'Tutor LMS Icon (314 icons)',
            'pro'     => false,
            'preview' => 'https://wordpress.org/plugins/tutor/',
        ),
        array(
            'id'      => 'ie-uniconsolid',
            'name'    => 'Unicon solid (189 icons)',
            'pro'     => false,
            'preview' => 'https://iconscout.com/unicons/explore/solid',
        ),
        array(
            'id'      => 'ie-happyicon',
            'name'    => 'Happy icon (646 icons)',
            'pro'     => false,
            'preview' => 'https://wordpress.org/plugins/happy-elementor-addons/',
        ),
        array(
            'id'      => 'ie-woocommerce',
            'name'    => 'Woo Commerce (68 icons)',
            'pro'     => false,
            'preview' => 'https://rawgit.com/woothemes/woocommerce-icons/master/demo.html',
        ),
        array(
            'id'      => 'ie-detheme',
            'name'    => 'DeTheme icon (385 icons)',
            'pro'     => false,
            'preview' => 'https://wordpress.org/plugins/dethemekit-for-elementor/',
        ),
        array(
            'id'      => 'ie-prestashop',
            'name'    => 'Prestashop (478 icons)',
            'pro'     => false,
            'preview' => 'https://build.prestashop-project.org/prestashop-icon-font/',
        ),
        array(
            'id'      => 'ie-uicons',
            'name'    => 'Uicons (2287 icons)',
            'pro'     => false,
            'preview' => 'https://github.com/freepik-company/flaticon-uicons/',
        ),
        array(
            'id'      => 'ie-jquery-uicons',
            'name'    => 'jQuery UI Icons (450 icons)',
            'pro'     => false,
            'preview' => 'https://api.jqueryui.com/resources/icons-list.html',
        ),
        array(
            'id'      => 'ie-xlslim',
            'name'    => 'XL Slim (292 icons)',
            'pro'     => false,
            'preview' => 'https://user-images.githubusercontent.com/5102591/46199020-8f8ed700-c316-11e8-9b3a-7388f3f4e818.png/',
        ),
        array(
            'id'      => 'ie-fabric',
            'name'    => 'Fabric Icon (1922 icons)',
            'pro'     => false,
            'preview' => 'https://uifabricicons.azurewebsites.net/',
        ),
        array(
            'id'      => 'ie-grommet',
            'name'    => 'Grommet (200 icons)',
            'pro'     => false,
            'preview' => 'https://icons.grommet.io/',
        ),
        array(
            'id'      => 'ie-orchid',
            'name'    => 'Orchid (283 icons)',
            'pro'     => false,
            'preview' => 'https://github.com/orchidsoftware/icons',
        ),

        // Pro (39)
        array(
            'id'      => 'ie-bootstrap',
            'name'    => 'Bootstrap (1682 icons)',
            'pro'     => true,
            'preview' => 'https://icons.getbootstrap.com/#icons',
        ),
        array(
            'id'      => 'ie-linea-music',
            'name'    => 'Linea Music (29 icons)',
            'pro'     => true,
            'preview' => 'https://linea.io/',
        ),
        array(
            'id'      => 'ie-boxicons-icons',
            'name'    => 'Boxicons (490 icons)',
            'pro'     => true,
            'preview' => 'https://github.com/atisawd/boxicons',
        ),
        array(
            'id'      => 'ie-elegant-font',
            'name'    => 'Elegant Font (359 icons)',
            'pro'     => true,
            'preview' => 'https://www.elegantthemes.com/blog/resources/elegant-icon-font',
        ),
        array(
            'id'      => 'ie-et-line',
            'name'    => 'ET Line (99 icons)',
            'pro'     => true,
            'preview' => 'https://www.elegantthemes.com/blog/freebie-of-the-week/free-line-style-icons',
        ),
        array(
            'id'      => 'ie-gonzo-font',
            'name'    => 'Gonzo (99 icons)',
            'pro'     => true,
            'preview' => 'https://www.gonzodesign.nl/gonzocons/',
        ),
        array(
            'id'      => 'ie-icomoon-font',
            'name'    => 'Icomoon (490 icons)',
            'pro'     => true,
            'preview' => 'https://icomoon.io/#preview-free',
        ),
        array(
            'id'      => 'ie-iconmonstr-font',
            'name'    => 'Iconmonstr (299 icons)',
            'pro'     => true,
            'preview' => 'https://iconmonstr.com/',
        ),
        array(
            'id'      => 'ie-io7-icon',
            'name'    => 'iOS7 (260 icons)',
            'pro'     => true,
            'preview' => 'http://akira-miyake.github.io/iOS7-icon-font/',
        ),
        array(
            'id'      => 'ie-linea_basic',
            'name'    => 'Linea Basic (134 icons)',
            'pro'     => true,
            'preview' => 'https://linea.io/',
        ),
        array(
            'id'      => 'ie-linea_elaboration',
            'name'    => 'Linea Elaboration (144 icons)',
            'pro'     => true,
            'preview' => 'https://linea.io/',
        ),
        array(
            'id'      => 'ie-linea_ecommerce',
            'name'    => 'Linea Ecommerce (84 icons)',
            'pro'     => true,
            'preview' => 'https://linea.io/',
        ),
        array(
            'id'      => 'ie-linearicons',
            'name'    => 'Linearicons (169 icons)',
            'pro'     => true,
            'preview' => 'https://linearicons.com/free',
        ),
        array(
            'id'      => 'ie-lineawesone-regular',
            'name'    => 'Lineawesome (1393 icons)',
            'pro'     => true,
            'preview' => 'https://icons8.com/line-awesome',
        ),
        array(
            'id'      => 'ie-lineicons',
            'name'    => 'Lineicons (306 icons)',
            'pro'     => true,
            'preview' => 'https://lineicons.com/',
        ),
        array(
            'id'      => 'ie-mobirise',
            'name'    => 'Mobirise (149 icons)',
            'pro'     => true,
            'preview' => 'https://mobiriseicons.com/cheatsheet.html',
        ),
        array(
            'id'      => 'ie-rivolicon',
            'name'    => 'Rivolicon (130 icons)',
            'pro'     => true,
            'preview' => 'https://rivolicons.hadrien.co/free/',
        ),
        array(
            'id'      => 'ie-themify-icons',
            'name'    => 'Themify-icons (351 icons)',
            'pro'     => true,
            'preview' => 'https://themify.me/themify-icons',
        ),
        array(
            'id'      => 'ie-tilda',
            'name'    => 'Tilda (794 icons)',
            'pro'     => true,
            'preview' => 'https://tilda.cc/free-icons/',
        ),
        array(
            'id'      => 'ie-tabler',
            'name'    => 'Tabler Icon (1977 icons)',
            'pro'     => true,
            'preview' => 'https://tablericons.com/',
        ),
        array(
            'id'      => 'ie-antdesign',
            'name'    => 'Antdesign Icon (637 icons)',
            'pro'     => true,
            'preview' => 'https://ant.design/components/icon/',
        ),
        array(
            'id'      => 'ie-chart',
            'name'    => 'Chart (37 icons)',
            'pro'     => true,
            'preview' => 'https://www.figma.com/file/0Gtw7eOrDnbNxPpveO183k/Chart-Icons---Outline-(Community)?node-id=275%3A6576',
        ),
        array(
            'id'      => 'ie-mapicon',
            'name'    => 'Map Icon (174 icons)',
            'pro'     => true,
            'preview' => 'http://map-icons.com/',
        ),
        array(
            'id'      => 'ie-devicon',
            'name'    => 'Devicon (499 icons)',
            'pro'     => true,
            'preview' => 'https://devicon.dev/',
        ),
        array(
            'id'      => 'ie-androidmaterial',
            'name'    => 'Android material (432 icons)',
            'pro'     => true,
            'preview' => 'https://www.androidicons.com/',
        ),
        array(
            'id'      => 'ie-androidholo',
            'name'    => 'Android holo (143 icons)',
            'pro'     => true,
            'preview' => 'https://www.androidicons.com/',
        ),
        array(
            'id'      => 'ie-evaicon',
            'name'    => 'Evaicon (244 icons)',
            'pro'     => true,
            'preview' => 'https://www.figma.com/file/T08qYmPlqINqGdU9ElXdXZ/Icon-Design-System---Eva-Icons-(Community)?node-id=0%3A1',
        ),
        array(
            'id'      => 'ie-iconicool',
            'name'    => 'Iconi cool (70 icons)',
            'pro'     => true,
            'preview' => 'https://www.figma.com/file/2jUsVzQgltQG4LXBYabU71/Iconicool-%7C-Free-Iconset-(Community)?node-id=3%3A250',
        ),
        array(
            'id'      => 'ie-elementplus',
            'name'    => 'Element plus (243 icons)',
            'pro'     => true,
            'preview' => 'https://element-plus.org/en-US/component/icon.html#icon-collection',
        ),
        array(
            'id'      => 'ie-uniconline',
            'name'    => 'Unicon line (1203 icons)',
            'pro'     => true,
            'preview' => 'https://iconscout.com/unicons/explore/line',
        ),
        array(
            'id'      => 'ie-unithinline',
            'name'    => 'Unicon thin line (214 icons)',
            'pro'     => true,
            'preview' => 'https://iconscout.com/unicons/explore/thinline',
        ),
        array(
            'id'      => 'ie-buddyboss',
            'name'    => 'Buddy Boss (1295 icons)',
            'pro'     => true,
            'preview' => 'https://www.buddyboss.com/resources/font-cheatsheet/',
        ),
        array(
            'id'      => 'ie-trademe',
            'name'    => 'Trademe (397 icons)',
            'pro'     => true,
            'preview' => 'https://trademe.github.io/TradeMe-IconFont/',
        ),
        array(
            'id'      => 'ie-mingcute',
            'name'    => 'Mingcute (2327 icons)',
            'pro'     => true,
            'preview' => 'https://www.mingcute.com/',
        ),
        array(
            'id'      => 'ie-olicons',
            'name'    => 'Olicons (677 icons)',
            'pro'     => true,
            'preview' => 'http://olicons.yemaosheji.com/index.html#sec-menu',
        ),
        array(
            'id'      => 'ie-phosphor-duotone',
            'name'    => 'Phosphor-duotone (3022 icons)',
            'pro'     => true,
            'preview' => 'https://phosphoricons.com/?weight=%22duotone%22',
        ),
        array(
            'id'      => 'ie-ixsiemens',
            'name'    => 'Siemens icon (642 icons)',
            'pro'     => true,
            'preview' => 'https://github.com/siemens/ix-icons',
        ),
        array(
            'id'      => 'ie-keyrune',
            'name'    => 'Keyrune (340 icons)',
            'pro'     => true,
            'preview' => 'https://keyrune.andrewgioia.com/icons.html',
        ),
        array(
            'id'      => 'ie-health',
            'name'    => 'Health (739 icons)',
            'pro'     => true,
            'preview' => 'https://healthicons.org/',
        ),
        array(
            'id'      => 'ie-icofont',
            'name'    => 'IcoFont (2139 icons)',
            'pro'     => true,
            'preview' => 'https://icofont.com',
        ),
        array(
            'id'      => 'ie-remix',
            'name'    => 'Remix (2055 icons)',
            'pro'     => true,
            'preview' => 'https://github.com/Remix-Design/RemixIcon',
        ),
        array(
            'id'      => 'ie-medical',
            'name'    => 'Medical (144 icons)',
            'pro'     => true,
            'preview' => '#',
        ),
        array(
            'id'      => 'ie-payment',
            'name'    => 'Payment (35 icons)',
            'pro'     => true,
            'preview' => '#',
        ),
        array(
            'id'      => 'ie-clarity',
            'name'    => 'Clarity (1081 icons)',
            'pro'     => true,
            'preview' => '#',
        ),
        array(
            'id'      => 'ie-jam',
            'name'    => 'Jam (986 icons)',
            'pro'     => true,
            'preview' => '#',
        ),
        array(
            'id'      => 'ie-octicons',
            'name'    => 'Octicons (986 icons)',
            'pro'     => true,
            'preview' => '#',
        ),
        array(
            'id'      => 'ie-nip',
            'name'    => 'Nip (82 icons)',
            'pro'     => true,
            'preview' => '#',
        ),
        array(
            'id'      => 'ie-framework7',
            'name'    => 'Framework7 (1233 icons)',
            'pro'     => true,
            'preview' => '#',
        ),  
        array(
            'id'      => 'ie-iconsaxcrypto',
            'name'    => 'Crypto (104 icons)',
            'pro'     => true,
            'preview' => '#',
        ),     
        array(
            'id'      => 'ie-iconsaxoutline',
            'name'    => 'Outline (898 icons)',
            'pro'     => true,
            'preview' => '#',
        ), 
        array(
            'id'      => 'ie-outlined',
            'name'    => 'Outlined (150 icons)',
            'pro'     => true,
            'preview' => '#',
        ),                            
    );
}

/**
 * Enqueue React scripts and styles.
 */
function rap_enqueue_admin_assets( $hook ) {
    if ( 'toplevel_page_iconelement' !== $hook ) {
        return;
    }

    wp_enqueue_script( 'react' );
    wp_enqueue_script( 'react-dom' );
    wp_enqueue_script( 'wp-api-fetch' );

    wp_enqueue_script(
        'rap-admin-script',
        ICON_ELEM_URL . 'admin/assets/js/admin-script.js',
        array( 'react', 'react-dom', 'wp-api-fetch' ),
        RAP_VERSION,
        true
    );

    wp_enqueue_style(
        'rap-admin-style',
        ICON_ELEM_URL . 'admin/assets/css/admin-style.css',
        array(),
        RAP_VERSION
    );

    wp_localize_script(
        'wp-api-fetch',
        'wpApiSettings',
        array(
            'root'  => esc_url_raw( rest_url() ),
            'nonce' => wp_create_nonce( 'wp_rest' ),
        )
    );

    wp_localize_script(
        'rap-admin-script',
        'rapSettings',
        array(
            'defaults'      => rap_get_settings_array(),
            'iconSets'      => rap_get_icon_sets(),
            'restNamespace' => 'iconelement-admin/v1',  // ← only namespace
            'nonce'         => wp_create_nonce( 'wp_rest' ), 
            'isLoggedIn'    => is_user_logged_in(),
            'authorSlugs'   => RAP_AUTHORS,
            'ispro'   => Icon_Element_Icons::is_iconelement_pro(),
        )
    );

} 
add_action( 'admin_enqueue_scripts', 'rap_enqueue_admin_assets' );

/**
 * Retrieve settings array from single option.
 *
 * @return array
 */
function rap_get_settings_array() {
    $icon_sets = rap_get_icon_sets();
    $defaults = array();
    foreach ( $icon_sets as $set ) {
        $defaults[ $set['id'] ] = false;
    }

    $settings = get_option( 'rap_settings', array() );
    return wp_parse_args( $settings, $defaults );
}

/**
 * Register REST API routes.
 */
function rap_register_rest_routes() {
    // Settings endpoints.
    register_rest_route(
        'iconelement-admin/v1',
        '/settings',
        array(
            'methods'             => 'GET',
            'callback'            => 'rap_get_settings',
            'permission_callback' => 'rap_permissions_check',
        )
    );
    register_rest_route(
        'iconelement-admin/v1',
        '/settings',
        array(
            'methods'             => 'POST',
            'callback'            => 'rap_update_settings',
            'permission_callback' => 'rap_permissions_check',
            'args'                => array(),
        )
    );

    // Plugins list endpoint (multi‑author).
    register_rest_route(
        'iconelement-admin/v1',
        '/plugins',
        array(
            'methods'             => 'GET',
            'callback'            => 'rap_get_plugins',
            'permission_callback' => 'rap_permissions_check',
            'args'                => array(
                'authors' => array(
                    'required' => true,
                    'type'     => 'string',
                ),
            ),
        )
    );

    // Plugin installation endpoint.
    register_rest_route(
        'iconelement-admin/v1',
        '/install-plugin',
        array(
            'methods'             => 'POST',
            'callback'            => 'rap_install_plugin',
            'permission_callback' => 'rap_permissions_check',
            'args'                => array(
                'slug' => array(
                    'required' => true,
                    'type'     => 'string',
                ),
            ),
        )
    );

    // Plugin activation endpoint.
    register_rest_route(
        'iconelement-admin/v1',
        '/activate-plugin',
        array(
            'methods'             => 'POST',
            'callback'            => 'rap_rest_activate_plugin',
            'permission_callback' => 'rap_permissions_check',
            'args'                => array(
                'slug' => array(
                    'required' => true,
                    'type'     => 'string',
                ),
            ),
        )
    );

    // Plugin status endpoint.
    register_rest_route(
        'iconelement-admin/v1',
        '/plugin-status',
        array(
            'methods'             => 'GET',
            'callback'            => 'rap_plugin_status',
            'permission_callback' => 'rap_permissions_check',
            'args'                => array(
                'slug' => array(
                    'required' => true,
                    'type'     => 'string',
                ),
            ),
        )
    );
}
add_action( 'rest_api_init', 'rap_register_rest_routes' );

/**
 * Permission callback.
 */
function rap_permissions_check() {
    return current_user_can( 'manage_options' );
}

/**
 * GET endpoint: retrieve all settings.
 */
function rap_get_settings() {
    return rest_ensure_response( rap_get_settings_array() );
}

/**
 * POST endpoint: update all settings.
 */
function rap_update_settings( $request ) {
    $settings = rap_get_settings_array();

    foreach ( array_keys( $settings ) as $key ) {
        if ( $request->has_param( $key ) ) {
            $settings[ $key ] = (bool) $request->get_param( $key );
        }
    }

    update_option( 'rap_settings', $settings );
    return rest_ensure_response( $settings );
}

/**
 * GET endpoint: fetch plugins from multiple authors.
 */
function rap_get_plugins( $request ) {
    $authors = $request->get_param( 'authors' );
    if ( empty( $authors ) ) {
        return rest_ensure_response( array( 'error' => true, 'message' => 'No authors provided.' ) );
    }
    if ( is_string( $authors ) ) {
        $authors = array_map( 'trim', explode( ',', $authors ) );
    }
    return rest_ensure_response( RAP_Plugin_Fetcher::fetch_plugins_by_authors( $authors ) );
}

/**
 * POST endpoint: install a plugin.
 */
function rap_install_plugin( $request ) {
    $slug = $request->get_param( 'slug' );
    $result = RAP_Plugin_Installer::install_plugin( $slug );
    return rest_ensure_response( $result );
}

/**
 * POST endpoint: activate an installed plugin.
 */
function rap_rest_activate_plugin( $request ) {
    $slug   = $request->get_param( 'slug' );
    $result = RAP_Plugin_Installer::activate_plugin( $slug );
    return rest_ensure_response( $result );
}

/**
 * GET endpoint: check if plugin is installed/active.
 */
function rap_plugin_status( $request ) {
    $slug = $request->get_param( 'slug' );
    return rest_ensure_response( array(
        'installed' => RAP_Plugin_Installer::is_plugin_installed( $slug ),
        'active'    => RAP_Plugin_Installer::is_plugin_active( $slug ),
    ) );
}

/**
 * Activation hook: set default options and flush rewrite rules.
 */
function rap_activate_plugin() {
    $existing = get_option( 'rap_settings', array() );
    if ( empty( $existing ) ) {
        $defaults = rap_get_settings_array();
        add_option( 'rap_settings', $defaults );
    } else {
        $defaults = rap_get_settings_array();
        $merged = wp_parse_args( $existing, $defaults );
        update_option( 'rap_settings', $merged );
    }
    // Clear plugin cache so requires_plugins field is fetched fresh.
    RAP_Plugin_Fetcher::clear_cache();
    flush_rewrite_rules();
}
register_activation_hook( ICONELEMENT_ROOT_FILE__, 'rap_activate_plugin' );

/**
 * Deactivation hook: flush rewrite rules.
 */
function rap_deactivate_plugin() {
    flush_rewrite_rules();
}
register_deactivation_hook( ICONELEMENT_ROOT_FILE__, 'rap_deactivate_plugin' );

/**
 * Clear the plugin list cache whenever WordPress runs its own update check.
 * This fires during the scheduled wp_update_plugins / wp_update_themes cron events
 * and when the user visits Dashboard → Updates.
 */
function rap_clear_cache_on_wp_update_check() {
    RAP_Plugin_Fetcher::clear_cache();
}
add_action( 'wp_update_plugins', 'rap_clear_cache_on_wp_update_check' );
add_action( 'wp_update_themes',  'rap_clear_cache_on_wp_update_check' );