<?php
/**
 * Appearance Settings Page
 *
 * Settings page for customizing the appearance of social media buttons.
 */

// Prevent direct access
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

$canvon_fb_can_download_premium = function_exists( 'canvon_fb_can_download_premium_build' ) && canvon_fb_can_download_premium_build();
$canvon_fb_premium_banner_url = $canvon_fb_can_download_premium ?
    admin_url( 'admin.php?page=canvon-floating-buttons-account' ) :
    admin_url( 'admin.php?page=canvon-floating-buttons-pricing&billing_cycle=lifetime' );
$canvon_fb_premium_buy_url = admin_url( 'admin.php?page=canvon-floating-buttons-pricing&billing_cycle=lifetime' );
$canvon_fb_premium_banner_label = $canvon_fb_can_download_premium ?
    'Download and activate Pro →' :
    'Unlock advanced customization in Pro →';
$canvon_fb_premium_notice_restore_ajax_url = $canvon_fb_can_download_premium ? admin_url( 'admin-ajax.php' ) : '';
$canvon_fb_premium_notice_restore_nonce    = $canvon_fb_can_download_premium ? wp_create_nonce( 'canvon_fb_reshow_freemius_upgrade_notice' ) : '';
?>


<div class="wrap">
    <!-- Premium Upgrade Banner -->
    <div id="canvon-fb-premium-banner" class="canvon-fb-premium-banner" style="display: none;">
        <div style="display: flex; align-items: center; gap: 12px;">
            <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
                <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
            </svg>
            <a class="canvon-fb-premium-banner-link" href="<?php echo esc_url( $canvon_fb_premium_banner_url ); ?>" data-canvon-fb-download-premium="<?php echo $canvon_fb_can_download_premium ? '1' : '0'; ?>">
                <?php echo esc_html( $canvon_fb_premium_banner_label ); ?>
            </a>
        </div>
        <button type="button" class="canvon-fb-banner-close" onclick="document.getElementById('canvon-fb-premium-banner').style.display='none'">
            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                <line x1="18" y1="6" x2="6" y2="18"></line>
                <line x1="6" y1="6" x2="18" y2="18"></line>
            </svg>
        </button>
    </div>

    <div class="canvon-fb-settings-wrapper">
        <div class="canvon-fb-left-column">
            <div class="canvon-fb-appearance-panel">
                <div class="canvon-fb-appearance-panel-header">
                    <h1 class="canvon-fb-appearance-title">Appearance</h1>
                    <a href="<?php echo esc_url( admin_url( 'admin.php?page=canvon-floating-buttons' ) ); ?>" class="canvon-fb-secondary-link-button canvon-fb-back-link-button">
                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="19" y1="12" x2="5" y2="12"></line><polyline points="12 19 5 12 12 5"></polyline></svg>
                        Back to Buttons
                    </a>
                    <p class="canvon-fb-appearance-title-description">Customize how the buttons look and where they appear.</p>
                </div>
                <form method="post" action="options.php">
                <?php
                settings_fields('canvon_fb_appearance_settings');
                do_settings_sections('canvon_fb_appearance_settings');
                ?>

                <div class="canvon-fb-appearance-section">
                    <h2>Position</h2>

                    <div class="canvon-fb-form-field">
                        <div style="display: flex; align-items: center; gap: 15px;">
                            <div class="canvon-fb-radio-group">
                                <label class="canvon-fb-radio-option">
                                    <input type="radio"
                                           name="canvon_fb_button_position"
                                           value="left"
                                           <?php checked(get_option('canvon_fb_button_position', 'right'), 'left'); ?> />
                                    <span>Left</span>
                                </label>
                                <label class="canvon-fb-radio-option">
                                    <input type="radio"
                                           name="canvon_fb_button_position"
                                           value="right"
                                           <?php checked(get_option('canvon_fb_button_position', 'right'), 'right'); ?> />
                                    <span>Right</span>
                                </label>
                            </div>
                            <?php do_action( 'canvon_fb_appearance_position_controls' ); ?>
                        </div>
                        <?php do_action( 'canvon_fb_appearance_position_panels' ); ?>
                    </div>
                </div>

                <div class="canvon-fb-appearance-section">
                    <h2>Size</h2>

                    <div class="canvon-fb-form-field">
                        <div style="display: flex; align-items: center; gap: 15px;">
                            <div class="canvon-fb-radio-group">
                                <label class="canvon-fb-radio-option">
                                    <input type="radio"
                                           name="canvon_fb_button_size"
                                           value="S"
                                           <?php checked(get_option('canvon_fb_button_size', 'M'), 'S'); ?> />
                                    <span>S</span>
                                </label>
                                <label class="canvon-fb-radio-option">
                                    <input type="radio"
                                           name="canvon_fb_button_size"
                                           value="M"
                                           <?php checked(get_option('canvon_fb_button_size', 'M'), 'M'); ?> />
                                    <span>M</span>
                                </label>
                                <label class="canvon-fb-radio-option">
                                    <input type="radio"
                                           name="canvon_fb_button_size"
                                           value="L"
                                           <?php checked(get_option('canvon_fb_button_size', 'M'), 'L'); ?> />
                                    <span>L</span>
                                </label>
                                <label class="canvon-fb-radio-option">
                                    <input type="radio"
                                           name="canvon_fb_button_size"
                                           value="XL"
                                           <?php checked(get_option('canvon_fb_button_size', 'M'), 'XL'); ?> />
                                    <span>XL</span>
                                </label>
                            </div>
                            <?php do_action( 'canvon_fb_appearance_size_controls' ); ?>
                        </div>
                        <?php do_action( 'canvon_fb_appearance_size_panels' ); ?>
                    </div>
                </div>

                <div class="canvon-fb-appearance-section">
                    <h2>Shape</h2>

                    <div class="canvon-fb-form-field">
                        <div style="display: flex; align-items: center; gap: 15px;">
                            <div class="canvon-fb-radio-group">
                                <label class="canvon-fb-radio-option">
                                    <input type="radio"
                                           name="canvon_fb_button_shape"
                                           value="round"
                                           <?php checked(get_option('canvon_fb_button_shape', 'round'), 'round'); ?> />
                                    <span>
                                        <i class="canvon-fb-shape-icon round"></i>
                                        Round
                                    </span>
                                </label>
                                <label class="canvon-fb-radio-option">
                                    <input type="radio"
                                           name="canvon_fb_button_shape"
                                           value="square"
                                           <?php checked(get_option('canvon_fb_button_shape', 'round'), 'square'); ?> />
                                    <span>
                                        <i class="canvon-fb-shape-icon square"></i>
                                        Square
                                    </span>
                                </label>
                            </div>
                            <?php do_action( 'canvon_fb_appearance_shape_controls' ); ?>
                        </div>
                        <?php do_action( 'canvon_fb_appearance_shape_panels' ); ?>
                    </div>
                </div>

                <div class="canvon-fb-appearance-section">
                    <h2>Widget Color</h2>

                    <div class="canvon-fb-form-field">
                        <div style="display: flex; align-items: center; gap: 15px;">
                            <div class="canvon-fb-color-picker">
                                <?php
                                $canvon_fb_preset_colors = array('#0D99FF','#87C184','#FFD489','#C48FFD','#716F6F','#E11894');
                                $canvon_fb_current_color = get_option('canvon_fb_button_color', '#0D99FF');
                                foreach ($canvon_fb_preset_colors as $canvon_fb_color) {
                                    $canvon_fb_checked = (strtoupper($canvon_fb_current_color) === strtoupper($canvon_fb_color)) ? 'checked' : '';
                                    echo '<label class="canvon-fb-color-option">';
                                    echo '<input type="radio" name="canvon_fb_button_color" value="' . esc_attr($canvon_fb_color) . '" ' . esc_attr( $canvon_fb_checked ) . ' />';
                                    echo '<span class="canvon-fb-color-swatch" style="background-color: ' . esc_attr($canvon_fb_color) . ';">';
                                    echo '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>';
                                    echo '</span>';
                                    echo '</label>';
                                }
                                ?>
                            </div>
                            <?php do_action( 'canvon_fb_appearance_color_controls', $canvon_fb_current_color, $canvon_fb_preset_colors ); ?>
                        </div>
                        <?php do_action( 'canvon_fb_appearance_color_panels', $canvon_fb_current_color, $canvon_fb_preset_colors ); ?>
                    </div>
                </div>

                <div class="canvon-fb-appearance-section">
                    <h2>Widget Icon</h2>

                    <div class="canvon-fb-form-field">
                        <div style="display: flex; align-items: flex-end; gap: 21px; flex-wrap: wrap;">
                            <div class="canvon-fb-widget-icon-picker">
                                <?php
                                $canvon_fb_icons_dir = CANVON_FB_PLUGIN_DIR . 'assets/images/';
                                $canvon_fb_widget_icons = array(
                                    'info'    => file_get_contents( $canvon_fb_icons_dir . 'widget-icon-1.svg' ),
                                    'chat'    => file_get_contents( $canvon_fb_icons_dir . 'widget-icon-2.svg' ),
                                    'message' => file_get_contents( $canvon_fb_icons_dir . 'widget-icon-3.svg' ),
                                    'contact' => file_get_contents( $canvon_fb_icons_dir . 'widget-icon-4.svg' ),
                                );
                                $canvon_fb_current_icon = get_option('canvon_fb_widget_icon', 'info');

                                foreach ($canvon_fb_widget_icons as $canvon_fb_icon_key => $canvon_fb_icon_svg) {
                                    $canvon_fb_checked = ($canvon_fb_current_icon === $canvon_fb_icon_key) ? 'checked' : '';
                                    echo '<label class="canvon-fb-widget-icon-option">';
                                    echo '<div class="canvon-fb-widget-icon-display">' . wp_kses( $canvon_fb_icon_svg, canvon_fb_get_icon_kses_allowed_html() ) . '</div>';
                                    echo '<input type="radio" name="canvon_fb_widget_icon" value="' . esc_attr($canvon_fb_icon_key) . '" ' . esc_attr( $canvon_fb_checked ) . ' />';
                                    echo '</label>';
                                }
                                ?>
                                <?php do_action( 'canvon_fb_appearance_widget_icon_options', $canvon_fb_current_icon ); ?>
                            </div>
                            <?php do_action( 'canvon_fb_appearance_widget_icon_controls', $canvon_fb_current_icon ); ?>
                        </div>
                    </div>
                </div>

                <div class="canvon-fb-appearance-section">
                    <h2>Widget Icon Text</h2>

                    <div class="canvon-fb-form-field">
                        <div class="canvon-fb-widget-text-wrapper">
                            <?php $canvon_fb_widget_text = get_option('canvon_fb_widget_icon_text', ''); ?>
                            <input type="text"
                                   name="canvon_fb_widget_icon_text"
                                   class="canvon-fb-widget-text-input"
                                   value="<?php echo esc_attr($canvon_fb_widget_text); ?>"
                                   maxlength="25"
                                   placeholder="Enter text (optional)">
                            <span class="canvon-fb-char-counter">
                                <span id="canvon-fb-char-count"><?php echo absint( strlen($canvon_fb_widget_text) ); ?></span> / 25
                            </span>
                        </div>

                        <div class="canvon-fb-toggle-wrapper">
                            <span class="canvon-fb-toggle-label">Show Text</span>
                            <label class="canvon-fb-toggle-switch">
                                <input type="checkbox"
                                       name="canvon_fb_widget_icon_text_show"
                                       value="1"
                                       <?php checked(get_option('canvon_fb_widget_icon_text_show', false), true); ?> />
                                <span class="canvon-fb-toggle-slider"></span>
                            </label>
                        </div>
                    </div>
                </div>

                <div style="display: flex; justify-content: flex-end; padding: 20px 25px;">
                    <button type="submit" class="canvon-fb-save-button">Save Changes</button>
                </div>

                <div class="canvon-fb-pro-summary-banner">
                    <div class="canvon-fb-pro-summary-copy">
                        <h2>Need more control over your widget's branding?</h2>
                        <p>Canvon Floating Buttons Pro adds advanced appearance customization and branding controls for teams that need more flexibility.</p>
                    </div>
                    <a class="canvon-fb-pro-summary-button" href="<?php echo esc_url( $canvon_fb_premium_buy_url ); ?>">View Pro Features</a>
                </div>
                </form>
            </div><!-- /.canvon-fb-appearance-panel -->
        </div>

        <div class="canvon-fb-right-column">
            <?php require_once plugin_dir_path( __FILE__ ) . 'preview-section.php'; ?>
        </div>
    </div>
