<?php

/**
 * Plugin Name: Canvon Floating Buttons
 * Description: Display Canvon floating buttons on your site and customize their content and appearance.
 * Version: 1.0.0
 * Author: Canvon
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: canvon-floating-buttons
 *
 *
 * Main plugin file - Loads all plugin components and defines constants.
 * This is the entry point that WordPress reads to recognize the plugin.
 * It loads all necessary files from includes/ and admin/ directories.
 */
// Prevent direct access
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
if ( !function_exists( 'canvon_fb_fs' ) ) {
    // Create a helper function for easy SDK access.
    function canvon_fb_fs() {
        global $canvon_fb_fs;
        if ( !isset( $canvon_fb_fs ) ) {
            // Include Freemius SDK.
            require_once dirname( __FILE__ ) . '/vendor/freemius/start.php';
            $canvon_fb_fs = fs_dynamic_init( array(
                'id'               => '24424',
                'slug'             => 'canvon-floating-buttons',
                'premium_slug'     => 'canvon-floating-buttons-premium',
                'type'             => 'plugin',
                'public_key'       => 'pk_c30fd158119cdd21bfd8adf441130',
                'is_premium'       => false,
                'premium_suffix'   => 'Premium',
                'has_addons'       => false,
                'has_paid_plans'   => true,
                'is_org_compliant' => true,
                'menu'             => array(
                    'slug'    => 'canvon-floating-buttons',
                    'contact' => false,
                    'support' => false,
                ),
                'is_live'          => true,
            ) );
        }
        return $canvon_fb_fs;
    }

    // Init Freemius.
    canvon_fb_fs();
    // Track premium activation to display a custom banner inside our settings UI.
    if ( !function_exists( 'canvon_fb_set_premium_activated_banner' ) ) {
        function canvon_fb_set_premium_activated_banner() {
            set_transient( 'canvon_fb_premium_activated_banner', 1, 15 * MINUTE_IN_SECONDS );
            update_option( 'canvon_fb_show_premium_activated_banner', 1, false );
            update_option( 'canvon_fb_premium_banner_dismissed', 0, false );
        }

    }
    if ( !function_exists( 'canvon_fb_can_download_premium_build' ) ) {
        function canvon_fb_can_download_premium_build() {
            return function_exists( 'canvon_fb_fs' ) && canvon_fb_fs()->can_use_premium_code() && !canvon_fb_fs()->is_premium();
        }

    }
    if ( !function_exists( 'canvon_fb_get_freemius_upgrade_notice_message' ) ) {
        function canvon_fb_get_freemius_upgrade_notice_message() {
            $canvon_fb_download_url = ( function_exists( 'canvon_fb_fs' ) ? canvon_fb_fs()->_get_latest_download_local_url() : '' );
            $canvon_fb_upload_url = 'https://wordpress.org/documentation/article/plugins-add-new-screen/#upload-plugins';
            return sprintf(
                '%1$s: <ol><li><a target="_blank" rel="noopener" href="%2$s">%3$s</a>.</li><li>%4$s (<a href="%5$s" target="_blank" rel="noopener">%6$s</a>).</li></ol>',
                esc_html__( 'Your account was successfully activated with the Premium plan. Please follow these steps to complete the upgrade', 'canvon-floating-buttons' ),
                esc_url( $canvon_fb_download_url ),
                esc_html__( 'Download the latest Premium version', 'canvon-floating-buttons' ),
                esc_html__( 'Upload and activate the downloaded version', 'canvon-floating-buttons' ),
                esc_url( $canvon_fb_upload_url ),
                esc_html__( 'How to upload and activate?', 'canvon-floating-buttons' )
            );
        }

    }
    if ( !function_exists( 'canvon_fb_reshow_freemius_upgrade_notice' ) ) {
        function canvon_fb_reshow_freemius_upgrade_notice() {
            if ( !is_admin() || !isset( $_GET['canvon_fb_reshow_freemius_upgrade_notice'] ) || '1' !== sanitize_text_field( wp_unslash( $_GET['canvon_fb_reshow_freemius_upgrade_notice'] ) ) ) {
                return;
            }
            if ( !current_user_can( 'manage_options' ) || !isset( $_GET['_canvon_fb_notice_nonce'] ) || !wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_canvon_fb_notice_nonce'] ) ), 'canvon_fb_reshow_freemius_upgrade_notice' ) ) {
                wp_die( esc_html__( 'You are not allowed to restore this notice.', 'canvon-floating-buttons' ) );
            }
            canvon_fb_add_freemius_upgrade_notice();
            wp_safe_redirect( remove_query_arg( array('canvon_fb_reshow_freemius_upgrade_notice', '_canvon_fb_notice_nonce') ) );
            exit;
        }

    }
    add_action( 'admin_init', 'canvon_fb_reshow_freemius_upgrade_notice' );
    if ( !function_exists( 'canvon_fb_add_freemius_upgrade_notice' ) ) {
        function canvon_fb_add_freemius_upgrade_notice() {
            if ( !canvon_fb_can_download_premium_build() ) {
                return false;
            }
            canvon_fb_fs()->add_sticky_admin_message(
                canvon_fb_get_freemius_upgrade_notice_message(),
                'plan_upgraded',
                esc_html__( 'Yee-haw!', 'canvon-floating-buttons' ),
                'success'
            );
            return true;
        }

    }
    if ( !function_exists( 'canvon_fb_ajax_reshow_freemius_upgrade_notice' ) ) {
        function canvon_fb_ajax_reshow_freemius_upgrade_notice() {
            check_ajax_referer( 'canvon_fb_reshow_freemius_upgrade_notice', 'nonce' );
            if ( !current_user_can( 'manage_options' ) ) {
                wp_send_json_error( array(
                    'message' => 'Unauthorized',
                ), 403 );
            }
            if ( !canvon_fb_add_freemius_upgrade_notice() ) {
                wp_send_json_error( array(
                    'message' => 'Premium download is not available.',
                ), 400 );
            }
            wp_send_json_success();
        }

    }
    add_action( 'wp_ajax_canvon_fb_reshow_freemius_upgrade_notice', 'canvon_fb_ajax_reshow_freemius_upgrade_notice' );
    canvon_fb_fs()->add_action( 'after_premium_version_activation', 'canvon_fb_set_premium_activated_banner' );
    // Also trigger the custom banner when the premium plugin itself is activated.
    register_activation_hook( __FILE__, 'canvon_fb_set_premium_activated_banner' );
    if ( !function_exists( 'canvon_fb_get_plugin_brand_name' ) ) {
        function canvon_fb_get_plugin_brand_name() {
            return 'Canvon Floating Buttons';
        }

    }
    if ( !function_exists( 'canvon_fb_get_plugin_brand_icon_url' ) ) {
        function canvon_fb_get_plugin_brand_icon_url() {
            return plugin_dir_url( __FILE__ ) . 'vendor/freemius/assets/img/canvon-floating-buttons.png';
        }

    }
    if ( !function_exists( 'canvon_fb_get_icon_kses_allowed_html' ) ) {
        function canvon_fb_get_icon_kses_allowed_html() {
            return array(
                'svg'      => array(
                    'aria-hidden'     => true,
                    'class'           => true,
                    'fill'            => true,
                    'focusable'       => true,
                    'height'          => true,
                    'role'            => true,
                    'stroke'          => true,
                    'stroke-linecap'  => true,
                    'stroke-linejoin' => true,
                    'stroke-width'    => true,
                    'viewbox'         => true,
                    'viewBox'         => true,
                    'width'           => true,
                    'xmlns'           => true,
                ),
                'path'     => array(
                    'class'           => true,
                    'clip-rule'       => true,
                    'd'               => true,
                    'fill'            => true,
                    'fill-rule'       => true,
                    'stroke'          => true,
                    'stroke-linecap'  => true,
                    'stroke-linejoin' => true,
                    'stroke-width'    => true,
                ),
                'circle'   => array(
                    'cx'     => true,
                    'cy'     => true,
                    'fill'   => true,
                    'r'      => true,
                    'stroke' => true,
                ),
                'rect'     => array(
                    'fill'   => true,
                    'height' => true,
                    'rx'     => true,
                    'ry'     => true,
                    'stroke' => true,
                    'width'  => true,
                    'x'      => true,
                    'y'      => true,
                ),
                'line'     => array(
                    'stroke'          => true,
                    'stroke-linecap'  => true,
                    'stroke-linejoin' => true,
                    'stroke-width'    => true,
                    'x1'              => true,
                    'x2'              => true,
                    'y1'              => true,
                    'y2'              => true,
                ),
                'polyline' => array(
                    'fill'            => true,
                    'points'          => true,
                    'stroke'          => true,
                    'stroke-linecap'  => true,
                    'stroke-linejoin' => true,
                    'stroke-width'    => true,
                ),
                'polygon'  => array(
                    'fill'   => true,
                    'points' => true,
                    'stroke' => true,
                ),
                'g'        => array(
                    'clip-path' => true,
                    'fill'      => true,
                    'stroke'    => true,
                ),
                'defs'     => array(),
                'clipPath' => array(
                    'id' => true,
                ),
                'img'      => array(
                    'alt'    => true,
                    'class'  => true,
                    'height' => true,
                    'src'    => true,
                    'style'  => true,
                    'width'  => true,
                ),
            );
        }

    }
    if ( !function_exists( 'canvon_fb_is_freemius_pricing_request' ) ) {
        function canvon_fb_is_freemius_pricing_request() {
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin routing check; no state change is performed here.
            $canvon_fb_page = ( isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '' );
            return is_admin() && 'canvon-floating-buttons-pricing' === $canvon_fb_page;
        }

    }
    if ( !function_exists( 'canvon_fb_get_pricing_action_param' ) ) {
        function canvon_fb_get_pricing_action_param() {
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Used only to route Freemius pricing AJAX; nonce is checked before overriding the response.
            return ( isset( $_GET['pricing_action'] ) ? sanitize_key( wp_unslash( $_GET['pricing_action'] ) ) : '' );
        }

    }
    if ( !function_exists( 'canvon_fb_purge_freemius_pricing_cache' ) ) {
        function canvon_fb_purge_freemius_pricing_cache() {
            if ( !canvon_fb_is_freemius_pricing_request() || !class_exists( 'FS_Api' ) || !current_user_can( 'manage_options' ) ) {
                return;
            }
            if ( defined( 'DOING_AJAX' ) && DOING_AJAX && 'fetch_pricing_data' === canvon_fb_get_pricing_action_param() ) {
                nocache_headers();
            }
            $canvon_fb_api = canvon_fb_fs()->get_api_plugin_scope();
            foreach ( array(false, true) as $canvon_fb_is_trial ) {
                $canvon_fb_params = array(
                    'is_enriched'  => true,
                    'trial'        => $canvon_fb_is_trial,
                    'sandbox'      => null,
                    's_ctx_type'   => null,
                    's_ctx_id'     => null,
                    's_ctx_ts'     => null,
                    's_ctx_secure' => null,
                );
                $canvon_fb_api->purge_cache( canvon_fb_fs()->add_show_pending( 'pricing.json?' . http_build_query( $canvon_fb_params ) ) );
            }
        }

    }
    add_action( 'admin_init', 'canvon_fb_purge_freemius_pricing_cache' );
    if ( !function_exists( 'canvon_fb_override_freemius_pricing_ajax' ) ) {
        function canvon_fb_override_freemius_pricing_ajax() {
            if ( 'fetch_pricing_data' !== canvon_fb_get_pricing_action_param() ) {
                return;
            }
            canvon_fb_fs()->check_ajax_referer( 'pricing_ajax_action' );
            if ( !current_user_can( 'manage_options' ) ) {
                wp_send_json_error( array(
                    'message' => 'Unauthorized',
                ), 403 );
            }
            $canvon_fb_params = array(
                'is_enriched'  => true,
                'trial'        => fs_request_get_bool( 'trial' ),
                'sandbox'      => fs_request_get_raw( 'sandbox' ),
                's_ctx_type'   => fs_request_get_raw( 's_ctx_type' ),
                's_ctx_id'     => fs_request_get_raw( 's_ctx_id' ),
                's_ctx_ts'     => fs_request_get_raw( 's_ctx_ts' ),
                's_ctx_secure' => fs_request_get_raw( 's_ctx_secure' ),
            );
            $canvon_fb_result = canvon_fb_fs()->get_api_plugin_scope()->get( canvon_fb_fs()->add_show_pending( 'pricing.json?' . http_build_query( $canvon_fb_params ) ) );
            if ( is_object( $canvon_fb_result ) && isset( $canvon_fb_result->plugin ) && is_object( $canvon_fb_result->plugin ) ) {
                $canvon_fb_result->plugin->title = canvon_fb_get_plugin_brand_name();
                $canvon_fb_result->plugin->icon = canvon_fb_get_plugin_brand_icon_url();
            }
            wp_send_json_success( $canvon_fb_result );
        }

    }
    if ( !function_exists( 'canvon_fb_register_freemius_pricing_ajax_override' ) ) {
        function canvon_fb_register_freemius_pricing_ajax_override() {
            add_action( 'wp_ajax_' . canvon_fb_fs()->get_ajax_action( 'pricing_ajax_action' ), 'canvon_fb_override_freemius_pricing_ajax', 1 );
        }

    }
    add_action( 'init', 'canvon_fb_register_freemius_pricing_ajax_override', 20 );
    if ( !function_exists( 'canvon_fb_hide_freemius_custom_implementation_upsell' ) ) {
        function canvon_fb_hide_freemius_custom_implementation_upsell(  $canvon_fb_html  ) {
            return $canvon_fb_html;
        }

    }
    canvon_fb_fs()->add_filter( 'templates/pricing.php', 'canvon_fb_hide_freemius_custom_implementation_upsell' );
    // Signal that SDK was initiated.
    do_action( 'canvon_fb_fs_loaded' );
}
// Handle premium banner dismiss early (before headers are sent).
add_action( 'admin_init', function () {
    if ( !isset( $_GET['canvon_fb_dismiss_premium_banner'] ) || '1' !== sanitize_text_field( wp_unslash( $_GET['canvon_fb_dismiss_premium_banner'] ) ) ) {
        return;
    }
    if ( !current_user_can( 'manage_options' ) || !isset( $_GET['_canvon_fb_banner_nonce'] ) || !wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_canvon_fb_banner_nonce'] ) ), 'canvon_fb_dismiss_premium_banner' ) ) {
        wp_die( esc_html__( 'You are not allowed to dismiss this notice.', 'canvon-floating-buttons' ) );
    }
    update_option( 'canvon_fb_premium_banner_dismissed', 1, false );
    delete_transient( 'canvon_fb_premium_activated_banner' );
    delete_option( 'canvon_fb_show_premium_activated_banner' );
    wp_safe_redirect( admin_url( 'admin.php?page=canvon-floating-buttons' ) );
    exit;
} );
// Define plugin constants
define( 'CANVON_FB_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'CANVON_FB_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
// Load core files
require_once CANVON_FB_PLUGIN_DIR . 'includes/admin-menu.php';
require_once CANVON_FB_PLUGIN_DIR . 'includes/settings.php';
require_once CANVON_FB_PLUGIN_DIR . 'includes/frontend-display.php';
if ( function_exists( 'canvon_fb_fs' ) && canvon_fb_fs()->is__premium_only() ) {
    $canvon_fb_premium_bootstrap = CANVON_FB_PLUGIN_DIR . 'premium/bootstrap.php';
    if ( file_exists( $canvon_fb_premium_bootstrap ) ) {
        require_once $canvon_fb_premium_bootstrap;
    }
}
/**
 * Enqueue admin assets.
 */
function canvon_fb_enqueue_admin_scripts(  $canvon_fb_hook  ) {
    $canvon_fb_plugin_admin_hooks = array('toplevel_page_canvon-floating-buttons', 'canvon-floating-buttons_page_canvon-floating-buttons-appearance');
    if ( !in_array( $canvon_fb_hook, $canvon_fb_plugin_admin_hooks, true ) && !canvon_fb_is_freemius_pricing_request() ) {
        return;
    }
    wp_enqueue_style(
        'canvon-fb-admin-style',
        CANVON_FB_PLUGIN_URL . 'admin/css/admin.css',
        array(),
        filemtime( CANVON_FB_PLUGIN_DIR . 'admin/css/admin.css' )
    );
    wp_register_script(
        'canvon-fb-admin-script',
        false,
        array('jquery'),
        '1.0.0',
        true
    );
    wp_enqueue_script( 'canvon-fb-admin-script' );
    if ( canvon_fb_is_freemius_pricing_request() ) {
        wp_add_inline_style( 'canvon-fb-admin-style', '#fs_pricing_app .fs-section--custom-implementation{display:none!important;}' . '#fs_pricing_app .fs-plugin-title-and-logo{justify-content:center!important;gap:0!important;}' . '#fs_pricing_app .fs-plugin-title-and-logo .fs-plugin-logo{display:none!important;}' );
    }
    if ( 'toplevel_page_canvon-floating-buttons' === $canvon_fb_hook ) {
        wp_enqueue_script( 'jquery-ui-sortable' );
        wp_enqueue_media();
    }
}

add_action( 'admin_enqueue_scripts', 'canvon_fb_enqueue_admin_scripts' );
/**
 * Live Preview: save unsaved form settings to a transient and return a preview URL.
 */
function canvon_fb_ajax_save_preview() {
    check_ajax_referer( 'canvon_fb_live_preview', 'nonce' );
    if ( !current_user_can( 'manage_options' ) ) {
        wp_send_json_error( 'Unauthorized' );
    }
    $canvon_fb_token = wp_generate_password( 12, false );
    $canvon_fb_data = array(
        'canvon_fb_selected_platforms'    => sanitize_text_field( wp_unslash( $_POST['canvon_fb_selected_platforms'] ?? get_option( 'canvon_fb_selected_platforms', '' ) ) ),
        'canvon_fb_button_position'       => sanitize_text_field( wp_unslash( $_POST['canvon_fb_button_position'] ?? get_option( 'canvon_fb_button_position', 'right' ) ) ),
        'canvon_fb_button_size'           => sanitize_text_field( wp_unslash( $_POST['canvon_fb_button_size'] ?? get_option( 'canvon_fb_button_size', 'M' ) ) ),
        'canvon_fb_button_shape'          => sanitize_text_field( wp_unslash( $_POST['canvon_fb_button_shape'] ?? get_option( 'canvon_fb_button_shape', 'round' ) ) ),
        'canvon_fb_button_color'          => sanitize_hex_color( wp_unslash( $_POST['canvon_fb_button_color'] ?? get_option( 'canvon_fb_button_color', '#0D99FF' ) ) ),
        'canvon_fb_widget_icon'           => sanitize_text_field( wp_unslash( $_POST['canvon_fb_widget_icon'] ?? get_option( 'canvon_fb_widget_icon', 'info' ) ) ),
        'canvon_fb_widget_icon_text'      => sanitize_text_field( wp_unslash( $_POST['canvon_fb_widget_icon_text'] ?? get_option( 'canvon_fb_widget_icon_text', '' ) ) ),
        'canvon_fb_widget_icon_text_show' => rest_sanitize_boolean( $_POST['canvon_fb_widget_icon_text_show'] ?? false ),
        'canvon_fb_wechat_qr_code_id'     => absint( $_POST['canvon_fb_wechat_qr_code_id'] ?? get_option( 'canvon_fb_wechat_qr_code_id', 0 ) ),
        'canvon_fb_wechat_qr_code_url'    => esc_url_raw( wp_unslash( $_POST['canvon_fb_wechat_qr_code_url'] ?? get_option( 'canvon_fb_wechat_qr_code_url', '' ) ) ),
    );
    $canvon_fb_data = apply_filters( 'canvon_fb_live_preview_data', $canvon_fb_data );
    // Save all platform URLs so the preview reflects unsaved channel selections
    $canvon_fb_all_platforms = array(
        'phone',
        'whatsapp',
        'line',
        'wechat',
        'kakao',
        'discord',
        'email',
        'tiktok',
        'twitter',
        'linkedin',
        'threads',
        'facebook',
        'instagram',
        'youtube'
    );
    foreach ( $canvon_fb_all_platforms as $canvon_fb_p ) {
        $canvon_fb_platform_url_field = 'canvon_fb_' . $canvon_fb_p . '_url';
        $canvon_fb_raw_platform_value = get_option( $canvon_fb_platform_url_field, '' );
        if ( isset( $_POST[$canvon_fb_platform_url_field] ) ) {
            $canvon_fb_raw_platform_value = sanitize_text_field( wp_unslash( $_POST[$canvon_fb_platform_url_field] ) );
        }
        $canvon_fb_data['canvon_fb_' . $canvon_fb_p . '_url'] = ( function_exists( 'canvon_fb_sanitize_platform_value' ) ? canvon_fb_sanitize_platform_value( $canvon_fb_raw_platform_value, $canvon_fb_p ) : sanitize_text_field( $canvon_fb_raw_platform_value ) );
        $canvon_fb_show_on_value = sanitize_text_field( wp_unslash( $_POST['canvon_fb_' . $canvon_fb_p . '_show_on'] ?? get_option( 'canvon_fb_' . $canvon_fb_p . '_show_on', 'both' ) ) );
        $canvon_fb_data['canvon_fb_' . $canvon_fb_p . '_show_on'] = ( function_exists( 'canvon_fb_sanitize_show_on_value' ) ? canvon_fb_sanitize_show_on_value( $canvon_fb_show_on_value ) : $canvon_fb_show_on_value );
    }
    set_transient( 'canvon_fb_preview_' . $canvon_fb_token, $canvon_fb_data, 30 * MINUTE_IN_SECONDS );
    wp_send_json_success( array(
        'url' => add_query_arg( 'canvon_fb_preview', $canvon_fb_token, home_url( '/' ) ),
    ) );
}

add_action( 'wp_ajax_canvon_fb_save_preview', 'canvon_fb_ajax_save_preview' );
/**
 * Render the settings page
 */
function canvon_fb_render_settings_page() {
    if ( !current_user_can( 'manage_options' ) ) {
        return;
    }
    require_once CANVON_FB_PLUGIN_DIR . 'admin/views/settings-page.php';
}
