<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
/**
 * Admin settings for Navi AI Product Chat Bot.
 *
 * @package NAVIAIPR
 */

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

/**
 * Admin settings page class.
 */
class NAVIAIPR_Admin
{

    /**
     * Plugin options.
     *
     * @var array
     */
    private $naviaipr_opts;

    /**
     * Default option values.
     *
     * @var array
     */
    private $naviaipr_defaults;

    /**
     * Constructor.
     *
     * @param array $default_arr Default option values.
     * @param array $opts_arr    Current option values.
     */
    public function __construct($default_arr, $opts_arr)
    {
        add_action('admin_menu', array($this, 'naviaipr_admin_menu'));
        add_action('admin_enqueue_scripts', array($this, 'naviaipr_enqueue_admin_assets'));
        add_action('admin_init', array($this, 'naviaipr_register_settings'));
        add_action('admin_init', array($this, 'naviaipr_reset'));
        $this->naviaipr_opts = $opts_arr;
        $this->naviaipr_defaults = $default_arr;
    }


    /**
     * Register plugin settings.
     */
    public function naviaipr_register_settings()
    {
        register_setting(NAVIAIPR_OPTION_KEY, NAVIAIPR_OPTION_KEY, array($this, 'naviaipr_sanitize_options'));
    }



    /**
     * Add admin menu page under WooCommerce.
     */
    public function naviaipr_admin_menu()
    {
        add_submenu_page(
            'woocommerce',
            'Navi AI Product Chat Bot',
            'Navi AI Product Chat Bot',
            'manage_options',
            'naviaipr',
            array($this, 'naviaipr_settings_page')
        );
    }

    /**
     * Handle reset action.
     */
    public function naviaipr_reset()
    {
        $page = isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';
        $action = isset($_GET['action']) ? sanitize_text_field(wp_unslash($_GET['action'])) : '';

        if ('naviaipr' === $page && 'reset' === $action) {
            $nonce = isset($_GET['_wpnonce'])
                ? sanitize_text_field(wp_unslash($_GET['_wpnonce']))
                : '';

            if (!wp_verify_nonce($nonce, 'naviaipr_reset')) {
                wp_die(esc_html('Security check failed!'));
            }
            if (!current_user_can('manage_options')) {
                wp_die(esc_html('Access denied.'));
            }
            $sanitized_defaults = $this->naviaipr_sanitize_options($this->naviaipr_defaults);
            if (!update_option(NAVIAIPR_OPTION_KEY, $sanitized_defaults)) {

                wp_safe_redirect(admin_url('admin.php?page=naviaipr'));
                exit;
            }

            wp_safe_redirect(admin_url('admin.php?page=naviaipr'));
            exit;

        }
    }




