<?php
/**
 * Plugin Name: BW Sticky Settings
 * Plugin URI: https://bowdenworks.com
 * Description: Manage multiple sticky elements by class or ID with individual offsets and push-up elements. Desktop-focused with mobile disable option.
 * Version: 1.0.0
 * Author: Bowden Works
 * Author URI: https://bowdenworks.com
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */

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

class BW_Sticky_Settings {

    private static $instance = null;
    private $option_name = 'bw_sticky_settings';

    public static function get_instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        add_action( 'admin_menu', array( $this, 'add_admin_menu' ) );
        add_action( 'admin_init', array( $this, 'register_settings' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) );
        add_action( 'wp_enqueue_scripts', array( $this, 'frontend_enqueue_scripts' ) );
    }

    /**
     * Add admin menu
     */
    public function add_admin_menu() {
        add_options_page(
            __( 'BW Sticky Settings', 'bw-sticky' ),
            __( 'BW Sticky', 'bw-sticky' ),
            'manage_options',
            'bw-sticky-settings',
            array( $this, 'render_settings_page' )
        );
    }

    /**
     * Register settings
     */
    public function register_settings() {
        register_setting(
            'bw_sticky_settings_group',
            $this->option_name,
            array( $this, 'sanitize_settings' )
        );
    }

    /**
     * Sanitize settings
     */
    public function sanitize_settings( $input ) {
        $sanitized = array();

        if ( isset( $input['elements'] ) && is_array( $input['elements'] ) ) {
            foreach ( $input['elements'] as $key => $element ) {
                if ( empty( $element['selector'] ) ) {
                    continue;
                }

                $sanitized['elements'][ $key ] = array(
                    'selector'       => sanitize_text_field( $element['selector'] ),
                    'offset'         => absint( $element['offset'] ?? 0 ),
                    'margin_bottom'  => absint( $element['margin_bottom'] ?? 0 ),
                    'push_element'   => sanitize_text_field( $element['push_element'] ?? '' ),
                    'z_index'        => absint( $element['z_index'] ?? 999 ),
                    'disable_mobile' => isset( $element['disable_mobile'] ) ? 1 : 0,
                    'mobile_breakpoint' => absint( $element['mobile_breakpoint'] ?? 1024 ),
                    'enabled'        => isset( $element['enabled'] ) ? 1 : 0,
                );
            }
            // Re-index array
            $sanitized['elements'] = array_values( $sanitized['elements'] );
        }

        return $sanitized;
    }

    /**
     * Admin scripts and styles
     */
    public function admin_enqueue_scripts( $hook ) {
        if ( 'settings_page_bw-sticky-settings' !== $hook ) {
            return;
        }

        wp_enqueue_style(
            'bw-sticky-admin',
            plugin_dir_url( __FILE__ ) . 'css/admin.css',
            array(),
            '1.0.0'
        );

        wp_enqueue_script(
            'bw-sticky-admin',
            plugin_dir_url( __FILE__ ) . 'js/admin.js',
            array( 'jquery' ),
            '1.0.0',
            true
        );
    }

    /**
     * Frontend scripts
     */
    public function frontend_enqueue_scripts() {
        $options = get_option( $this->option_name, array() );

        if ( empty( $options['elements'] ) ) {
            return;
        }

        // Filter to only enabled elements
        $enabled_elements = array_filter( $options['elements'], function( $el ) {
            return ! empty( $el['enabled'] );
        });

        if ( empty( $enabled_elements ) ) {
            return;
        }

        wp_enqueue_script(
            'bw-sticky-frontend',
            plugin_dir_url( __FILE__ ) . 'js/sticky.js',
            array(),
            '1.4.0',
            true
        );

        wp_localize_script( 'bw-sticky-frontend', 'bwStickyConfig', array(
            'elements' => array_values( $enabled_elements ),
        ));
    }

    /**
     * Render settings page
     */
    public function render_settings_page() {
        $options = get_option( $this->option_name, array() );
        $elements = $options['elements'] ?? array();
        ?>
        <div class="wrap bw-sticky-wrap">
            <h1><?php esc_html_e( 'BW Sticky Settings', 'bw-sticky' ); ?></h1>
            <p class="description"><?php esc_html_e( 'Manage multiple sticky elements with individual settings.', 'bw-sticky' ); ?></p>

            <form method="post" action="options.php">
                <?php settings_fields( 'bw_sticky_settings_group' ); ?>

                <div id="bw-sticky-elements">
                    <?php
                    if ( ! empty( $elements ) ) {
                        foreach ( $elements as $index => $element ) {
                            $this->render_element_row( $index, $element );
                        }
                    }
                    ?>
                </div>

                <p>
                    <button type="button" id="bw-add-element" class="button button-secondary">
                        + <?php esc_html_e( 'Add Sticky Element', 'bw-sticky' ); ?>
                    </button>
                </p>

                <?php submit_button(); ?>
            </form>

            <!-- Template for new elements (hidden) -->
            <script type="text/template" id="bw-element-template">
                <?php $this->render_element_row( '{{INDEX}}', array() ); ?>
            </script>
        </div>
        <?php
    }

    /**
     * Render a single element row
     */
    private function render_element_row( $index, $element ) {
        $defaults = array(
            'selector'       => '',
            'offset'         => 0,
            'margin_bottom'  => 0,
            'push_element'   => '',
            'z_index'        => 999,
            'disable_mobile' => 1,
            'mobile_breakpoint' => 1024,
            'enabled'        => 1,
        );
        $element = wp_parse_args( $element, $defaults );
        $name_prefix = $this->option_name . '[elements][' . $index . ']';
        ?>
        <div class="bw-sticky-element" data-index="<?php echo esc_attr( $index ); ?>">
            <div class="bw-sticky-element-header">
                <span class="bw-sticky-element-title">
                    <?php if ( $element['selector'] ) : ?>
                        <code><?php echo esc_html( $element['selector'] ); ?></code>
                    <?php else : ?>
                        <?php esc_html_e( 'New Sticky Element', 'bw-sticky' ); ?>
                    <?php endif; ?>
                </span>
                <label class="bw-sticky-enabled-toggle">
                    <input type="checkbox" name="<?php echo esc_attr( $name_prefix ); ?>[enabled]" value="1" <?php checked( $element['enabled'], 1 ); ?>>
                    <?php esc_html_e( 'Enabled', 'bw-sticky' ); ?>
                </label>
                <button type="button" class="bw-toggle-element button button-small">
                    <?php esc_html_e( 'Edit', 'bw-sticky' ); ?>
                </button>
                <button type="button" class="bw-remove-element button button-small button-link-delete">
                    <?php esc_html_e( 'Remove', 'bw-sticky' ); ?>
                </button>
            </div>

            <div class="bw-sticky-element-body" style="display: none;">
                <table class="form-table">
                    <tr>
                        <th scope="row">
                            <label for="<?php echo esc_attr( $name_prefix ); ?>_selector">
                                <?php esc_html_e( 'Selector', 'bw-sticky' ); ?>
                            </label>
                        </th>
                        <td>
                            <input type="text"
                                   id="<?php echo esc_attr( $name_prefix ); ?>_selector"
                                   name="<?php echo esc_attr( $name_prefix ); ?>[selector]"
                                   value="<?php echo esc_attr( $element['selector'] ); ?>"
                                   class="regular-text"
                                   placeholder="#my-element or .my-class">
                            <p class="description"><?php esc_html_e( 'CSS selector (ID or class) of the element to make sticky.', 'bw-sticky' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="<?php echo esc_attr( $name_prefix ); ?>_offset">
                                <?php esc_html_e( 'Top Offset', 'bw-sticky' ); ?>
                            </label>
                        </th>
                        <td>
                            <input type="number"
                                   id="<?php echo esc_attr( $name_prefix ); ?>_offset"
                                   name="<?php echo esc_attr( $name_prefix ); ?>[offset]"
                                   value="<?php echo esc_attr( $element['offset'] ); ?>"
                                   class="small-text"
                                   min="0"> px
                            <p class="description"><?php esc_html_e( 'Distance from the top of the viewport when sticky.', 'bw-sticky' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="<?php echo esc_attr( $name_prefix ); ?>_margin_bottom">
                                <?php esc_html_e( 'Margin Bottom', 'bw-sticky' ); ?>
                            </label>
                        </th>
                        <td>
                            <input type="number"
                                   id="<?php echo esc_attr( $name_prefix ); ?>_margin_bottom"
                                   name="<?php echo esc_attr( $name_prefix ); ?>[margin_bottom]"
                                   value="<?php echo esc_attr( $element['margin_bottom'] ); ?>"
                                   class="small-text"
                                   min="0"> px
                            <p class="description"><?php esc_html_e( 'Space below the sticky element when sticky.', 'bw-sticky' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="<?php echo esc_attr( $name_prefix ); ?>_push_element">
                                <?php esc_html_e( 'Push-up Element', 'bw-sticky' ); ?>
                            </label>
                        </th>
                        <td>
                            <input type="text"
                                   id="<?php echo esc_attr( $name_prefix ); ?>_push_element"
                                   name="<?php echo esc_attr( $name_prefix ); ?>[push_element]"
                                   value="<?php echo esc_attr( $element['push_element'] ); ?>"
                                   class="regular-text"
                                   placeholder="#footer or .site-footer">
                            <p class="description"><?php esc_html_e( 'Optional. Element that will push the sticky element up when reached.', 'bw-sticky' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="<?php echo esc_attr( $name_prefix ); ?>_z_index">
                                <?php esc_html_e( 'Z-Index', 'bw-sticky' ); ?>
                            </label>
                        </th>
                        <td>
                            <input type="number"
                                   id="<?php echo esc_attr( $name_prefix ); ?>_z_index"
                                   name="<?php echo esc_attr( $name_prefix ); ?>[z_index]"
                                   value="<?php echo esc_attr( $element['z_index'] ); ?>"
                                   class="small-text"
                                   min="1">
                            <p class="description"><?php esc_html_e( 'Stack order of the sticky element.', 'bw-sticky' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e( 'Mobile Settings', 'bw-sticky' ); ?></th>
                        <td>
                            <label>
                                <input type="checkbox"
                                       name="<?php echo esc_attr( $name_prefix ); ?>[disable_mobile]"
                                       value="1"
                                       <?php checked( $element['disable_mobile'], 1 ); ?>>
                                <?php esc_html_e( 'Disable on mobile devices', 'bw-sticky' ); ?>
                            </label>
                            <br><br>
                            <label>
                                <?php esc_html_e( 'Mobile breakpoint:', 'bw-sticky' ); ?>
                                <input type="number"
                                       name="<?php echo esc_attr( $name_prefix ); ?>[mobile_breakpoint]"
                                       value="<?php echo esc_attr( $element['mobile_breakpoint'] ); ?>"
                                       class="small-text"
                                       min="320"
                                       max="1200"> px
                            </label>
                            <p class="description"><?php esc_html_e( 'Sticky behavior disabled below this screen width.', 'bw-sticky' ); ?></p>
                        </td>
                    </tr>
                </table>
            </div>
        </div>
        <?php
    }
}

// Initialize plugin
BW_Sticky_Settings::get_instance();
