<?php declare( strict_types=1 );

/**
 * Fired during plugin activation
 *
 * @link       https://webequipe.com
 * @since      1.0.0
 *
 * @package    Webequipe_Spin_Win_Wheel
 * @subpackage Webequipe_Spin_Win_Wheel/includes
 */

/**
 * Fired during plugin activation.
 *
 * This class defines all code necessary to run during the plugin's activation.
 *
 * @since      1.0.0
 * @package    Webequipe_Spin_Win_Wheel
 * @subpackage Webequipe_Spin_Win_Wheel/includes
 * @author     Webequipe <support@webequipe.com>
 */



namespace Webequipe\SpinWinWheel;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching

/**
 * Ajax handler class
 */
class Ajax
{

    /**
         * Class constructor
         */
    public function __construct()
    {
        add_action( 'wp_ajax_wsww_email_enquiry', [ $this, 'email_enquiry'] );
        add_action( 'wp_ajax_nopriv_wsww_email_enquiry', [ $this, 'email_enquiry'] );

        add_action( 'wp_ajax_wsww_spin_win', [ $this, 'spinWinDataInsert'] );
        add_action( 'wp_ajax_nopriv_wsww_spin_win', [ $this, 'spinWinDataInsert'] );

        add_action( 'wp_ajax_wsww_claim_update', [ $this, 'claim_update'] );
        
        add_action( 'wp_ajax_wsww_spin_preview', [ $this, 'spin_preview'] );
    }

    /**
     * Handle Enquiry Submission
     *
     * @return void
     */
    public function email_enquiry() {

        check_ajax_referer( 'wsww-email-enquiry-form' );

        $email  = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : '';
        $phone  = isset( $_POST['phone'] ) ? sanitize_text_field( wp_unslash( $_POST['phone'] ) ) : '';
        $name   = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
        $display_after_same_email = isset( $_POST['display_after_same_email'] )
            ? sanitize_text_field( wp_unslash( $_POST['display_after_same_email'] ) )
            : '';

        if ( empty( $email ) ) {
            wp_send_json_error(
                [
                    'message' => esc_html__( 'Email is required.', 'webequipe-spin-win-wheel' ),
                ]
            );
        }

        $email_enquiry_data = webequipe_sww_get_email_enquiry( $email );
        $check_last_entry   = webequipe_sww_check_last_entry( $email );
        wp_send_json_success(
            [
                'message'                  => esc_html__( 'Enquiry has been sent successfully!', 'webequipe-spin-win-wheel' ),
                'email'                    => $email_enquiry_data['email'],
                'phone'                    => $phone,
                'name'                     => $name,
                'display_after_same_email' => $display_after_same_email,
                'email_rows'               => $email_enquiry_data['rows'],
                'email_found'              => $email_enquiry_data['email_found'],
                'last_entry'               => $check_last_entry,
            ]
        );

        wp_die();
    }