</div>

<?php
ob_start();
?>
jQuery(document).ready(function($) {
    function relocateFreemiusLicenseNotice() {
        var $canvon_fb_settingsWrapper = $('.canvon-fb-settings-wrapper').first();
        var $canvon_fb_notices = $('.canvon-fb-settings-wrapper .fs-notice');

        if ($canvon_fb_notices.length && $canvon_fb_settingsWrapper.length) {
            $canvon_fb_notices.addClass('canvon-fb-license-notice-row').insertBefore($canvon_fb_settingsWrapper);
        }
    }

    function focusFreemiusLicenseNotice() {
        var $canvon_fb_notice = $('.canvon-fb-license-notice-row, .fs-notice').filter(':visible').first();

        if (!$canvon_fb_notice.length) {
            return false;
        }

        $canvon_fb_notice.get(0).scrollIntoView({
            behavior: 'smooth',
            block: 'center'
        });
        $canvon_fb_notice.attr('tabindex', '-1').trigger('focus');
        return true;
    }

    function focusFreemiusLicenseNoticeAfterReload() {
        try {
            if (window.sessionStorage.getItem('canvon_fb_focus_freemius_notice') !== '1') {
                return;
            }

            window.sessionStorage.removeItem('canvon_fb_focus_freemius_notice');
        } catch (error) {
            return;
        }

        setTimeout(window.mcpFocusFreemiusLicenseNotice, 250);
        setTimeout(window.mcpFocusFreemiusLicenseNotice, 1000);
        setTimeout(window.mcpFocusFreemiusLicenseNotice, 1800);
    }

    window.mcpFocusFreemiusLicenseNotice = function() {
        relocateFreemiusLicenseNotice();
        return focusFreemiusLicenseNotice();
    };

    window.mcpShowPremiumDownloadFallbackBanner = function() {
        var banner = document.getElementById('canvon-fb-premium-banner');

        if (!banner) {
            return false;
        }

        banner.style.display = 'flex';
        banner.scrollIntoView({ behavior: 'smooth', block: 'start' });
        return true;
    };

    window.mcpRestoreFreemiusUpgradeNotice = function() {
        <?php if ( empty( $canvon_fb_premium_notice_restore_ajax_url ) || empty( $canvon_fb_premium_notice_restore_nonce ) ) : ?>
        return false;
        <?php else : ?>
        if (!window.fetch || !window.URLSearchParams) {
            return false;
        }

        var payload = new window.URLSearchParams();
        payload.set('action', 'canvon_fb_reshow_freemius_upgrade_notice');
        payload.set('nonce', '<?php echo esc_js( $canvon_fb_premium_notice_restore_nonce ); ?>');

        window.fetch('<?php echo esc_js( $canvon_fb_premium_notice_restore_ajax_url ); ?>', {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            body: payload.toString()
        }).then(function(response) {
            if (!response.ok) {
                throw new Error('Unable to restore Freemius notice.');
            }

            try {
                window.sessionStorage.setItem('canvon_fb_focus_freemius_notice', '1');
            } catch (error) {}

            window.location.reload();
        }).catch(function() {
            window.mcpShowPremiumDownloadFallbackBanner();
        });

        return true;
        <?php endif; ?>
    };

    relocateFreemiusLicenseNotice();
    setTimeout(relocateFreemiusLicenseNotice, 250);
    setTimeout(relocateFreemiusLicenseNotice, 1000);
    focusFreemiusLicenseNoticeAfterReload();

    $('.canvon-fb-premium-banner-link[data-canvon-fb-download-premium="1"]').on('click', function(event) {
        relocateFreemiusLicenseNotice();

        if (focusFreemiusLicenseNotice()) {
            event.preventDefault();
        }
    });

    var settingsWrapper = document.querySelector('.canvon-fb-settings-wrapper');
    if (settingsWrapper && window.MutationObserver) {
        var freemiusNoticeObserver = new MutationObserver(relocateFreemiusLicenseNotice);
        freemiusNoticeObserver.observe(settingsWrapper, {
            childList: true,
            subtree: true
        });
    }

    // Character counter for widget icon text
    $('.canvon-fb-widget-text-input').on('input', function() {
        var currentLength = $(this).val().length;
        $('#canvon-fb-char-count').text(currentLength);
    });

    <?php do_action( 'canvon_fb_appearance_admin_script' ); ?>

});

<?php
wp_add_inline_script( 'canvon-fb-admin-script', ob_get_clean() );
?>