    /**
     * Enqueue admin assets.
     *
     * @param string $hook Current admin page.
     */
    public function naviaipr_enqueue_admin_assets($hook)
    {

        if ('woocommerce_page_naviaipr' !== $hook) {
            return;
        }

        $opts = $this->naviaipr_opts;

        wp_enqueue_media();
        wp_enqueue_style('wp-color-picker');
        wp_enqueue_script('wp-color-picker');
        wp_enqueue_style('naviaipr-public-css', plugins_url('../public/css/navi-ai-product-chat-bot-public.css', __FILE__), array(), NAVIAIPR_VERSION);
        wp_register_style(
            'naviaipr-inline-css',
            false,
            array(),
            md5(wp_json_encode($opts))
        );
        wp_enqueue_style('naviaipr-inline-css');
        wp_add_inline_style('naviaipr-inline-css', wp_strip_all_tags(naviaipr_generate_dynamic_css($opts)));
        wp_enqueue_script('naviaipr-admin-js', plugins_url('/js/navi-ai-product-chat-bot-admin.js', __FILE__), array(), NAVIAIPR_VERSION, true);
        wp_enqueue_style('naviaipr-admin-css', plugins_url('/css/navi-ai-product-chat-bot-admin.css', __FILE__), array(), NAVIAIPR_VERSION);
        wp_add_inline_script(
            'wp-color-picker',
            "jQuery(function($){
                $('.settings-form .pb-color-picker').wpColorPicker({
                    palettes: true,
                    change: function(event, ui){
                        $(event.target).val(ui.color.toString());
                    },
                    clear: function(e){
                        $(e.target).val('');
                    }
                });
            });"
        );

        wp_register_script('naviaipr-media-library', false, array(), NAVIAIPR_VERSION, true);
        wp_enqueue_script('naviaipr-media-library');

        wp_add_inline_script(
            'naviaipr-media-library',
            "jQuery(document).ready(function($) {

             var media_frame;

        $('#bubble_image_upload_btn').on('click',function(e) {
            e.preventDefault();

            // If the frame exists, reopen it
            if (media_frame) {
                media_frame.open();
                return;
            }

            // Create the media frame
            media_frame = wp.media.frames.file_frame = wp.media({
                title: 'Select Image',
                button: {
                    text: 'Use this image'
                },
                multiple: false, // Set to true for multiple selection
                library: {
                    type: 'image' // Restrict to images
                }
            });

            // When an image is selected, update the input field
            media_frame.on('select', function() {
                var attachment = media_frame.state().get('selection').first().toJSON();
                $('#bubble-image-url').val(attachment.url);
                $('#bubble-image').prop('src',attachment.url);
            });

            // Open the media frame
            media_frame.open();
        });
    });"
        );
    }


    /**
     * Sanitize RGBA or hex color.
     *
     * @param string $color        Color value.
     * @param string $default_param Default fallback color.
     * @return string
     */
    private function naviaipr_sanitize_rgba_color($color, $default_param = 'rgba(0,0,0,1)')
    { // phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames
        if (empty($color)) {
            return $default_param;
        }
        $color = trim($color);

        if (strpos($color, 'rgba') !== false) {
            $color = str_replace(' ', '', $color);
            if (preg_match('/^rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),(0|0?\.\d+|1)\)$/', $color)) {
                return $color;
            }
        }

        $hex = sanitize_hex_color($color);
        if ($hex) {
            $hex = str_replace('#', '', $hex);
            if (strlen($hex) === 3) {
                $r = hexdec($hex[0] . $hex[0]);
                $g = hexdec($hex[1] . $hex[1]);
                $b = hexdec($hex[2] . $hex[2]);
            } else {
                $r = hexdec(substr($hex, 0, 2));
                $g = hexdec(substr($hex, 2, 2));
                $b = hexdec(substr($hex, 4, 2));
            }
            return "rgba($r,$g,$b,1)";
        }
        return $default_param;
    }

    /**
     * Sanitize all plugin options.
     *
     * @param array $in Raw input.
     * @return array
     */
    public function naviaipr_sanitize_options($in)
    {
        $plugin_url = plugin_dir_url(dirname(__DIR__, 1));
        $out = array();
        $out['max_results'] = intval($in['max_results'] ?? 5);
        $out['bubble_color'] = naviaipr_sanitize_rgba_color($in['bubble_color'] ?? '#1f7ae0');
        $out['bubble_text_color'] = naviaipr_sanitize_rgba_color($in['bubble_text_color'] ?? '#ffffff');
        $out['bubble_image'] = esc_url_raw($in['bubble_image'] ?? $plugin_url . 'assets/Chatbot.jpg');
        $out['bubble_hori_position'] = in_array($in['bubble_hori_position'] ?? 'right', array('right', 'left'), true) ? $in['bubble_hori_position'] : 'right';
        $out['bubble_vert_position'] = in_array($in['bubble_vert_position'] ?? 'bottom', array('top', 'bottom'), true) ? $in['bubble_vert_position'] : 'bottom';
        $out['bubble_bottom'] = max(0, intval($in['bubble_bottom'] ?? 20));
        $out['bubble_side'] = max(0, intval($in['bubble_side'] ?? 20));
        $out['header_color_from'] = naviaipr_sanitize_rgba_color($in['header_color_from'] ?? '#1f7ae0', '#1f7ae0');
        $out['header_color_to'] = naviaipr_sanitize_rgba_color($in['header_color_to'] ?? '#3fb0ff', '#3fb0ff');
        $out['header_text_color'] = naviaipr_sanitize_rgba_color($in['header_text_color'] ?? '#ffffff');
        $out['accent_color'] = naviaipr_sanitize_rgba_color($in['accent_color'] ?? '#ea1b25');
        $out['accent_text_color'] = naviaipr_sanitize_rgba_color($in['accent_text_color'] ?? '#ffffff');
        $out['panel_width'] = max(280, min(800, intval($in['panel_width'] ?? 360)));
        $out['font_family'] = sanitize_text_field($in['font_family'] ?? $this->naviaipr_defaults['font_family']);
        $out['user_msg_bg'] = naviaipr_sanitize_rgba_color($in['user_msg_bg'] ?? '#e6f0ff');
        $out['bot_msg_bg'] = naviaipr_sanitize_rgba_color($in['bot_msg_bg'] ?? '#ffffff');
        $out['bot_font_size'] = max(0, intval($in['bot_font_size'] ?? 17));
        $out['chat_layout'] = sanitize_text_field($in['chat_layout'] ?? $this->naviaipr_defaults['chat_layout']);
        $out['greeting_msg'] = sanitize_text_field($in['greeting_msg'] ?? $this->naviaipr_defaults['greeting_msg']);
        $out['chat_bg'] = naviaipr_sanitize_rgba_color($in['chat_bg'] ?? '#f7fbff');
        $out['border_radius'] = max(0, min(24, intval($in['border_radius'] ?? 12)));
        return $out;
    }

    /**
     * Render the settings page.
     */
    public function naviaipr_settings_page()
    {
        if (!current_user_can('manage_options')) {
            return;
        }
        $opts = $this->naviaipr_opts;
        $key = NAVIAIPR_OPTION_KEY;
        ?>
                <div class="wrap">
                    <h1>AI Product Chat Bot Settings</h1>

                    <form class="settings-form" method="post" action="options.php">
                        <?php settings_fields(NAVIAIPR_OPTION_KEY); ?>
                        <nav class="nav-tab-wrapper" style="margin-bottom:20px">
                            <a href="#" class="nav-tab nav-tab-active pb-tab-link"
                                data-tab="tab-bubble"><?php echo esc_html('Bubble Button'); ?></a>
                            <a href="#" class="nav-tab pb-tab-link"
                                data-tab="tab-header"><?php echo esc_html('Header'); ?></a>
                            <a href="#" class="nav-tab pb-tab-link"
                                data-tab="tab-chat"><?php echo esc_html('Chat Area'); ?></a>
                            <a href="#" class="nav-tab pb-tab-link"
                                data-tab="tab-accent"><?php echo esc_html('Buttons & Accents'); ?></a>
                            <a href="#" class="nav-tab pb-tab-link"
                                data-tab="tab-layout"><?php echo esc_html('Layout & Font'); ?></a>
                        </nav>



                        <div id="tab-bubble" class="pb-tab">
                            <p>Customize the floating chat button on your storefront.</p>
                            <table class="form-table">
                                <tr>
                                    <th>Button Image</th>
                                    <td class="bubble-image-container">
                                        <img id="bubble-image" src="<?php echo esc_url($opts['bubble_image']); ?>"
                                            style="max-width:50px; height: 50px;">
                                        <input type="button" id="bubble_image_upload_btn" value="Select Image" class="button">
                                        <input type="text" hidden id="bubble-image-url"
                                            name="<?php echo esc_attr($key); ?>[bubble_image]"
                                            value="<?php echo esc_attr($opts['bubble_image']); ?>" />
                                    </td>


                                </tr>
                                <tr>
                                    <th>Background Color</th>
                                    <td><input type="text" class="pb-color-picker" name="<?php echo esc_attr($key); ?>[bubble_color]"
                                            value="<?php echo esc_attr($opts['bubble_color']); ?>" data-alpha="true"></td>
                                </tr>
                                <tr>
                                    <th>Text Color</th>
                                    <td><input type="text" class="pb-color-picker"
                                            name="<?php echo esc_attr($key); ?>[bubble_text_color]"
                                            value="<?php echo esc_attr($opts['bubble_text_color']); ?>" data-alpha="true"></td>
                                </tr>
                                <tr>
                                    <th>Horizontal Position</th>
                                    <td>
                                        <select name="<?php echo esc_attr($key); ?>[bubble_hori_position]">
                                            <option value="right" <?php selected($opts['bubble_hori_position'], 'right'); ?>>Right side
                                            </option>
                                            <option value="left" <?php selected($opts['bubble_hori_position'], 'left'); ?>>Left side
                                            </option>
                                        </select>
                                    </td>
                                </tr>
                                <tr>
                                    <th>Vertical Position</th>
                                    <td>
                                        <select name="<?php echo esc_attr($key); ?>[bubble_vert_position]">
                                            <option value="top" <?php selected($opts['bubble_vert_position'], 'top'); ?>>Top
                                            </option>
                                            <option value="bottom" <?php selected($opts['bubble_vert_position'], 'bottom'); ?>>Bottom
                                            </option>
                                        </select>
                                    </td>
                                </tr>
                                <tr>
                                    <th>Distance from Bottom (px)</th>
                                    <td><input type="number" min="0" max="200" name="<?php echo esc_attr($key); ?>[bubble_bottom]"
                                            value="<?php echo intval($opts['bubble_bottom']); ?>" style="width:80px"></td>
                                </tr>
                                <tr>
                                    <th>Distance from Side (px)</th>
                                    <td><input type="number" min="0" max="200" name="<?php echo esc_attr($key); ?>[bubble_side]"
                                            value="<?php echo intval($opts['bubble_side']); ?>" style="width:80px"></td>
                                </tr>
                            </table>
                        </div>

                        <div id="tab-header" class="pb-tab" style="display:none">
                            <p>Customize the gradient header bar at the top of the chat panel.</p>
                            <table class="form-table">
                                <tr>
                                    <th>Gradient Start Color</th>
                                    <td><input type="text" class="pb-color-picker"
                                            name="<?php echo esc_attr($key); ?>[header_color_from]"
                                            value="<?php echo esc_attr($opts['header_color_from']); ?>" data-alpha="true"></td>
                                </tr>
                                <tr>
                                    <th>Gradient End Color</th>
                                    <td><input type="text" class="pb-color-picker" name="<?php echo esc_attr($key); ?>[header_color_to]"
                                            value="<?php echo esc_attr($opts['header_color_to']); ?>" data-alpha="true"></td>
                                </tr>
                                <tr>
                                    <th>Header Text Color</th>
                                    <td><input type="text" class="pb-color-picker"
                                            name="<?php echo esc_attr($key); ?>[header_text_color]"
                                            value="<?php echo esc_attr($opts['header_text_color']); ?>" data-alpha="true"></td>
                                </tr>
                            </table>
                        </div>

                        <div id="tab-chat" class="pb-tab" style="display:none">
                            <p>Customize message bubbles and the chat background.</p>
                            <table class="form-table">
                                <tr>
                                    <th>Chat Background Color</th>
                                    <td><input type="text" class="pb-color-picker" name="<?php echo esc_attr($key); ?>[chat_bg]"
                                            value="<?php echo esc_attr($opts['chat_bg']); ?>" data-alpha="true"></td>
                                </tr>
                                <tr>
                                    <th>User Message Bubble Color</th>
                                    <td><input type="text" class="pb-color-picker" name="<?php echo esc_attr($key); ?>[user_msg_bg]"
                                            value="<?php echo esc_attr($opts['user_msg_bg']); ?>" data-alpha="true"></td>
                                </tr>
                                <tr>
                                    <th>Bot Message Bubble Color</th>
                                    <td><input type="text" class="pb-color-picker" name="<?php echo esc_attr($key); ?>[bot_msg_bg]"
                                            value="<?php echo esc_attr($opts['bot_msg_bg']); ?>" data-alpha="true"></td>
                                </tr>
                                <tr>
                                    <th>Chat Area Font Size (px)</th>
                                    <td><input type="tel" name="<?php echo esc_attr($key); ?>[bot_font_size]"
                                            value="<?php echo esc_attr($opts['bot_font_size']); ?>" style="width: 80px;"></td>
                                </tr>
                                <tr>
                                    <th>Greeting Keywords </th>
                                    <td><textarea title="" style="resize: none;" name="<?php echo esc_attr($key); ?>[greeting_msg]"
                                            rows="8" cols="46"><?php echo esc_attr($opts['greeting_msg']); ?></textarea>
                                        <p class="description">seperate keywords with ,(comma)</p>

                                    </td>
                                </tr>
                                <tr>
                                    <th>Select Your Chat Area Layout</th>
                                    <td>
                                        <div class="layout-container">
                                            <div class="first-layout-container">
                                                <input type="radio" name="<?php echo esc_attr($key); ?>[chat_layout]" value="first"
                                                    <?php checked($opts['chat_layout'], 'first', true); ?> id="">
                                                <div class="pb-msg bot">
                                                    <div style="margin-bottom:8px;font-weight:600">Products at $100:</div>
                                                    <div class="pb-product"><img
                                                            src="<?php echo esc_url(plugin_dir_url(__FILE__) . '../assets/sample-product.png'); ?>"
                                                            alt="Protein Powder">
                                                        <div style="flex:1">
                                                            <div class="title">Protein Powder</div>
                                                            <div class="price">$100</div>
                                                            <div class="excerpt">this is protein powder .. very limited stock purchase
                                                                now.</div>
                                                        </div>
                                                        <div><a class="pb-buy" href="#" target="_blank" rel="noopener">Buy Now</a></div>
                                                    </div>
                                                </div>
                                            </div>


                                            <div class="second-layout-container">
                                                <input type="radio" name="<?php echo esc_attr($key); ?>[chat_layout]" <?php checked($opts['chat_layout'], 'second', true); ?> value="second" id="">
                                                <div class="pb-msg bot">
                                                    <div style="margin-bottom:8px;font-weight:600">Products at $100:</div>
                                                    <div class="pb-product second-layout"><img
                                                            src="<?php echo esc_url(plugin_dir_url(__FILE__) . '../assets/sample-product.png'); ?>"
                                                            alt="Protein Powder">
                                                        <div style="flex:1">
                                                            <div class="title">Protein Powder</div>
                                                            <div class="price">$100</div>
                                                            <div class="excerpt">this is protein powder .. very limited stock purchase
                                                                now.</div>
                                                        </div>
                                                        <div><a class="pb-buy" href="#" target="_blank" rel="noopener">Buy Now</a></div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>

                        <div id="tab-accent" class="pb-tab" style="display:none">
                            <p>Controls <strong>Buy Now</strong>, <strong>Send</strong> button, product price text color, and hover
                                border highlights.</p>
                            <table class="form-table">
                                <tr>
                                    <th>Accent Background Color</th>
                                    <td><input type="text" class="pb-color-picker" name="<?php echo esc_attr($key); ?>[accent_color]"
                                            value="<?php echo esc_attr($opts['accent_color']); ?>" data-alpha="true"></td>
                                </tr>
                                <tr>
                                    <th>Accent Text Color</th>
                                    <td><input type="text" class="pb-color-picker"
                                            name="<?php echo esc_attr($key); ?>[accent_text_color]"
                                            value="<?php echo esc_attr($opts['accent_text_color']); ?>" data-alpha="true"></td>
                                </tr>
                            </table>
                        </div>

                        <div id="tab-layout" class="pb-tab" style="display:none">
                            <table class="form-table">
                                <tr>
                                    <th>Panel Width (px)</th>
                                    <td>
                                        <input type="number" min="280" max="800" name="<?php echo esc_attr($key); ?>[panel_width]"
                                            value="<?php echo intval($opts['panel_width']); ?>" style="width:100px">
                                        <p class="description">Default 360px. On mobile fills width automatically.</p>
                                    </td>
                                </tr>
                                <tr>
                                    <th>Corner Radius (px)</th>
                                    <td>
                                        <input type="number" min="0" max="24" name="<?php echo esc_attr($key); ?>[border_radius]"
                                            value="<?php echo intval($opts['border_radius']); ?>" style="width:80px">
                                        <p class="description">0 = sharp, 12 = rounded (default), 24 = very round</p>
                                    </td>
                                </tr>
                                <tr>
                                    <th>Font Family</th>
                                    <td>
                                        <input type="text" name="<?php echo esc_attr($key); ?>[font_family]"
                                            value="<?php echo esc_attr($opts['font_family']); ?>" style="width:420px">
                                        <p class="description">CSS font-family string, e.g. <code>'Open Sans', sans-serif</code></p>
                                    </td>
                                </tr>
                            </table>
                        </div>
                        <div class="fm-btns" style="display: flex; column-gap: 12px; align-items: center;">
                            <?php submit_button('Save All Settings'); ?>


                            <?php
                            $reset_url = wp_nonce_url(admin_url('admin.php?page=naviaipr&action=reset'), 'naviaipr_reset');
                            ?>

                            <a href="<?php echo esc_url($reset_url); ?>" class="button button-primary">Reset</a>

                        </div>
                    </form>



                    <hr>
                    <h2>Usage Examples</h2>
                    <ul>
                        <li><em>"Product Name"</em> – Search by name</li>
                        <li><em>"$60"</em> or <em>"60"</em> – Products at exact price</li>
                        <li><em>"Product at 60"</em> – Keyword + exact price</li>
                        <li><em>"Product under $60"</em> – Price range filter</li>
                        <li><em>"Product above $50"</em> – Advanced query</li>

                    </ul>
                </div>
                <?php
    }
}

?>