   /**
     * Handle Spin Win Data Submission
     *
     * @return void
     */
    public function spinWinDataInsert() {
        check_ajax_referer( 'wsww-spin-win-form' );

        $data = [];

        $data['spin_id']            = isset( $_POST['spin_id'] ) ? intval( wp_unslash( $_POST['spin_id'] ) ) : 0;
        $data['spin_label']         = isset( $_POST['spin_label'] ) ? sanitize_text_field( wp_unslash( $_POST['spin_label'] ) ) : '';
        $data['email']              = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : '';
        $data['phone']              = isset( $_POST['phone'] ) ? sanitize_text_field( wp_unslash( $_POST['phone'] ) ) : '';
        $data['name']               = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
        $data['page_url']           = isset( $_POST['page_url'] ) ? esc_url_raw( wp_unslash( $_POST['page_url'] ) ) : '';
        $data['marketing_consent']  = isset( $_POST['wsww_marketing_consent'] ) ? sanitize_text_field( wp_unslash( $_POST['wsww_marketing_consent'] ) ) : '';

        global $wpdb;

        $table = $wpdb->prefix . 'spin_emails';

        if ( empty( $data['spin_id'] ) ) {
            wp_send_json_error(
                [
                    'message' => esc_html__( 'Invalid spin wheel.', 'webequipe-spin-win-wheel' ),
                ]
            );
        }

        $spin_data = webequipe_sww_get_spin( $data['spin_id'] );
        if ( empty( $spin_data ) || is_wp_error( $spin_data ) ) {
            wp_send_json_error(
                [
                    'message' => esc_html__( 'Spin wheel not found.', 'webequipe-spin-win-wheel' ),
                ]
            );
        }

        if ( isset( $spin_data->spin_status ) && 'active' !== $spin_data->spin_status ) {
            wp_send_json_error(
                [
                    'message' => esc_html__( 'Spin wheel is not active.', 'webequipe-spin-win-wheel' ),
                ]
            );
        }

        $spins_list = [];
        if ( ! empty( $spin_data->spins ) ) {
            $decoded_spins = json_decode( $spin_data->spins, true );
            if ( is_array( $decoded_spins ) ) {
                $spins_list = $decoded_spins;
            }
        }

        $matched_spin = null;
        if ( ! empty( $spins_list ) && '' !== $data['spin_label'] ) {
            foreach ( $spins_list as $spin_item ) {
                if ( ! is_array( $spin_item ) ) {
                    continue;
                }
                $item_label = isset( $spin_item['spin_label'] ) ? sanitize_text_field( $spin_item['spin_label'] ) : '';
                if ( '' !== $item_label && $item_label === $data['spin_label'] ) {
                    $matched_spin = $spin_item;
                    break;
                }
            }
        }

        if ( $matched_spin ) {
            $data['spin_label']         = sanitize_text_field( $matched_spin['spin_label'] ?? $data['spin_label'] );
            $data['is_win']             = sanitize_text_field( $matched_spin['is_win'] ?? 'no' );
            $data['spin_value']         = sanitize_text_field( $matched_spin['spin_value'] ?? '' );
            $data['spin_item_unique_id'] = isset( $matched_spin['spin_item_unique_id'] ) ? preg_replace( '/[^0-9]/', '', (string) $matched_spin['spin_item_unique_id'] ) : '';
        } else {
            $data['is_win']     = 'no';
            $data['spin_value'] = '';
        }

        $data['send_email']         = sanitize_text_field( $spin_data->send_email ?? '' );
        $data['from_name']          = sanitize_text_field( $spin_data->from_name ?? '' );
        $data['from_address']       = sanitize_email( $spin_data->from_address ?? '' );
        $data['from_subject']       = sanitize_text_field( $spin_data->from_subject ?? '' );
        $data['from_message']       = wp_kses_post( $spin_data->from_message ?? '' );
        $data['admin_geting_email'] = sanitize_text_field( $spin_data->admin_geting_email ?? '' );

        $admin_recipient  = get_option( 'wsww_setting_options_recipient' );
        $thanks_msg       = get_option( 'wsww_setting_options_thank_u_message', __( 'Thank you! A member of our team will respond to your inquiry as soon as possible.', 'webequipe-spin-win-wheel' ) );
        $user_email_body  = get_option( 'wsww_setting_options_user_email_body' );
        $admin_email_body = get_option( 'wsww_setting_options_admin_email_body' );

        $dynamic_message = '';
        $coupon_payload  = [];

        $data['coupon_code']    = '';
        $data['coupon_applied'] = 'no';

        // Prepare DB insert, including coupon info when available.
        $data_insert = [
            'spin_id'             => $data['spin_id'],
            'spin_item_unique_id' => isset( $data['spin_item_unique_id'] ) && '' !== $data['spin_item_unique_id'] ? substr( (string) $data['spin_item_unique_id'], 0, 20 ) : null,
            'spin_label'          => $data['spin_label'],
            'email'               => $data['email'],
            'phone'               => $data['phone'],
            'name'                => $data['name'],
            'page_url'            => $data['page_url'],
            'coupon_code'         => isset( $data['coupon_code'] ) ? (string) $data['coupon_code'] : '',
            'coupon_applied'      => isset( $data['coupon_applied'] ) ? (string) $data['coupon_applied'] : '',
        ];

        $formats = [ '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' ];

        $insert_data = $wpdb->insert( $table, $data_insert, $formats );

        if ( $insert_data ) {
            $user_to           = $data['email'];
            $user_name         = $data['name'];
            $subject           = $data['from_subject'];
            $spin_label        = $data['spin_label'];
            $company_name      = get_bloginfo( 'name' );
            $company_url       = get_site_url();
            $user_body         = $data['from_message'];
            $is_win            = $data['is_win'];
            $spin_value        = $data['spin_value'];
            $user_geting_email = $data['send_email'];

            $admin_to      = $admin_recipient;
            $admin_subject = __( 'New Spin', 'webequipe-spin-win-wheel' );
            $user_phone    = $data['phone'];
            $admin_body    = is_string( $admin_email_body ) ? $admin_email_body : '';
            $try_date      = wp_date( get_option( 'date_format' ) );

            $replacements = [
                'customer_name'  => $user_name,
                'customer_phone' => $user_phone,
                'customer_email' => $user_to,
                'company_name'   => $company_name,
                'company_url'    => $company_url,
                'spin_label'     => $spin_label,
                'today'          => $try_date,
                'spin_value'     => $spin_value,
                'coupon_code'    => isset( $data['coupon_code'] ) ? (string) $data['coupon_code'] : '',
            ];

            $user_email_body = webequipe_sww_formatMessage( $user_body, $replacements );
            $is_admin_geting_email = $data['admin_geting_email'];

            $admin_email_body = str_replace(
                [ '{customer_name}', '{customer_phone}', '{customer_email}', '{company_name}', '{company_url}', '{price_value}', '{today}', '{coupon_code}' ],
                [
                    $user_name,
                    $user_phone,
                    $user_to,
                    $company_name,
                    $company_url,
                    $spin_value,
                    $try_date,
                    isset( $data['coupon_code'] ) ? (string) $data['coupon_code'] : '',
                ],
                $admin_body
            );

            $headers = [ 'Content-Type: text/html; charset=UTF-8' ];

            if ( 'yes' === $is_win && 'yes' === $user_geting_email ) {
                wp_mail( $user_to, $subject, $user_email_body, $headers );
            }

            if ( 'yes' === $is_win && 'yes' === $is_admin_geting_email && ! empty( $admin_to ) ) {
                wp_mail( $admin_to, $admin_subject, $admin_email_body, $headers );
            }
            $sync_settings_map = get_option( 'wsww_spin_sync_settings', [] );
            if ( ! is_array( $sync_settings_map ) ) {
                $sync_settings_map = [];
            }

            $sync_defaults = [
                'enabled'      => 1,
                'provider'     => 'mailchimp',
                'capture_mode' => 'both',
            ];
            $wheel_sync_settings = isset( $sync_settings_map[ $data['spin_id'] ] ) && is_array( $sync_settings_map[ $data['spin_id'] ] )
                ? wp_parse_args( $sync_settings_map[ $data['spin_id'] ], $sync_defaults )
                : $sync_defaults;

            $sync_enabled  = ! empty( $wheel_sync_settings['enabled'] );
            $sync_provider = isset( $wheel_sync_settings['provider'] ) ? sanitize_key( (string) $wheel_sync_settings['provider'] ) : 'mailchimp';
            $capture_mode  = isset( $wheel_sync_settings['capture_mode'] ) ? sanitize_key( (string) $wheel_sync_settings['capture_mode'] ) : 'both';

            $is_win_result = isset( $data['is_win'] ) && 'yes' === strtolower( (string) $data['is_win'] );
            $allow_sync_for_result = (
                'both' === $capture_mode
                || ( 'win' === $capture_mode && $is_win_result )
                || ( 'lose' === $capture_mode && ! $is_win_result )
            );

            // Attempt Mailchimp sync (non‑blocking, silent on failure).
            if ( $sync_enabled && 'mailchimp' === $sync_provider && $allow_sync_for_result && class_exists( __NAMESPACE__ . '\Mailchimp' ) ) {
                Mailchimp::maybe_subscribe_from_spin(
                    [
                        'email'   => $data['email'],
                        'name'    => $data['name'],
                        'phone'   => $data['phone'],
                        'consent' => $data['marketing_consent'],
                    ]
                );
            }
        }
        if ( ! empty( $data['spin_id'] ) ) {
            $spin_data = webequipe_sww_get_spin( $data['spin_id'] );
            if ( $spin_data && ! is_wp_error( $spin_data ) ) {
                // Get the appropriate message based on win/loss
                if ( 'yes' === $data['is_win'] ) {
                    $message_template = ! empty( $spin_data->win_message ) ? $spin_data->win_message : '';
                } else {
                    $message_template = ! empty( $spin_data->loss_message ) ? $spin_data->loss_message : '';
                }
                
                // Replace placeholders in the message
                if ( ! empty( $message_template ) ) {
                    $replacements = [
                        'label' => $data['spin_label'],
                        'value' => $data['spin_value'],
                        'coupon_code' => isset( $data['coupon_code'] ) ? (string) $data['coupon_code'] : '',
                    ];
                    $dynamic_message = webequipe_sww_formatMessage( $message_template, $replacements );
                }
            }
        }
        
        // Fallback to generic message if dynamic message is not available
        if ( empty( $dynamic_message ) ) {
            $dynamic_message = $thanks_msg;
        }

        if ( ob_get_length() ) {
            ob_clean();
        }

        wp_send_json_success(
            [
                'message'       => wp_kses_post( $dynamic_message ),
                'inserted_data' => $data,
                'coupon'        => is_array( $coupon_payload ) ? $coupon_payload : [],
            ]
        );

        wp_die();
    }

