<?php

/**
 * Plugin Name: RZCPS Post Scrollers
 * Text Domain: rzcps-post-scrollers
 * Description: Creates a scrolling news marquee of posts from a specific category using a shortcode.
 * Version: 1.0.4
 * Author: rz creation
 * Author URI: https://github.com/rhfarukh
 * License: GPL2
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
if ( !function_exists( 'psp_fs' ) ) {
    // Create a helper function for easy SDK access.
    function psp_fs() {
        global $psp_fs;
        if ( !isset( $psp_fs ) ) {
            // Include Freemius SDK.
            require_once dirname( __FILE__ ) . '/vendor/freemius/start.php';
            $psp_fs = fs_dynamic_init( array(
                'id'               => '20110',
                'slug'             => 'rzcps-post-scrollers',
                'type'             => 'plugin',
                'public_key'       => 'pk_8d0437020d3a536b76c76d6784d8c',
                'is_premium'       => false,
                'is_org_compliant' => true,
                'has_addons'       => false,
                'has_paid_plans'   => false,
                'menu'             => array(
                    'first-path' => 'plugins.php',
                    'support'    => false,
                ),
                'is_live'          => true,
            ) );
        }
        return $psp_fs;
    }

    // Init Freemius.
    psp_fs();
    // Signal that SDK was initiated.
    do_action( 'psp_fs_loaded' );
}
// Define plugin version constant
if ( !defined( 'RZCPS_SCRIPT_VERSION' ) ) {
    define( 'RZCPS_SCRIPT_VERSION', '1.5.0' );
}
// Enqueue the plugin's CSS file
function rzcps_post_scrollers_enqueue_style() {
    wp_enqueue_style(
        'post-scroller-rzcps-style',
        plugin_dir_url( __FILE__ ) . 'assets/css/main.css',
        array(),
        RZCPS_SCRIPT_VERSION
    );
}

add_action( 'wp_enqueue_scripts', 'rzcps_post_scrollers_enqueue_style' );
// Enqueue the plugin's JS files
function rzcps_post_scrollers_enqueue_scripts() {
    wp_enqueue_script( 'jquery' );
    wp_enqueue_script(
        'post-scroller-rzcps-script',
        plugin_dir_url( __FILE__ ) . 'assets/js/main.js',
        array('jquery'),
        RZCPS_SCRIPT_VERSION,
        true
    );
    wp_enqueue_script(
        'post-scroller-rzcps-fade-pro-script',
        plugin_dir_url( __FILE__ ) . 'assets/js/fade-pro.js',
        array('jquery'),
        RZCPS_SCRIPT_VERSION,
        true
    );
    wp_enqueue_script(
        'post-scroller-rzcps-slide-pro-script',
        plugin_dir_url( __FILE__ ) . 'assets/js/slide-pro.js',
        array('jquery'),
        RZCPS_SCRIPT_VERSION,
        true
    );
}

add_action( 'wp_enqueue_scripts', 'rzcps_post_scrollers_enqueue_scripts' );
add_action( 'admin_enqueue_scripts', function ( $hook ) {
    // Only load on edit screen of your custom post type to avoid loading everywhere
    if ( $hook === 'post.php' || $hook === 'post-new.php' ) {
        $screen = get_current_screen();
        if ( $screen && $screen->post_type === 'rzcps_post_scrollers' ) {
            wp_enqueue_media();
            // Enqueues media uploader scripts/styles
            wp_enqueue_script( 'jquery' );
            // Admin CSS
            wp_enqueue_style(
                'post-scroller-rzcps-admin-style',
                plugin_dir_url( __FILE__ ) . 'assets/css/admin.css',
                array(),
                RZCPS_SCRIPT_VERSION
            );
            // Admin JS - reset fields
            wp_enqueue_script(
                'post-scroller-rzcps-reset-fields-script',
                plugin_dir_url( __FILE__ ) . 'assets/js/reset-fields.js',
                array('jquery'),
                RZCPS_SCRIPT_VERSION,
                true
            );
        }
    }
} );
add_action( 'init', function () {
    register_post_type( 'rzcps_post_scrollers', [
        'labels'        => [
            'name'          => 'Post Scrollers',
            'singular_name' => 'Post Scroller',
            'add_new_item'  => 'Create New Scroller',
            'edit_item'     => 'Edit Scroller',
        ],
        'public'        => false,
        'show_ui'       => true,
        'menu_position' => 6,
        'menu_icon'     => 'dashicons-admin-post',
        'supports'      => ['title'],
    ] );
} );
add_action( 'admin_menu', function () {
    if ( function_exists( 'psp_fs' ) && psp_fs()->is_free_plan() ) {
        add_submenu_page(
            'edit.php?post_type=rzcps_post_scrollers',
            // Parent slug (CPT main menu)
            'Upgrade to Pro',
            // Page title
            'Upgrade to Pro',
            // Menu title
            'manage_options',
            // Capability required
            'post_scroller_upgrade',
            // Menu slug
            function () {
                // Content of the Upgrade page
                echo '<div class="wrap"><h1>Upgrade to Pro</h1>';
                echo '<p>Click the button below to upgrade:</p>';
                echo '<a href="' . esc_url( psp_fs()->get_upgrade_url() ) . '" class="button button-primary" target="_blank" rel="noopener noreferrer">Upgrade Now</a>';
                echo '</div>';
            }
        );
    }
} );
add_action( 'add_meta_boxes', function () {
    add_meta_box(
        'scroller_settings_rzcps',
        'Scroller Settings',
        'render_scroller_meta_box_rzcps',
        'rzcps_post_scrollers',
        'normal',
        'high'
    );
} );
function render_scroller_meta_box_rzcps(  $post  ) {
    $values = get_post_meta( $post->ID, 'scroller_settings_rzcps', true );
    $show_date = ( isset( $values['show_date'] ) ? $values['show_date'] : 0 );
    $show_ticker_title = ( isset( $values['show_ticker_title'] ) ? $values['show_ticker_title'] : 0 );
    $show_item_icon = ( isset( $values['show_item_icon'] ) ? $values['show_item_icon'] : 0 );
    $show_post_image = ( isset( $values['show_post_image'] ) ? $values['show_post_image'] : 0 );
    $show_discount_percent = ( isset( $values['show_discount_percent'] ) ? $values['show_discount_percent'] : 0 );
    $rtl = ( isset( $values['rtl'] ) ? $values['rtl'] : 0 );
    $category = $values['category'] ?? '';
    $limit = $values['limit'] ?? 5;
    $scroll_speed = $values['scroll_speed'] ?? 50;
    $scroll_type = $values['scroll_type'] ?? 'horizontal';
    $content_style = $values['content_style'] ?? 'style1';
    $animation_style = $values['animation_style'] ?? 'marquee';
    $visible_items = $values['visible_items'] ?? 3;
    $group_items = $values['group_items'] ?? 4;
    $styling = $values['styling'] ?? [];
    $categories = get_categories();
    $product_category = $values['product_category'] ?? '';
    ?>

    <div class="rzcps-tabs">
        <?php 
    wp_nonce_field( 'rzcps_save_settings', 'rzcps_nonce' );
    ?>
        <div class="rzcps-tab-buttons">
            <div class="rzcps-tab-btn active" data-tab="settings">Settings</div>
            <div class="rzcps-tab-btn" data-tab="styling">Styling</div>
        </div>

        <div id="tab-settings" class="rzcps-tab-content active">
            <div class="rzcps-form-group rzcps-horizontal-group">
                <div class="title">News Ticker Title:</div>
                <div class="form-item">
                    <input type="text" name="scroller_settings_rzcps[ticker_title]" value="<?php 
    echo esc_attr( $values['ticker_title'] ?? 'News Update' );
    ?>" />
                </div>
            </div>
            <div class="rzcps-form-group rzcps-horizontal-group">
                <div class="title">Show News Ticker Title:</div>
                <div class="form-item">
                    <label>
                        <input type="checkbox" name="scroller_settings_rzcps[show_ticker_title]" value="1" <?php 
    checked( 1, $show_ticker_title );
    ?> />
                        Show News Ticker Title
                    </label>
                </div>
            </div>
            <div class="rzcps-form-group rzcps-icon-grid-group rzcps-horizontal-group">
                <div class="title">Choose Icon:</div>
                <div class="icon-grid" id="rzcps-icon-grid">
                    <?php 
    $selected_icon_id = $values['item_icon'] ?? '';
    $custom_icon_ids = get_option( 'rzcps_custom_icons', [] );
    // 1. Default icons (in plugin assets)
    $default_icons = [
        'bell.png',
        'dot.png',
        'paper.png',
        'clock.png',
        'broadcast.png',
        'compass.png',
        'idea.png'
    ];
    foreach ( $default_icons as $icon ) {
        $url = plugin_dir_url( __FILE__ ) . 'assets/icons/' . $icon;
        $checked = ( $selected_icon_id === $url ? 'checked' : '' );
        echo '<label class="rzcps-icon-item">';
        echo '<input type="radio" name="scroller_settings_rzcps[item_icon]" value="' . esc_attr( $url ) . '" ' . esc_attr( $checked ) . '>';
        echo '<img src="' . esc_url( $url ) . '" />';
        echo '</label>';
    }
    // 2. Custom uploaded icons (stored in media and option)
    foreach ( $custom_icon_ids as $attach_id ) {
        $url = wp_get_attachment_url( $attach_id );
        if ( !$url ) {
            continue;
        }
        $checked = ( $selected_icon_id == $url ? 'checked' : '' );
        echo '<label class="rzcps-icon-item custom">';
        echo '<input type="radio" name="scroller_settings_rzcps[item_icon]" value="' . esc_attr( $url ) . '" ' . esc_attr( $checked ) . '>';
        echo '<img src="' . esc_url( $url ) . '" />';
        echo '<span class="rzcps-remove-icon" data-id="' . esc_attr( $attach_id ) . '">&times;</span>';
        echo '</label>';
    }
    ?>
                </div>
                <?php 
    ?>
            </div>

            <div class="rzcps-form-group rzcps-horizontal-group">
                <div class="title">Show Item Icon:</div>
                <div class="form-item">
                    <label>
                        <input type="checkbox" name="scroller_settings_rzcps[show_item_icon]" value="1" <?php 
    checked( 1, $show_item_icon );
    ?> />
                        Show Item Icon
                    </label>
                </div>
            </div>
            <div class="rzcps-form-group">
                <div class="title">Show Post Image/Product Image:</div>
                <div class="form-item">
                    <label>
                        <input type="checkbox" name="scroller_settings_rzcps[show_post_image]" value="1" <?php 
    checked( 1, $show_post_image );
    ?> />
                        Show Post Image/Product Image
                    </label>
                </div>
            </div>
            <div class="rzcps-form-group rzcps-horizontal-group">
                <div class="title">Icon Dimensions (Width × Height in px):</div>
                <div class="form-item">
                    <input type="number" name="scroller_settings_rzcps[icon_width]" value="<?php 
    echo esc_attr( $values['icon_width'] ?? 15 );
    ?>" style="width: 80px;" min="10" /> ×
                    <input type="number" name="scroller_settings_rzcps[icon_height]" value="<?php 
    echo esc_attr( $values['icon_height'] ?? 15 );
    ?>" style="width: 80px;" min="10" />
                </div>
            </div>
            <?php 
    $post_type = $values['post_type'] ?? 'post';
    $xml_data = $values['xml_data'] ?? '';
    ?>
            <div class="rzcps-form-group">
                <div class="title">Data Source:</div>
                <div class="form-item">
                    <select name="scroller_settings_rzcps[post_type]" id="rzcps-post-type-select">
                        <option value="post" <?php 
    selected( $post_type, 'post' );
    ?>>Post</option>
                        <?php 
    ?>
                    </select>
                </div>
            </div>
            <div class="rzcps-form-group" id="rzcps-category-group" style="<?php 
    echo ( $post_type === 'post' ? '' : 'display:none;' );
    ?>">
                <div class="title">Category:</div>
                <div class="form-item">
                    <select name="scroller_settings_rzcps[category]">
                        <option value="">-- Select Category --</option>
                        <?php 
    foreach ( $categories as $cat ) {
        ?>
                            <option value="<?php 
        echo esc_attr( $cat->slug );
        ?>" <?php 
        selected( $category, $cat->slug );
        ?>><?php 
        echo esc_html( $cat->name );
        ?></option>
                        <?php 
    }
    ?>
                    </select>
                </div>
            </div>
            <!-- Product category select for 'product' -->
            <?php 
    ?>
            <div class="rzcps-form-group">
                <div class="title">Number of Posts:</div>
                <div class="form-item"><input type="number" name="scroller_settings_rzcps[limit]" value="<?php 
    echo esc_attr( $limit );
    ?>" min="1" /></div>
            </div>
            <div class="rzcps-form-group">
                <div class="title">Animation Style:</div>
                <div class="form-item">
                    <select name="scroller_settings_rzcps[animation_style]">
                        <option value="marquee" <?php 
    selected( $animation_style, 'marquee' );
    ?>>Marquee (Default)</option>
                        <option value="fade" <?php 
    selected( $animation_style, 'fade' );
    ?>>Fade In/Out</option>
                        <option value="slide" <?php 
    selected( $animation_style, 'slide' );
    ?>>Slide</option>
                    </select>
                </div>
            </div>
            <div class="rzcps-form-group">
                <div class="title">Visible Items (Fade + Vertical):</div>
                <div class="form-item"><input type="number" name="scroller_settings_rzcps[visible_items]" value="<?php 
    echo esc_attr( $visible_items );
    ?>" min="1" /></div>
            </div>
            <div class="rzcps-form-group">
                <div class="title">Group Items (For Product and Stock XML):</div>
                <div class="form-item"><input type="number" name="scroller_settings_rzcps[group_items]" value="<?php 
    echo esc_attr( $group_items );
    ?>" min="1" /></div>
            </div>
            <div class="rzcps-form-group">
                <div class="title">Scroll Speed (lower = faster):</div>
                <div class="form-item"><input type="number" name="scroller_settings_rzcps[scroll_speed]" value="<?php 
    echo esc_attr( $scroll_speed );
    ?>" min="1" /></div>
            </div>
            <div class="rzcps-form-group">
                <div class="title">Scroll Type:</div>
                <div class="form-item">
                    <select name="scroller_settings_rzcps[scroll_type]">
                        <option value="horizontal" <?php 
    selected( $scroll_type, 'horizontal' );
    ?>>Horizontal</option>
                        <option value="vertical" <?php 
    selected( $scroll_type, 'vertical' );
    ?>>Vertical</option>
                    </select>
                </div>
            </div>
            <div class="rzcps-form-group">
                <div class="title">Content Style</div>
                <div class="form-item">
                    <select name="scroller_settings_rzcps[content_style]">
                        <option value="style1" <?php 
    selected( $content_style, 'style1' );
    ?>>Style1</option>
                        <option value="style2" <?php 
    selected( $content_style, 'style2' );
    ?>>Style2</option>
                    </select>
                </div>
            </div>
            <div class="rzcps-form-group">
                <div class="title">Show Date:</div>
                <div class="form-item">
                    <label>
                        <input type="checkbox" name="scroller_settings_rzcps[show_date]" value="1" <?php 
    checked( 1, $show_date );
    ?> />
                        Show Date
                    </label>
                </div>
            </div>
            <div class="rzcps-form-group">
                <div class="title">RTL Mode:</div>
                <div class="form-item">
                    <label>
                        <input type="checkbox" name="scroller_settings_rzcps[rtl]" value="1" <?php 
    checked( $rtl );
    ?> />
                        Right‑to‑left (Arabic/Hebrew)
                    </label>
                </div>
            </div>
            <div class="rzcps-form-group">
                <div class="title">Shortcode:</div>
                <div class="form-item">
                    <code>[rzcps_post_scrollers id="<?php 
    echo esc_attr( $post->ID );
    ?>"]</code>
                </div>
            </div>

        </div>

        <div id="tab-styling" class="rzcps-tab-content">
            <div class="rzcps-form-group">
                <div class="title">Padding of Ticker(px):</div>
                <div class="form-item">
                    Top <input type="number" name="scroller_settings_rzcps[styling][padding_top]" value="<?php 
    echo esc_attr( $styling['padding_top'] ?? 0 );
    ?>" min="0" style="width: 60px;" />
                    Right <input type="number" name="scroller_settings_rzcps[styling][padding_right]" value="<?php 
    echo esc_attr( $styling['padding_right'] ?? 0 );
    ?>" min="0" style="width: 60px;" />
                    Bottom <input type="number" name="scroller_settings_rzcps[styling][padding_bottom]" value="<?php 
    echo esc_attr( $styling['padding_bottom'] ?? 0 );
    ?>" min="0" style="width: 60px;" />
                    Left <input type="number" name="scroller_settings_rzcps[styling][padding_left]" value="<?php 
    echo esc_attr( $styling['padding_left'] ?? 0 );
    ?>" min="0" style="width: 60px;" />
                </div>
            </div>
            <?php 
    function rzcps_color_input(
        $label,
        $name,
        $value,
        $extra_class = ''
    ) {
        echo '<div class="rzcps-form-group ' . esc_attr( $extra_class ) . '">';
        echo '<div class="title">' . esc_html( $label ) . ':</div>';
        echo '<div class="form-item"><input type="color" name="scroller_settings_rzcps[styling][' . esc_attr( $name ) . ']" value="' . esc_attr( $value ) . '" /></div>';
        echo '</div>';
    }

    rzcps_color_input( 'News Ticker Background Color', 'bg_color', $styling['bg_color'] ?? '#ffffff' );
    ?>
            <div class="rzcps-form-group">
                <div class="title"></div>
                <div class="form-item">
                    <button type="button" id="rzcps-reset-styling" class="button">Reset Styling</button>
                </div>
            </div>
            <?php 
    ?>
                <div class="rzcps-form-group">
                    <img 
                        style="width:100%;" 
                        src="<?php 
    echo esc_url( plugin_dir_url( __FILE__ ) . 'assets/images/settings-premium-only.jpg' );
    ?>" 
                        alt="<?php 
    esc_attr_e( 'Free Plan Image', 'rzcps-post-scrollers' );
    ?>" 
                    />
                    <div class="rzcps-overlay-custom">
                        <a 
                            class="button button-primary" 
                            href="<?php 
    echo esc_url( psp_fs()->get_upgrade_url() );
    ?>" 
                            target="_blank" 
                            rel="noopener noreferrer"
                        >
                            <?php 
    esc_html_e( 'Upgrade to Pro', 'rzcps-post-scrollers' );
    ?>
                        </a>
                    </div>
                </div>
            <?php 
    ?>    
        </div>
    </div>

    <?php 
}

add_action( 'save_post', function ( $post_id ) {
    // Verify nonce safely
    if ( !isset( $_POST['rzcps_nonce'] ) || !wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['rzcps_nonce'] ) ), 'rzcps_save_settings' ) ) {
        return;
    }
    // Prevent autosave issues
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }
    // Check user permissions
    if ( !current_user_can( 'edit_post', $post_id ) ) {
        return;
    }
    if ( isset( $_POST['scroller_settings_rzcps'] ) && is_array( $_POST['scroller_settings_rzcps'] ) ) {
        $data = [];
        $raw_data = $_POST['scroller_settings_rzcps'];
        // Handle checkboxes
        $checkboxes = [
            'show_date',
            'show_ticker_title',
            'show_item_icon',
            'show_post_image',
            'show_discount_percent'
        ];
        foreach ( $checkboxes as $cb ) {
            $data[$cb] = ( isset( $raw_data[$cb] ) ? 1 : 0 );
        }
        // Sanitize everything else
        foreach ( $raw_data as $key => $value ) {
            if ( in_array( $key, $checkboxes, true ) ) {
                continue;
            }
            if ( $key === 'xml_data' || $key === 'stock_xml_data' ) {
                $data[$key] = trim( wp_unslash( $value ) );
            } elseif ( $key === 'styling' && is_array( $value ) ) {
                $data[$key] = [
                    'bg_color'                     => sanitize_hex_color( $value['bg_color'] ?? '#ffffff' ),
                    'padding_top'                  => intval( $value['padding_top'] ?? 0 ),
                    'padding_right'                => intval( $value['padding_right'] ?? 0 ),
                    'padding_bottom'               => intval( $value['padding_bottom'] ?? 0 ),
                    'padding_left'                 => intval( $value['padding_left'] ?? 0 ),
                    'title_color'                  => sanitize_hex_color( $value['title_color'] ?? '#000000' ),
                    'title_background_color'       => sanitize_hex_color( $value['title_background_color'] ?? '#1E8005' ),
                    'item_title_color'             => sanitize_hex_color( $value['item_title_color'] ?? '#000000' ),
                    'content_color'                => sanitize_hex_color( $value['content_color'] ?? '#333333' ),
                    'date_color'                   => sanitize_hex_color( $value['date_color'] ?? '#999999' ),
                    'title_size'                   => intval( $value['title_size'] ?? 14 ),
                    'item_title_size'              => intval( $value['item_title_size'] ?? 13 ),
                    'content_size'                 => intval( $value['content_size'] ?? 12 ),
                    'date_size'                    => intval( $value['date_size'] ?? 10 ),
                    'xml_link_color'               => sanitize_hex_color( $value['xml_link_color'] ?? '#0066cc' ),
                    'xml_link_size'                => intval( $value['xml_link_size'] ?? 12 ),
                    'old_price_color'              => sanitize_hex_color( $value['old_price_color'] ?? '#d9534f' ),
                    'new_price_color'              => sanitize_hex_color( $value['new_price_color'] ?? '#1E8005' ),
                    'old_price_size'               => intval( $value['old_price_size'] ?? 12 ),
                    'new_price_size'               => intval( $value['new_price_size'] ?? 12 ),
                    'product_regular_price_color'  => sanitize_hex_color( $value['product_regular_price_color'] ?? '#666666' ),
                    'product_sale_price_color'     => sanitize_hex_color( $value['product_sale_price_color'] ?? '#c0392b' ),
                    'product_regular_price_size'   => intval( $value['product_regular_price_size'] ?? 12 ),
                    'product_sale_price_size'      => intval( $value['product_sale_price_size'] ?? 12 ),
                    'title_weight'                 => sanitize_text_field( $value['title_weight'] ?? '500' ),
                    'item_title_weight'            => sanitize_text_field( $value['item_title_weight'] ?? '500' ),
                    'content_weight'               => sanitize_text_field( $value['content_weight'] ?? '400' ),
                    'date_weight'                  => sanitize_text_field( $value['date_weight'] ?? '400' ),
                    'xml_link_weight'              => sanitize_text_field( $value['xml_link_weight'] ?? '400' ),
                    'old_price_weight'             => sanitize_text_field( $value['old_price_weight'] ?? '400' ),
                    'new_price_weight'             => sanitize_text_field( $value['new_price_weight'] ?? '400' ),
                    'product_regular_price_weight' => sanitize_text_field( $value['product_regular_price_weight'] ?? '400' ),
                    'product_sale_price_weight'    => sanitize_text_field( $value['product_sale_price_weight'] ?? '400' ),
                ];
            } else {
                $data[$key] = ( is_array( $value ) ? array_map( 'sanitize_text_field', $value ) : sanitize_text_field( $value ) );
            }
        }
        // Save cleaned data
        update_post_meta( $post_id, 'scroller_settings_rzcps', $data );
        // Clear cached product IDs
        $cache_key = 'rzcps_products_' . md5( serialize( $data ) );
        delete_transient( $cache_key );
    }
} );
// Helper function to recursively sanitize an array
function array_map_recursive(  $callback, $array  ) {
    $result = [];
    foreach ( $array as $key => $value ) {
        $result[$key] = ( is_array( $value ) ? array_map_recursive( $callback, $value ) : call_user_func( $callback, $value ) );
    }
    return $result;
}

// Add a new "Shortcode" column to the post_scroller admin list table
add_filter( 'manage_rzcps_post_scrollers_posts_columns', function ( $columns ) {
    // Temporarily store and remove 'date' column
    $date = $columns['date'];
    unset($columns['date']);
    // Add our custom shortcode column
    $columns['shortcode'] = 'Shortcode';
    // Add 'date' column back at the end
    $columns['date'] = $date;
    return $columns;
} );
// Populate the "Shortcode" column with the actual shortcode
add_action(
    'manage_rzcps_post_scrollers_posts_custom_column',
    function ( $column, $post_id ) {
        if ( $column === 'shortcode' ) {
            echo '<code>[rzcps_post_scrollers id="' . esc_attr( $post_id ) . '"]</code>';
        }
    },
    10,
    2
);
function rzcps_format_price_plain(  $price_number  ) {
    // Format price to HTML string
    $formatted = wc_price( $price_number );
    // Strip all HTML tags except the currency symbol (which may be a text or entity)
    // WooCommerce outputs <span class="woocommerce-Price-amount amount">...<span class="woocommerce-Price-currencySymbol">৳</span></span>
    // We want to keep currency symbol text but remove spans
    $formatted = strip_tags( $formatted );
    // If you want to keep currency symbol, just stripping tags is usually enough,
    // but if currency symbol is entity encoded, this preserves it.
    return $formatted;
}

function rzcps_get_discount_percent(  $regular_price, $sale_price  ) {
    if ( $regular_price > 0 && $sale_price < $regular_price ) {
        return round( ($regular_price - $sale_price) / $regular_price * 100 );
    }
    return 0;
}

// Register shortcode
add_shortcode( 'rzcps_post_scrollers', function ( $atts ) {
    $atts = shortcode_atts( [
        'id' => 0,
    ], $atts );
    $post_id = intval( $atts['id'] );
    $settings = get_post_meta( $post_id, 'scroller_settings_rzcps', true );
    if ( !$settings ) {
        return '<p>Invalid scroller ID.</p>';
    }
    $ticker_title = esc_html( $settings['ticker_title'] ?? 'News Update' );
    $thumbnail_width = ( isset( $settings['thumbnail_width'] ) ? intval( $settings['thumbnail_width'] ) : 60 );
    $thumbnail_height = ( isset( $settings['thumbnail_height'] ) ? intval( $settings['thumbnail_height'] ) : 60 );
    $animation_style = $settings['animation_style'] ?? 'marquee';
    $visible_items = $settings['visible_items'] ?? 3;
    $group_items = $settings['group_items'] ?? 4;
    $scroll_type = $settings['scroll_type'] ?? 'horizontal';
    $scroll_class = ( $scroll_type === 'vertical' ? 'vertical' : 'horizontal' );
    $content_style = $settings['content_style'] ?? 'style1';
    $show_date = isset( $settings['show_date'] ) && $settings['show_date'] == 1;
    $show_ticker_title = isset( $settings['show_ticker_title'] ) && $settings['show_ticker_title'] == 1;
    $show_item_icon = isset( $settings['show_item_icon'] ) && $settings['show_item_icon'] == 1;
    $show_post_image = isset( $settings['show_post_image'] ) && $settings['show_post_image'] == 1;
    $post_type = $settings['post_type'] ?? 'post';
    // new: post or xml
    $show_discount_percent = isset( $settings['show_discount_percent'] ) && $settings['show_discount_percent'] == 1;
    $styling = $settings['styling'] ?? [];
    $bg_color = esc_attr( $styling['bg_color'] ?? '#ffffff' );
    $padding_top = intval( $styling['padding_top'] ?? 0 );
    $padding_right = intval( $styling['padding_right'] ?? 0 );
    $padding_bottom = intval( $styling['padding_bottom'] ?? 0 );
    $padding_left = intval( $styling['padding_left'] ?? 0 );
    $padding_style = "padding: {$padding_top}px {$padding_right}px {$padding_bottom}px {$padding_left}px;";
    // --- default values (free version) ---
    $title_color = '#000000';
    $title_background_color = '#1E8005';
    $title_size = 14;
    $title_weight = '500';
    $item_title_color = '#000000';
    $item_title_size = 13;
    $item_title_weight = '500';
    $content_color = '#333333';
    $content_size = 12;
    $content_weight = '400';
    $date_color = '#999999';
    $date_size = 10;
    $date_weight = '400';
    $is_rtl = !empty( $settings['rtl'] );
    $rtl_class = ( $is_rtl ? 'rtl' : '' );
    $rtl_data = ( $is_rtl ? '1' : '0' );
    ob_start();
    if ( $scroll_class === 'horizontal' && !empty( $settings['item_icon'] ) ) {
        $icon_url = esc_url( $settings['item_icon'] );
        $icon_width = ( isset( $settings['icon_width'] ) ? intval( $settings['icon_width'] ) : 15 );
        $icon_height = ( isset( $settings['icon_height'] ) ? intval( $settings['icon_height'] ) : 15 );
    }
    if ( $post_type === 'post' ) {
        // 1.  How many posts per slide?
        $group_size = intval( $group_items ?? 1 );
        // default 1 if not set
        // 2.  Fetch the posts
        $args = [
            'category_name'  => $settings['category'] ?? '',
            'posts_per_page' => intval( $settings['limit'] ?? 5 ),
            'orderby'        => 'date',
            'order'          => 'DESC',
        ];
        $query = new WP_Query($args);
        if ( $query->have_posts() ) {
            /* -------- container markup -------- */
            echo '<div class="rzcps-wrapper" style="background-color:' . esc_attr( $bg_color ) . '; ' . esc_attr( $padding_style ) . '"><div class="rzcps-container ' . esc_attr( $scroll_class ) . ' ' . esc_attr( $animation_style ) . ' ' . esc_attr( $rtl_class ) . '"' . ' data-speed="' . esc_attr( $settings['scroll_speed'] ) . '"' . ' data-visible="' . esc_attr( $visible_items ) . '"' . ' data-rtl="' . esc_attr( $rtl_data ) . '"' . ' style="background-color:' . esc_attr( $bg_color ) . ';">';
            if ( $scroll_class === 'horizontal' && !empty( $show_ticker_title ) ) {
                echo '<div class="rzcps-title" style="color:' . esc_attr( $title_color ) . '; background-color:' . esc_attr( $title_background_color ) . '; font-size:' . esc_attr( $title_size ) . 'px; font-weight:' . esc_attr( $title_weight ) . ';">' . esc_html( $ticker_title ) . '</div>';
            }
            echo '<div class="rzcps">';
            /* -------- collect posts so we can loop in groups -------- */
            $posts_array = [];
            while ( $query->have_posts() ) {
                $query->the_post();
                $posts_array[] = get_post();
            }
            $total_posts = count( $posts_array );
            /* -------- output in groups of $group_size -------- */
            for ($i = 0; $i < $total_posts; $i += $group_size) {
                echo '<div class="item"><div class="content grouped" style="--cols:' . esc_attr( $group_size ) . ';">';
                for ($j = $i; $j < $i + $group_size && $j < $total_posts; $j++) {
                    $post_obj = $posts_array[$j];
                    setup_postdata( $post_obj );
                    echo '<a href="' . esc_url( get_permalink( $post_obj->ID ) ) . '" class="group-item">';
                    /* optional leading icon */
                    if ( $scroll_class === 'horizontal' && !empty( $show_item_icon ) && $icon_url ) {
                        echo '<div class="rzcps-item-icon" style="width:' . esc_attr( $icon_width ) . 'px; height:' . esc_attr( $icon_height ) . 'px;">';
                        echo '<img src="' . esc_url( $icon_url ) . '" alt="Icon" />';
                        echo '</div>';
                    }
                    echo '<div class="content-wrapper ' . esc_attr( $content_style ) . '">';
                    /* thumbnail only */
                    if ( !empty( $show_post_image ) && has_post_thumbnail( $post_obj->ID ) ) {
                        $img_url = get_the_post_thumbnail_url( $post_obj->ID, 'thumbnail' );
                        echo '<div class="thumb" style="width:' . esc_attr( $thumbnail_width ) . 'px; height:' . esc_attr( $thumbnail_height ) . 'px;">';
                        echo '<img src="' . esc_url( $img_url ) . '" alt="' . esc_attr( get_the_title( $post_obj->ID ) ) . '"/>';
                        echo '</div>';
                    }
                    echo '<div class="text-wrapper">';
                    /* title */
                    echo '<div class="item-title" style="color:' . esc_attr( $item_title_color ) . '; font-size:' . esc_attr( $item_title_size ) . 'px; font-weight:' . esc_attr( $item_title_weight ) . ';">' . esc_html( get_the_title( $post_obj->ID ) ) . '</div>';
                    /* excerpt (vertical only) */
                    $excerpt = strip_tags( get_the_excerpt( $post_obj->ID ) );
                    if ( $scroll_class === 'vertical' && !empty( $excerpt ) ) {
                        echo '<div class="excerpt" style="color:' . esc_attr( $content_color ) . '; font-size:' . esc_attr( $content_size ) . 'px; font-weight:' . esc_attr( $content_weight ) . ';">' . esc_html( $excerpt ) . '</div>';
                    }
                    /* date */
                    if ( !empty( $show_date ) && $show_date ) {
                        echo '<span class="date" style="color:' . esc_attr( $date_color ) . '; font-size:' . esc_attr( $date_size ) . 'px; font-weight:' . esc_attr( $date_weight ) . ';">' . esc_html( get_the_date( 'F, Y', $post_obj->ID ) ) . '</span>';
                    }
                    echo '</div></div></a>';
                    // .text-wrapper / .group-item
                }
                echo '</div></div>';
                // .content.grouped / .item
            }
            echo '</div></div></div>';
            // .rzcps / .rzcps-container
            wp_reset_postdata();
        } else {
            echo '<p>No posts found.</p>';
        }
    }
    return ob_get_clean();
} );