<?php

/**
 * Handles the custom meta box for the Notification builder.
 *
 * @package    Surftrust
 * @subpackage Surftrust/admin
 */
class Surftrust_Metabox
{

    /**
     * Hook into WordPress to add the meta box and save its data.
     */
    public function __construct()
    {
        add_action('add_meta_boxes', array($this, 'add_meta_box'));
        add_action('save_post_st_notification', array($this, 'save_meta_box'));
    }


    /**
     * Add the meta box to the 'st_notification' CPT edit screen.
     */
    public function add_meta_box()
    {
        add_meta_box(
            'surftrust_builder_metabox',
            'Notification Builder',
            array($this, 'render_meta_box'),
            'st_notification',
            'normal',
            'high'
        );
    }

    /**
     * Render the HTML for the meta box.
     */
    public function render_meta_box($post)
    {
        wp_nonce_field('surftrust_save_meta_box_data', 'surftrust_meta_box_nonce');
        echo '<div id="surftrust-builder-app"></div>';
    }

    /**
     * Save the meta box data when the post is saved.
     *
     * @param int $post_id The ID of the post being saved.
     */
    public function save_meta_box($post_id)
    {
        // 1. Standard Security Checks
        if (!isset($_POST['surftrust_meta_box_nonce']) || !wp_verify_nonce(sanitize_text_field( wp_unslash ($_POST['surftrust_meta_box_nonce'])), 'surftrust_save_meta_box_data')) {
            return;
        }
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
        if (!isset($_POST['_surftrust_settings'])) {
            return;
        }

        // 2. Decode Data
        $raw_data = json_decode(wp_unslash($_POST['_surftrust_settings']), true);
        if (!is_array($raw_data)) {
            return;
        }

       // error_log('[PHASE 2A] save_meta_box: Received RAW data from browser: ' . print_r($raw_data, true));
        // 3. Prepare Sanitized Array
        $sanitized_settings = [];
        if (!empty($raw_data['type'])) {
            $sanitized_settings['type'] = sanitize_text_field($raw_data['type']);
        } else {
            return; // Exit if no type is set.
        }
        $type = $sanitized_settings['type'];

        // 4. Sanitize All Data
        $sanitize_display_rules = function ($rules_raw) {
            $sanitized = [];
            if (!empty($rules_raw['show_on']) && is_array($rules_raw['show_on'])) {
                foreach ($rules_raw['show_on'] as $post) {
                    if (isset($post['id']) && isset($post['title'])) {
                        $sanitized['show_on'][] = ['id' => absint($post['id']), 'title' => sanitize_text_field($post['title'])];
                    }
                }
            }
            if (!empty($rules_raw['hide_on']) && is_array($rules_raw['hide_on'])) {
                foreach ($rules_raw['hide_on'] as $post) {
                    if (isset($post['id']) && isset($post['title'])) {
                        $sanitized['hide_on'][] = ['id' => absint($post['id']), 'title' => sanitize_text_field($post['title'])];
                    }
                }
            }
            return $sanitized;
        };

        // Sanitize each notification type's specific content
        if ($type === 'sale' && isset($raw_data['sales_notification'])) {
            $data_to_sanitize = $raw_data['sales_notification'];
            $sanitized = []; // Create a local array to build the settings.

            // All lines now write to the local `$sanitized` array.
            if (isset($data_to_sanitize['message'])) {
                $sanitized['message'] = sanitize_textarea_field($data_to_sanitize['message']);
            }
            if (isset($data_to_sanitize['display_rules'])) {
                $sanitized['display_rules'] = $sanitize_display_rules($data_to_sanitize['display_rules']);
            }

            // Assign the complete object at the end.
            $sanitized_settings['sales_notification'] = $sanitized;
        }
        if ($type === 'review' && isset($raw_data['review_displays'])) {
            $data_to_sanitize = $raw_data['review_displays'];
            $sanitized_settings['review_displays']['message'] = sanitize_textarea_field($data_to_sanitize['message']);
            $sanitized_settings['review_displays']['min_rating'] = absint($data_to_sanitize['min_rating']);
            if (isset($data_to_sanitize['display_rules'])) {
                $sanitized_settings['review_displays']['display_rules'] = $sanitize_display_rules($data_to_sanitize['display_rules']);
            }
        }
        if ($type === 'stock' && isset($raw_data['low_stock_alert'])) {
            $data_to_sanitize = $raw_data['low_stock_alert'];
            $sanitized = []; // We will build all settings in this local array first.

            // FIX: ALL lines now correctly write to the SAME local `$sanitized` array.
            if (isset($data_to_sanitize['message'])) $sanitized['message'] = sanitize_textarea_field($data_to_sanitize['message']);
            if (isset($data_to_sanitize['threshold'])) $sanitized['threshold'] = absint($data_to_sanitize['threshold']);
            if (isset($data_to_sanitize['source'])) $sanitized['source'] = sanitize_key($data_to_sanitize['source']);
            if (isset($data_to_sanitize['selected_product_id'])) $sanitized['selected_product_id'] = absint($data_to_sanitize['selected_product_id']);

            if (isset($data_to_sanitize['display_rules'])) {
                $sanitized['display_rules'] = $sanitize_display_rules($data_to_sanitize['display_rules']);
            }

            // FIX: Finally, we assign the COMPLETE local array to the main settings array in one step.
            $sanitized_settings['low_stock_alert'] = $sanitized;
        }

        if ($type === 'sale_announcement' && isset($raw_data['sale_announcement'])) {
            $data_to_sanitize = $raw_data['sale_announcement'];
            $sanitized = [];

            if (isset($data_to_sanitize['message'])) $sanitized['message'] = sanitize_textarea_field($data_to_sanitize['message']);

            // Deal Card Fields
            if (isset($data_to_sanitize['manual_sale_price'])) $sanitized['manual_sale_price'] = sanitize_text_field($data_to_sanitize['manual_sale_price']);
            if (isset($data_to_sanitize['manual_regular_price'])) $sanitized['manual_regular_price'] = sanitize_text_field($data_to_sanitize['manual_regular_price']);
            if (isset($data_to_sanitize['manual_discount'])) $sanitized['manual_discount'] = sanitize_text_field($data_to_sanitize['manual_discount']);

            //Display Position
            if (isset($data_to_sanitize['display_position'])) {
                $allowed_positions = ['top-bar', 'bottom-bar', 'top-left', 'top-right', 'bottom-left', 'bottom-right'];
                if (in_array($data_to_sanitize['display_position'], $allowed_positions)) {
                    $sanitized['display_position'] = $data_to_sanitize['display_position'];
                }
            }

            // Urgency Banner Fields
            if (isset($data_to_sanitize['link_type'])) $sanitized['link_type'] = sanitize_key($data_to_sanitize['link_type']);
            if (isset($data_to_sanitize['selected_category_id'])) $sanitized['selected_category_id'] = absint($data_to_sanitize['selected_category_id']);
            if (isset($data_to_sanitize['selected_product_id'])) $sanitized['selected_product_id'] = absint($data_to_sanitize['selected_product_id']);

            // Sanitize Timer Toggle
            $sanitized['timer_enabled'] = !empty($data_to_sanitize['timer_enabled']);

            // Sanitize Timer Type (fixed or evergreen)
            if (isset($data_to_sanitize['timer_type'])) {
                $sanitized['timer_type'] = in_array($data_to_sanitize['timer_type'], ['fixed', 'evergreen']) ? $data_to_sanitize['timer_type'] : 'fixed';
            }

            // Sanitize the Fixed End Date
            if (isset($data_to_sanitize['timer_end_date'])) {
                $sanitized['timer_end_date'] = sanitize_text_field($data_to_sanitize['timer_end_date']);
            }

            // Sanitize Evergreen Timer values
            if (isset($data_to_sanitize['timer_evergreen_hours'])) {
                $sanitized['timer_evergreen_hours'] = absint($data_to_sanitize['timer_evergreen_hours']);
            }
            if (isset($data_to_sanitize['timer_evergreen_minutes'])) {
                $sanitized['timer_evergreen_minutes'] = absint($data_to_sanitize['timer_evergreen_minutes']);
            }
            $sanitized['is_sticky'] = !empty($data_to_sanitize['is_sticky']);

            // --- BUG FIX: ADDED SANITIZATION FOR CTA BUTTON FIELDS ---
            // Sanitize the boolean toggle for enabling the button
            $sanitized['cta_button_enabled'] = !empty($data_to_sanitize['cta_button_enabled']);
            // Sanitize the text field for the button's label
            if (isset($data_to_sanitize['cta_button_text'])) {
                $sanitized['cta_button_text'] = sanitize_text_field($data_to_sanitize['cta_button_text']);
            }
            // --- END OF BUG FIX ---
            if (isset($data_to_sanitize['display_rules'])) {
                $sanitized['display_rules'] = $sanitize_display_rules($data_to_sanitize['display_rules']);
            }
            $sanitized_settings['sale_announcement'] = $sanitized;
        }



        if ($type === 'cookie_notice' && isset($raw_data['cookie_notice'])) {
            $data_to_sanitize = $raw_data['cookie_notice'];
            $sanitized_settings['cookie_notice']['message'] = sanitize_textarea_field($data_to_sanitize['message']);
            $sanitized_settings['cookie_notice']['button_text'] = sanitize_text_field($data_to_sanitize['button_text']);
            if (isset($data_to_sanitize['display_rules'])) {
                $sanitized_settings['cookie_notice']['display_rules'] = $sanitize_display_rules($data_to_sanitize['display_rules']);
            }
        }
        if ($type === 'growth_alert' && isset($raw_data['growth_alert'])) {
            $data_to_sanitize = $raw_data['growth_alert'];
            $sanitized_settings['growth_alert']['message'] = sanitize_text_field($data_to_sanitize['message']);
            $sanitized_settings['growth_alert']['enable_facebook'] = !empty($data_to_sanitize['enable_facebook']);
            $sanitized_settings['growth_alert']['enable_twitter'] = !empty($data_to_sanitize['enable_twitter']);
            $sanitized_settings['growth_alert']['enable_pinterest'] = !empty($data_to_sanitize['enable_pinterest']);
            if (isset($data_to_sanitize['display_rules'])) {
                $sanitized_settings['growth_alert']['display_rules'] = $sanitize_display_rules($data_to_sanitize['display_rules']);
            }
        }
        if ($type === 'live_visitors' && isset($raw_data['live_visitors'])) {
            $data_to_sanitize = $raw_data['live_visitors'];
            $sanitized_settings['live_visitors']['message'] = sanitize_textarea_field($data_to_sanitize['message']);
            if (isset($data_to_sanitize['display_rules'])) {
                $sanitized_settings['live_visitors']['display_rules'] = $sanitize_display_rules($data_to_sanitize['display_rules']);
            }
        }

        // Sanitize the 'customize' settings array
        if (isset($raw_data['customize']) && is_array($raw_data['customize'])) {
            foreach ($raw_data['customize'] as $key => $value) {

                // Check for colors
                if (in_array($key, ['background_color', 'font_color'])) {
                    $sanitized_settings['customize'][$key] = sanitize_hex_color($value);
                }
                // Check for device targeting
                elseif ($key === 'device_targeting') {
                    $allowed_values = ['global', 'all', 'desktop', 'mobile'];
                    if (in_array($value, $allowed_values, true)) {
                        $sanitized_settings['customize'][$key] = $value;
                    }
                }
                // Check for layout style
                elseif ($key === 'layout_style') {
                    $sanitized_settings['customize'][$key] = sanitize_key($value);
                }
                // Handle all other fields
                else {
                    $sanitized_settings['customize'][$key] = sanitize_text_field($value);
                }
            }
        }

        // Inject the Post ID
        $sanitized_settings['id'] = $post_id;
     //   error_log('[PHASE 2B] save_meta_box: Saving FINAL sanitized settings to database: ' . print_r($sanitized_settings, true));

        // 5. Save the final, clean PHP array to the database.
        update_post_meta($post_id, '_surftrust_settings', $sanitized_settings);
    }
}