    /**
     * Handle claim update
     *
     * @return void
     */
    public function claim_update() {
        check_ajax_referer( 'wsww-claim-update-form' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error(
                [
                    'message' => esc_html__( 'No permission!', 'webequipe-spin-win-wheel' ),
                ]
            );
        }

        $id = isset( $_REQUEST['id'] ) ? intval( wp_unslash( $_REQUEST['id'] ) ) : 0;

        webequipe_sww_claim_update( $id );

        wp_send_json_success(
            [
                'message'     => esc_html__( 'Data has been updated successfully!', 'webequipe-spin-win-wheel' ),
                'update_data' => $id,
            ]
        );

        wp_die();
    }


    /**
     * Handle Spin Preview
     *
     * @return void
     */
    public function spin_preview()
    {
        check_ajax_referer( 'wsww-preview-nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( [
                'message' => __( 'No permission!', 'webequipe-spin-win-wheel' ),
            ] );
        }

        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- JSON string; validated via json_decode below.
        $form_data_raw = isset( $_POST['form_data'] ) ? wp_unslash( $_POST['form_data'] ) : '';
        if ( is_array( $form_data_raw ) ) {
            $form_data_raw = '';
        }

        $form_data = null;
        if ( ! empty( $form_data_raw ) ) {
            $form_data_raw = trim( $form_data_raw );
            $form_data     = json_decode( $form_data_raw, true );
            $json_error    = json_last_error();

            if ( JSON_ERROR_NONE === $json_error && is_array( $form_data ) ) {
                $form_data = $this->normalize_json_form_data( $form_data );
            } else {
                $form_data = null;
            }
        }
       
        // Fallback: Use direct POST data if JSON failed
        if ($form_data === null) {
            $form_data = wp_unslash( $_POST );
            
            // Remove non-form fields
            unset($form_data['action']);
            unset($form_data['_wpnonce']);
            unset($form_data['form_data']);
        }
        
        // Parse form data into spin object
        $spin = $this->parse_form_data_to_spin($form_data);
        
        // Generate preview HTML and preview config data
        $preview_result = $this->generate_preview_html( $spin );
        $preview_html   = isset( $preview_result['html'] ) ? $preview_result['html'] : '';
        $preview_config = isset( $preview_result['config'] ) ? $preview_result['config'] : [];
        
        wp_send_json_success( [
            'preview_html' => $preview_html,
            'preview_config' => $preview_config,
        ] );

        wp_die();
    }

    /**
     * Parse form data into spin object
     *
     * @param array $form_data
     * @return object
     */
    private function parse_form_data_to_spin($form_data)
    {
        // Ensure $form_data is an array
        if (!is_array($form_data)) {
            $form_data = [];
        }
        
        $spin = (object) [];
        
        // Basic settings
        $spin->spin_title = sanitize_text_field($form_data['spin_title'] ?? 'WebEquipe Spin & Win Wheel');
        $spin->spin_description = sanitize_text_field($form_data['spin_description'] ?? 'Enter your info for the chance to win!!');
        $spin->spin_status = sanitize_text_field($form_data['spin_status'] ?? 'active');
        
        // Template setting
        $spin->template_setting = sanitize_text_field($form_data['template_setting'] ?? 'spin-on-left');
        
        // Card settings
        $spin->card_background = sanitize_hex_color($form_data['card_background'] ?? '#E6F6F4');
        $spin->card_color = sanitize_hex_color($form_data['card_color'] ?? '#000000');
        $spin->card_boder_radius = intval($form_data['card_boder_radius'] ?? 0);
        $spin->card_boder_padding = intval($form_data['card_boder_padding'] ?? 15);
        
        // Wheel center settings
        $spin->wheel_center_background = sanitize_hex_color($form_data['wheel_center_background'] ?? '#fefefeff');
        $spin->wheel_center_boder_color = sanitize_hex_color($form_data['wheel_center_boder_color'] ?? '#003B33');
        $spin->wheel_center_boder_width = intval($form_data['wheel_center_boder_width'] ?? 3);
        $spin->wheel_center_image_icon = sanitize_text_field($form_data['wheel_center_image_icon'] ?? 'star');
        // carry custom URL or inline data URL into preview spin object if provided
        $custom_inline_data = isset($form_data['custom_wheel_center_image_icon_data']) ? $form_data['custom_wheel_center_image_icon_data'] : '';
        if (!empty($custom_inline_data) && is_string($custom_inline_data) && strpos($custom_inline_data, 'data:image') === 0) {
            // trust the data URL for preview only
            $spin->custom_wheel_center_image_icon = $custom_inline_data;
        } else {
            $spin->custom_wheel_center_image_icon = sanitize_text_field($form_data['existing_custom_image'] ?? ($form_data['custom_wheel_center_image_icon'] ?? ''));
        }
        
        // Wheel stroke settings
        $spin->wheel_stroke_border_color = sanitize_hex_color($form_data['wheel_stroke_border_color'] ?? '#003B33');
        $spin->wheel_stroke_border_size = intval($form_data['wheel_stroke_border_size'] ?? 5);
        $spin->wheel_stroke_font_size = intval($form_data['wheel_stroke_font_size'] ?? 20);
        $spin->wheel_stroke_font_family = sanitize_text_field($form_data['wheel_stroke_font_family'] ?? 'roboto');
        $spin->wheel_stroke_font_style = sanitize_text_field($form_data['wheel_stroke_font_style'] ?? 'bold');
        
        // Form design settings
        $spin->from_design_alinment = sanitize_text_field($form_data['from_design_alinment'] ?? 'left');
        $spin->from_button_text = sanitize_text_field($form_data['from_button_text'] ?? 'TRY YOUR LUCKY');
        $spin->from_button_color = sanitize_hex_color($form_data['from_button_color'] ?? '#FFFFFF');
        $spin->from_button_background_color = sanitize_hex_color($form_data['from_button_background_color'] ?? '#009883');
        
        // Display field settings with debugging
      
        
        if (!empty($form_data['display_field_setting'])) {
            $display_setting = (array)$form_data['display_field_setting'];
            
            // Flatten the nested array structure
            $flattened_setting = [];
            foreach ($display_setting as $item) {
                if (is_array($item)) {
                    $flattened_setting = array_merge($flattened_setting, array_values($item));
                } else {
                    $flattened_setting[] = $item;
                }
            }
            
            $spin->display_field_setting = wp_json_encode($flattened_setting);
          
        } else {
            $spin->display_field_setting = wp_json_encode(['email_field']);
        }
        
      
        
        // Initial button settings
        $spin->initial_button_text = sanitize_text_field($form_data['initial_button_text'] ?? 'Spin to win');
        $spin->initial_button_color = sanitize_hex_color($form_data['initial_button_color'] ?? '#FFFFFF');
        $spin->initial_button_background_color = sanitize_hex_color($form_data['initial_button_background_color'] ?? '#009883');
        
        // Parse spins items
        $spins_data = [];
        if (isset($form_data['spins']) && is_array($form_data['spins'])) {
            foreach ($form_data['spins'] as $spin_item) {
                if (!empty($spin_item['spin_label'])) {
                    $spins_data[] = [
                        'is_win' => sanitize_text_field($spin_item['is_win'] ?? 'no'),
                        'spin_probability' => intval($spin_item['spin_probability'] ?? 0),
                        'spin_label' => sanitize_text_field($spin_item['spin_label'] ?? ''),
                        'spin_value' => sanitize_text_field($spin_item['spin_value'] ?? ''),
                        'spin_bgcolor' => sanitize_hex_color($spin_item['spin_bgcolor'] ?? '#ffffff'),
                        'spin_textcolor' => sanitize_hex_color($spin_item['spin_textcolor'] ?? '#000000'),
                    ];
                }
            }
        }
        
        // If no spins data, use default
        if (empty($spins_data)) {
            $spins_data = [
                [
                    'is_win' => 'no',
                    'spin_probability' => 20,
                    'spin_label' => 'ZERO',
                    'spin_value' => 'ZERO',
                    'spin_bgcolor' => '#004C41',
                    'spin_textcolor' => '#FFFFFF',
                ],
                [
                    'is_win' => 'yes',
                    'spin_probability' => 10,
                    'spin_label' => '$10',
                    'spin_value' => '$10',
                    'spin_bgcolor' => '#008774',
                    'spin_textcolor' => '#000000',
                ],
                [
                    'is_win' => 'yes',
                    'spin_probability' => 10,
                    'spin_label' => '$2',
                    'spin_value' => '$2',
                    'spin_bgcolor' => '#B0E4DD',
                    'spin_textcolor' => '#000000',
                ],
                [
                    'is_win' => 'no',
                    'spin_probability' => 25,
                    'spin_label' => 'ZERO',
                    'spin_value' => 'ZERO',
                    'spin_bgcolor' => '#004C41',
                    'spin_textcolor' => '#FFFFFF',
                ]
            ];
        }
        
        $spin->spins = wp_json_encode($spins_data);
        
        return $spin;
    }

    /**
     * Generate preview HTML
     *
     * @param object $spin Spin configuration data.
     * @return array{html:string,config:array}
     */
    private function generate_preview_html($spin)
    {
        // Ensure $spin is an object with required properties
        if (!is_object($spin)) {
            $spin = (object) [];
        }
        
        // Ensure spins property exists
        if (!isset($spin->spins)) {
            $spin->spins = wp_json_encode([]);
        }
        
        ob_start();
        
        $plugin_url = plugin_dir_url( dirname( __FILE__ ) ); 
        $spins_items = json_decode($spin->spins, true);
        
        // Validate $spins_items - ensure it's always an array
        if (!is_array($spins_items)) {
            // Use default data if invalid or empty
            $spins_items = [
                [
                    'is_win' => 'no',
                    'spin_probability' => 20,
                    'spin_label' => 'ZERO',
                    'spin_value' => 'ZERO',
                    'spin_bgcolor' => '#004C41',
                    'spin_textcolor' => '#FFFFFF',
                ],
                [
                    'is_win' => 'yes',
                    'spin_probability' => 10,
                    'spin_label' => '$10',
                    'spin_value' => '$10',
                    'spin_bgcolor' => '#008774',
                    'spin_textcolor' => '#000000',
                ],
                [
                    'is_win' => 'yes',
                    'spin_probability' => 10,
                    'spin_label' => '$2',
                    'spin_value' => '$2',
                    'spin_bgcolor' => '#B0E4DD',
                    'spin_textcolor' => '#000000',
                ],
                [
                    'is_win' => 'no',
                    'spin_probability' => 25,
                    'spin_label' => 'ZERO',
                    'spin_value' => 'ZERO',
                    'spin_bgcolor' => '#004C41',
                    'spin_textcolor' => '#FFFFFF',
                ]
            ];
        }
        
        // Set up variables for preview
        $circle_size = 450;
        $arrow_icon = $plugin_url . 'assets/img/wheel-arrow.png';
        // Center icon for preview: use selected icon; if custom, use provided URL or inline data URL; fallback to default
        $wheel_center_image_icon = isset($spin->wheel_center_image_icon) ? $spin->wheel_center_image_icon : 'star';
        $center_icon = $plugin_url . 'assets/img/' . $wheel_center_image_icon . '.png';
        if (!empty($wheel_center_image_icon) && $wheel_center_image_icon === 'custom') {
            if (!empty($spin->custom_wheel_center_image_icon)) {
                // Allow inline data URLs for preview
                if (strpos($spin->custom_wheel_center_image_icon, 'data:image') === 0) {
                    $center_icon = $spin->custom_wheel_center_image_icon;
                } else {
                    $center_icon = esc_url_raw($spin->custom_wheel_center_image_icon);
                }
            } else {
                $center_icon = $plugin_url . 'assets/img/cbl_logo.png';
            }
        }
        // Keep inline data URIs untouched so the preview can show unsaved uploads.
        $center_icon_for_preview = (0 === strpos((string) $center_icon, 'data:image'))
            ? $center_icon
            : esc_url($center_icon);
        
        $card_flex_diection = "row";

  // Go up two levels
$templates = [
    'spin-on-left'   => $plugin_url . 'assets/img/horizotal.png',
    'spin-on-right'  => $plugin_url . 'assets/img/horizotal_reverse.png',
    'spin-on-top'    => $plugin_url . 'assets/img/virtical.png',
    'spin-on-bottom' => $plugin_url . 'assets/img/virtical_reverse.png',
];      

$preview_template_setting = ! empty( $spin->template_setting ) ? (string) $spin->template_setting : 'spin-on-left';

// Admin preview DOM order is [content_section (form), spin_section (wheel)].
// Canonical template semantics:
//   spin-on-left   => wheel LEFT,  form RIGHT  => row-reverse
//   spin-on-right  => wheel RIGHT, form LEFT   => row
//   spin-on-top    => wheel TOP,   form BELOW  => column-reverse (preview DOM is [form, wheel])
//   spin-on-bottom => wheel BOTTOM,form ABOVE  => column (preview DOM is [form, wheel])
// Frontend DOM is [wheel, form]: spin-on-top => column; spin-on-bottom => column-reverse
if($spin->template_setting==="spin-on-left"){
    $card_flex_diection = "row-reverse";
}elseif($spin->template_setting==="spin-on-right"){
     $card_flex_diection = "row";
}elseif($spin->template_setting==="spin-on-top"){
     $card_flex_diection = "column-reverse";
}elseif($spin->template_setting==="spin-on-bottom"){
     $card_flex_diection = "column";
}
            
        
        ?>
        <div class="wsww-preview-container wsww-preview-template-<?php echo esc_attr( sanitize_html_class( $preview_template_setting ) ); ?>" style="background: <?php echo esc_attr($spin->card_background); ?>; 
             color: <?php echo esc_attr($spin->card_color); ?>; 
             border-radius: <?php echo esc_attr($spin->card_boder_radius); ?>px; 
             padding: <?php echo esc_attr($spin->card_boder_padding); ?>px; 
             max-width: 100%; margin: 20px auto;">

            <div class="preview_inner" style="    
                        display: flex;
                        align-content: center;
                        align-items: center;
                        justify-content: space-around; 
                        flex-direction: <?php echo esc_attr($card_flex_diection); ?>;
                        gap: 50px;
                        ">
                <div class="content_section">
                    <h3 style="text-align: <?php echo esc_attr($spin->from_design_alinment); ?>; margin-bottom: 20px; color: <?php echo esc_attr($spin->card_color); ?>">
                        <?php echo esc_html($spin->spin_title); ?>
                    </h3>
                    
                    <p style="text-align: <?php echo esc_attr($spin->from_design_alinment); ?>; margin-bottom: 20px; color: <?php echo esc_attr($spin->card_color); ?>">
                        <?php echo esc_html($spin->spin_description); ?>
                    </p>

                     <!-- Form Fields Preview -->
                    <div style="margin: 20px 0;">
                        <form style=" text-align: <?php echo esc_attr($spin->from_design_alinment); ?>;">
                            <?php

                            // Get display fields from database record
                            $display_fields = $spin->display_field_setting;
                            
                            // Decode JSON if it's a string
                            if (!empty($display_fields) && is_string($display_fields)) {
                
                                $display_fields = json_decode($display_fields, true);
                            }
                            
                            // Fallback to empty array if still not valid
                            if (!is_array($display_fields)) {
                                
                                $display_fields = [];
                            }
                            
                            // Debug: Log the final display fields
                           
                            
                            // Flatten the nested array structure
                            $flat_display_fields = [];
                            foreach ($display_fields as $item) {
                                if (is_array($item)) {
                                    $flat_display_fields = array_merge($flat_display_fields, array_values($item));
                                } else {
                                    $flat_display_fields[] = $item;
                                }
                            }
                            
                            
                            
                            // Show fields based on display settings
                            $show_name = in_array('name_field', $flat_display_fields);
                            $show_email = in_array('email_field', $flat_display_fields);
                            $show_phone = in_array('mobile_field', $flat_display_fields);
                            
                            // Email field is always required (as per form logic)
                            $show_email = true;
                            
                    
                            
                            // Add name field if enabled
                            if ($show_name): 
                              
                            ?>
                                <div class="from_field" style="margin-bottom: 15px;">
                                    <input type="text" name="name" placeholder="Your Name" 
                                        style="width: 100%;  padding: 10px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px;">
                                </div>
                            <?php 
                            else:
                               
                            endif; ?>
                            
                            <?php // Add email field if enabled
                            if ($show_email): 
                               
                            ?>
                                <div class="from_field" style="margin-bottom: 15px;">
                                    <input type="email" name="email" placeholder="Your Email" 
                                        style="width: 100%;  padding: 10px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px;">
                                </div>
                            <?php 
                            else:
                              
                            endif; ?>
                            
                            <?php // Add mobile field if enabled
                            if ($show_phone): 
                               
                            ?>
                                <div class="from_field" style="margin-bottom: 15px;">
                                    <input type="text" name="phone" placeholder="Your Phone" 
                                        style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px;">
                                </div>
                            <?php 
                            else:
                              
                            endif; ?>
                            
                            <div style="margin-top: 20px;">
                                <button type="button" style="background: <?php echo esc_attr($spin->from_button_background_color); ?>; 
                                        color: <?php echo esc_attr($spin->from_button_color); ?>; 
                                        border: none; padding: 12px 24px; border-radius: 5px; cursor: pointer; width: 100%;">
                                    <?php echo esc_html($spin->from_button_text); ?>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="spin_section" style="display: flex; align-items: center; justify-content: center; margin: 30px 0;">
                    <div id="preview-chart" style="position: relative;">
                        <!-- SVG will be generated here -->
                    </div>
                </div>

            </div>

        </div>

        <?php
        // Get HTML content (everything output so far)
        $html_content = ob_get_clean();

        $preview_config = [
            'spins'                => $spins_items,
            'circle_size'         => (int) $circle_size,
            'arrow_icon'          => esc_url( $arrow_icon ),
            'center_icon'         => $center_icon_for_preview,
            'stroke_color'        => isset( $spin->wheel_stroke_border_color ) ? (string) $spin->wheel_stroke_border_color : '#003B33',
            'stroke_size'         => isset( $spin->wheel_stroke_border_size ) ? (int) $spin->wheel_stroke_border_size : 5,
            'font_size'           => isset( $spin->wheel_stroke_font_size ) ? (int) $spin->wheel_stroke_font_size : 20,
            'font_family'         => isset( $spin->wheel_stroke_font_family ) ? (string) $spin->wheel_stroke_font_family : 'roboto',
            'font_style'          => isset( $spin->wheel_stroke_font_style ) ? (string) $spin->wheel_stroke_font_style : 'bold',
            'center_background'   => isset( $spin->wheel_center_background ) ? (string) $spin->wheel_center_background : '#ffffff',
            'center_border_color' => isset( $spin->wheel_center_boder_color ) ? (string) $spin->wheel_center_boder_color : '#003B33',
            'center_border_width' => isset( $spin->wheel_center_boder_width ) ? (int) $spin->wheel_center_boder_width : 3,
        ];

        return [
            'html'   => $html_content,
            'config' => $preview_config,
        ];
    }

    /**
     * Normalize decoded JSON form data to rebuild nested arrays from bracketed keys.
     *
     * @param array $form_data
     * @return array
     */
    private function normalize_json_form_data( $form_data ) {
        $normalized = [];

        foreach ( $form_data as $key => $value ) {
            if ( ! is_string( $key ) || strpos( $key, '[' ) === false ) {
                $normalized[ $key ] = $value;
                continue;
            }

            $segments = $this->extract_form_key_segments( $key );
            if ( empty( $segments ) ) {
                continue;
            }

            $base_key = array_shift( $segments );
            if ( ! isset( $normalized[ $base_key ] ) || ! is_array( $normalized[ $base_key ] ) ) {
                $normalized[ $base_key ] = [];
            }

            $this->assign_normalized_form_value( $normalized[ $base_key ], $segments, $value );
        }

        return $normalized;
    }

    /**
     * Break a bracketed field key (e.g. spins[1][label]) into its segments.
     *
     * @param string $key
     * @return array
     */
    private function extract_form_key_segments( $key ) {
        $segments = [];
        $base_key = strstr( $key, '[', true );

        if ( false === $base_key ) {
            $base_key = $key;
        }

        $base_key = trim( (string) $base_key );
        if ( '' === $base_key ) {
            return $segments;
        }

        $segments[] = $base_key;

        if ( preg_match_all( '/\[([^\]]*)\]/', $key, $matches ) ) {
            foreach ( $matches[1] as $match ) {
                $segments[] = $match;
            }
        }

        return $segments;
    }

    /**
     * Assign a value into a nested array following the provided path segments.
     *
     * @param array $target
     * @param array $segments
     * @param mixed $value
     * @return void
     */
    private function assign_normalized_form_value( &$target, $segments, $value ) {
        if ( empty( $segments ) ) {
            return;
        }

        $last_segment_index = count( $segments ) - 1;
        $reference          = &$target;

        foreach ( $segments as $index => $segment ) {
            $is_last = ( $index === $last_segment_index );

            if ( $is_last ) {
                if ( '' === $segment ) {
                    if ( is_array( $value ) ) {
                        foreach ( $value as $array_value ) {
                            $reference[] = $array_value;
                        }
                    } else {
                        $reference[] = $value;
                    }
                } else {
                    $reference[ $segment ] = $value;
                }
                continue;
            }

            if ( '' === $segment ) {
                $reference[] = [];
                end( $reference );
                $last_key = key( $reference );
                if ( null === $last_key ) {
                    $last_key = count( $reference ) - 1;
                }
                $reference = &$reference[ $last_key ];
            } else {
                if ( ! isset( $reference[ $segment ] ) || ! is_array( $reference[ $segment ] ) ) {
                    $reference[ $segment ] = [];
                }
                $reference = &$reference[ $segment ];
            }
        }
    }
}
