<?php
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.NamingConventions.PrefixAllGlobals -- Editor partial uses plugin-owned tables and legacy extension hooks.

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

// Set global variable to indicate this is an HTML popup
$GLOBALS['instant_popup_builder_current_popup_type'] = 'html';

use Admin\Settings\Edit\Class_instant_setting_edit;
$instant_popup_builder_is_active = Class_instant_popup_builder_manager::get_active_popup();
$instant_popup_builder_current_slug = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
$instant_popup_builder_message = '';
$instant_popup_builder_id = isset($_GET['edit_id']) && !empty($_GET['edit_id']) ? absint(sanitize_text_field(wp_unslash($_GET['edit_id']))) : 0;
if (isset($_POST['instant_popup_builder_edit_submit']) && isset($_POST['instant_popup_builder_edit_nonce']) &&  wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['instant_popup_builder_edit_nonce'])), 'instant_popup_builder_edit_nonce_action')) {

    /**
     * Sanitize multidimensional array recursively
     *
     * @since    1.0.0
     * @param array $data The array to sanitize
     * @return array Sanitized array
     */
    $instant_popup_builder_sanitize_multidimensional_array = function($data) use (&$instant_popup_builder_sanitize_multidimensional_array) {
        if (!is_array($data)) {
            return sanitize_text_field($data);
        }

        $sanitized = [];
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                $sanitized[$key] = $instant_popup_builder_sanitize_multidimensional_array($value);
            } else {
                $sanitized[$key] = sanitize_text_field($value);
            }
        }

        return $sanitized;
    };

    $instant_popup_builder_Instant_admin = new Instant_Popup_Builder_Admin();
    $instant_popup_builder_type = isset($_POST['popup_temp_type']) && !empty($_POST['popup_temp_type']) ?   sanitize_text_field(wp_unslash($_POST['popup_temp_type'])) : '';
    $instant_popup_builder_title = isset($_POST['popup_title']) && !empty($_POST['popup_title']) ? sanitize_text_field(wp_unslash($_POST['popup_title'])) : 'New Popup';
    $instant_popup_builder_status = isset($_POST['instant_popup_builder_edit_submit']) && !empty($_POST['instant_popup_builder_edit_submit']) && $_POST['instant_popup_builder_edit_submit'] == 'Update' ? 'publish' : 'draft';
    $instant_popup_builder_select_option = isset($_POST['selected_option']) && !empty($_POST['selected_option']) ?  array_map('sanitize_text_field', wp_unslash($_POST['selected_option'])) : [];
    $instant_popup_builder_display_option = isset($_POST['display_option']) && !empty($_POST['display_option']) ?  array_map('sanitize_text_field', wp_unslash($_POST['display_option'])) : [];
    $instant_popup_builder_is_display = isset($_POST['is_display']) && !empty($_POST['is_display']) ?   array_map('sanitize_text_field', wp_unslash($_POST['is_display'])) : 'publish';
    // Preserve multi-dimensional display rule targets for HTML-based popups (edit mode, including Contact Form)
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- map_deep(sanitize_text_field) on next line sanitizes nested rule targets; helper is defense-in-depth.
    $instant_popup_builder_spec_val_raw = isset($_POST['spec_val']) && !empty($_POST['spec_val']) ? wp_unslash($_POST['spec_val']) : [];
    $instant_popup_builder_spec_val_raw = is_array($instant_popup_builder_spec_val_raw) ? map_deep($instant_popup_builder_spec_val_raw, 'sanitize_text_field') : sanitize_text_field((string) $instant_popup_builder_spec_val_raw);
    $instant_popup_builder_spec_val = $instant_popup_builder_sanitize_multidimensional_array($instant_popup_builder_spec_val_raw);
    $instant_popup_builder_spec_val = is_array($instant_popup_builder_spec_val) ? array_values($instant_popup_builder_spec_val) : [];
    $instant_popup_builder_trigger_option = isset($_POST['trigger_option']) && !empty($_POST['trigger_option']) ?   sanitize_text_field(wp_unslash($_POST['trigger_option']))  : '';
    $instant_popup_builder_trigger_delay = isset($_POST['trigger_delay']) && !empty($_POST['trigger_delay']) ?  array_map('sanitize_text_field', wp_unslash($_POST['trigger_delay']))  : [];
    $instant_popup_builder_trigger_class_h = isset($_POST['trigger_class']) && !empty($_POST['trigger_class']) ?  array_map('sanitize_text_field', wp_unslash($_POST['trigger_class'])) : [];
    $instant_popup_builder_trigger_class_c = isset($_POST['trigger_class_click']) && !empty($_POST['trigger_class_click']) ? array_map('sanitize_text_field', wp_unslash($_POST['trigger_class_click'])) : [];
    $instant_popup_builder_close_option = function_exists( 'ipb_sanitize_closing_from_request' )
        ? ipb_sanitize_closing_from_request()
        : array();
    $instant_popup_builder_close_position = isset($_POST['close_position']) && !empty($_POST['close_position']) ? sanitize_text_field(wp_unslash($_POST['close_position'])) : '';
    $instant_popup_builder_limit_count = isset($_POST['limit_count']) && !empty($_POST['limit_count']) ?  sanitize_text_field(wp_unslash($_POST['limit_count'])) : '0';
    $instant_popup_builder_limit_expiry = isset($_POST['limit_expiry']) && !empty($_POST['limit_expiry']) ? sanitize_text_field(wp_unslash($_POST['limit_expiry'])) : '0';
    $instant_popup_builder_popup_position = isset($_POST['position']) && !empty($_POST['position']) ?  sanitize_text_field(wp_unslash($_POST['position'])) : '';
    $instant_popup_builder_popup_theme = isset($_POST['theme']) && !empty($_POST['theme']) ?  sanitize_text_field(wp_unslash($_POST['theme'])) : '';
    $instant_popup_builder_background_selection = isset($_POST['background_selection']) && !empty($_POST['background_selection']) ?  sanitize_text_field(wp_unslash($_POST['background_selection'])) : '';
    $instant_popup_builder_back_color_toggle = ($instant_popup_builder_background_selection == 'color') && !empty($_POST['back_color_toggle']) ?  sanitize_text_field(wp_unslash($_POST['back_color_toggle'])) : '';
    $instant_popup_builder_background_color = ($instant_popup_builder_background_selection == 'color') && !empty($_POST['background_color']) ?  sanitize_text_field(wp_unslash($_POST['background_color'])) : '';
    $instant_popup_builder_back_image_toggle = '';
    if ($instant_popup_builder_background_selection === 'image') {
        if (!empty($_POST['back_image_toggle'])) {
            $instant_popup_builder_back_image_toggle = sanitize_text_field(wp_unslash($_POST['back_image_toggle']));
        } elseif (!empty($_POST['background_image_url'])) {
            $instant_popup_builder_back_image_toggle = 'yes';
        }
    }
    $instant_popup_builder_back_zindex = isset($_POST['popup_zindex']) && !empty($_POST['popup_zindex']) ? sanitize_text_field(wp_unslash($_POST['popup_zindex'])) : 1;
    $instant_popup_builder_border_enabled = isset($_POST['border_enabled']) ? sanitize_text_field(wp_unslash($_POST['border_enabled'])) : 'no';
    $instant_popup_builder_border_width = isset($_POST['border_width']) ? absint($_POST['border_width']) : 1;
    $instant_popup_builder_border_color = isset($_POST['border_color']) ? sanitize_text_field(wp_unslash($_POST['border_color'])) : '#111827';
    $instant_popup_builder_background_image = ($instant_popup_builder_background_selection == 'image') && !empty($_POST['background_image_url']) ?   sanitize_text_field(wp_unslash($_POST['background_image_url'])) : 1;
    // if (isset($_FILES['background_image'])) {

    //     $upload_overrides = array('test_form' => false);
    //     $upload = wp_handle_upload($_FILES['background_image'], $upload_overrides);

    //     if ($upload && !isset($upload['error'])) {

    //         $background_image = esc_url($upload['url']);
    //     } else {
    //         $background_image = 'no-image';
    //     }
    // }
    $instant_popup_builder_back_img_pos_toggle = isset($_POST['back_image_pos_toggle']) && !empty($_POST['back_image_pos_toggle']) ?   sanitize_text_field(wp_unslash($_POST['back_image_pos_toggle'])) : '';
    $instant_popup_builder_back_img_position = isset($_POST['back_img_position']) && !empty($_POST['back_img_position']) ?  sanitize_text_field(wp_unslash($_POST['back_img_position'])) : '';
    $instant_popup_builder_back_image_size = isset($_POST['back_image_size']) && !empty($_POST['back_image_size']) ?  sanitize_text_field(wp_unslash($_POST['back_image_size'])) : '';
    $instant_popup_builder_backcolor_opacity = isset($_POST['backcolor_opacity']) && !empty($_POST['backcolor_opacity']) ?   sanitize_text_field(wp_unslash($_POST['backcolor_opacity'])) : '';
    $instant_popup_builder_backimage_opacity = isset($_POST['backimage_opacity']) && !empty($_POST['backimage_opacity']) ?   sanitize_text_field(wp_unslash($_POST['backimage_opacity'])) : '';
    $instant_popup_builder_design_width = isset($_POST['design_width']) && !empty($_POST['design_width']) ? sanitize_text_field(wp_unslash($_POST['design_width'])) : '';
    $instant_popup_builder_design_height = isset($_POST['design_height']) && !empty($_POST['design_height']) ? sanitize_text_field(wp_unslash($_POST['design_height'])) : '';
    $instant_popup_builder_design_percentage = isset($_POST['design_percentage']) && !empty($_POST['design_percentage']) ? sanitize_text_field(wp_unslash($_POST['design_percentage'])) : '';
    $instant_popup_builder_design_percentage_toggle = isset($_POST['design_percentage_toggle']) && !empty($_POST['design_percentage_toggle']) && $_POST['design_percentage_toggle'] == 'yes' ? sanitize_text_field(wp_unslash($_POST['design_percentage_toggle'])) : 'no';
    $instant_popup_builder_animate_type = isset($_POST['animate_type']) && !empty($_POST['animate_type']) ? sanitize_text_field(wp_unslash($_POST['animate_type'])) : '';
    $instant_popup_builder_animate_speed = isset($_POST['animate_speed']) && !empty($_POST['animate_speed']) ? sanitize_text_field(wp_unslash($_POST['animate_speed'])) : '';
    $instant_popup_builder_animate_origin = isset($_POST['animate_origin']) && !empty($_POST['animate_origin']) ? sanitize_text_field(wp_unslash($_POST['animate_origin'])) : '';
    $instant_popup_builder_advance_action = isset($_POST['action_click']) && !empty($_POST['action_click']) ? sanitize_text_field(wp_unslash($_POST['action_click'])) : '';
    $instant_popup_builder_advance_url = isset($_POST['redirect_url']) && !empty($_POST['redirect_url']) ? sanitize_text_field(wp_unslash($_POST['redirect_url'])) : '';
    $instant_popup_builder_advance_newtab = isset($_POST['action_new_tab']) && !empty($_POST['action_new_tab']) ? sanitize_text_field(wp_unslash($_POST['action_new_tab'])) : '';
    $instant_popup_builder_sound_open = isset($_POST['sound_open']) && !empty($_POST['sound_open']) ? sanitize_text_field(wp_unslash($_POST['sound_open'])) : '';
    $instant_popup_builder_sound_close = isset($_POST['sound_close']) && !empty($_POST['sound_close']) ? sanitize_text_field(wp_unslash($_POST['sound_close'])) : '';
    $instant_popup_builder_sound_open_file = isset($_POST['sound_open_url']) && !empty($_POST['sound_open_url']) ? sanitize_text_field(wp_unslash($_POST['sound_open_url'])) : '';
    $instant_popup_builder_sound_close_file = isset($_POST['sound_closing_url']) && !empty($_POST['sound_closing_url']) ? sanitize_text_field(wp_unslash($_POST['sound_closing_url'])) : '';

    $instant_popup_builder_advance = [
        'action' => $instant_popup_builder_advance_action,
        'url' => $instant_popup_builder_advance_url,
        'tab' => $instant_popup_builder_advance_newtab,
        'sound_open' => $instant_popup_builder_sound_open,
        'sound_close' => $instant_popup_builder_sound_close,
        'sound_open_file' => $instant_popup_builder_sound_open_file,
        'sound_close_file' => $instant_popup_builder_sound_close_file
    ];
    $instant_popup_builder_design = [

        'back_color_toggle' => $instant_popup_builder_back_color_toggle,
        'popup_theme' => $instant_popup_builder_popup_theme,
        'background_selection' => $instant_popup_builder_background_selection,
        'background_color' => $instant_popup_builder_background_color,
        'back_image_toggle' => $instant_popup_builder_back_image_toggle,
        'background_image' => $instant_popup_builder_background_image,
        'back_image_pos_toggle' => $instant_popup_builder_back_img_pos_toggle,
        'back_img_position' => $instant_popup_builder_back_img_position,
        'back_image_size' => $instant_popup_builder_back_image_size,
        'backcolor_opacity' => $instant_popup_builder_backcolor_opacity,
        'backimage_opacity' => $instant_popup_builder_backimage_opacity,
        'design_width' => $instant_popup_builder_design_width,
        'design_height' => $instant_popup_builder_design_height,
        'design_percentage' => $instant_popup_builder_design_percentage,
        'design_percentage_toggle' => $instant_popup_builder_design_percentage_toggle,
        'animate_type' => $instant_popup_builder_animate_type,
        'animate_speed' => $instant_popup_builder_animate_speed,
        'animate_origin' => $instant_popup_builder_animate_origin,
        'back_zindex' => $instant_popup_builder_back_zindex,
        'border_enabled' => $instant_popup_builder_border_enabled,
        'border_width' => $instant_popup_builder_border_width,
        'border_color' => $instant_popup_builder_border_color,
    ];
    $instant_popup_builder_limit = [

        'limit_count' => $instant_popup_builder_limit_count,
        'limit_expiry' => $instant_popup_builder_limit_expiry,
        'popup_position' => $instant_popup_builder_popup_position

    ];
    $instant_popup_builder_trigger = [

        'trigger_option' => $instant_popup_builder_trigger_option,
        'trigger_delay' => $instant_popup_builder_trigger_delay,
        'trigger_class_click' => $instant_popup_builder_trigger_class_c,
        'trigger_class_hover' => $instant_popup_builder_trigger_class_h,
    ];

    // Allow extensions to add their trigger settings via filter
    $instant_popup_builder_trigger = apply_filters('ipb_trigger_settings', $instant_popup_builder_trigger, $instant_popup_builder_trigger_option, $_POST);

    // Universal device targeting - show on all devices
    $instant_popup_builder_trigger['target_device'] = ['desktop', 'tablet', 'mobile'];
    $instant_popup_builder_closing = [

        'close_option' => $instant_popup_builder_close_option,
        'close_position' => $instant_popup_builder_close_position
    ];
    if ($instant_popup_builder_type == 'popup_html') {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce verified earlier in save flow; custom HTML sanitized by ipb_sanitize_html_popup_content() below.
        $instant_popup_builder_popup_type_raw = isset($_POST['popup_type_value']) ? wp_unslash($_POST['popup_type_value']) : '';
        $instant_popup_builder_popup_type_raw = is_string($instant_popup_builder_popup_type_raw) ? $instant_popup_builder_popup_type_raw : '';
        $instant_popup_builder_text = $instant_popup_builder_popup_type_raw !== '' ? ipb_sanitize_html_popup_content($instant_popup_builder_popup_type_raw) : '';
    } elseif ($instant_popup_builder_type == 'popup_image') {

        $instant_popup_builder_imageUrl = isset($_POST['popu_image_url']) ? sanitize_text_field(wp_unslash($_POST['popu_image_url'])) : '';
    }
    $instant_popup_builder_message = $instant_popup_builder_Instant_admin->ipb_update_query($instant_popup_builder_id, $instant_popup_builder_text, $instant_popup_builder_status, $instant_popup_builder_title, $instant_popup_builder_select_option, $instant_popup_builder_is_display, $instant_popup_builder_spec_val, $instant_popup_builder_trigger, $instant_popup_builder_closing, $instant_popup_builder_limit, $instant_popup_builder_design, $instant_popup_builder_advance);
    if(class_exists('Instant_Popup_Custom_Targeting_Admin')){
    $instant_popup_builder_custom_trigger_Cls = new Instant_Popup_Custom_Targeting_Admin;
        $instant_popup_builder_custom_trigger_Cls->save_custom_targeting_settings($instant_popup_builder_id);

    }
}

// $instant_popup_builder_id = isset($_GET['edit_id']) && !empty($_GET['edit_id']) ? intval($_GET['edit_id']) : 0;
global $wpdb;
if ($instant_popup_builder_id) {

    // $query
    $instant_popup_builder_row = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}instant_popup_builder WHERE id = %d", $instant_popup_builder_id));
}

// Perform the query using get_results() method
if (!$instant_popup_builder_row) {

    return false;
}
?>
<?php Instant_Popup_Builder_Admin::ipb_top_header();
$instant_popup_builder_setting_edit = new Class_instant_setting_edit();

// Check if we should show success toast (when redirected after publish with "stay" behavior)
$show_success_toast = isset($_GET['published']) && '1' === $_GET['published'];
$post_publish_behavior = get_option('instant_popup_builder_post_publish_behavior', 'dashboard');
if ($show_success_toast && 'stay' === $post_publish_behavior && isset($instant_popup_builder_row) && !empty($instant_popup_builder_row)) {
    // Determine success message based on popup status
    $popup_status = isset($instant_popup_builder_row[0]->status) ? $instant_popup_builder_row[0]->status : 'draft';
    $success_message = ('publish' === $popup_status)
        ? __('The popup has been published.', 'instant-popup-builder')
        : __('The popup has been saved as a draft.', 'instant-popup-builder');
    ?>
    <div id="ipb-popup-success-toast" style="position: fixed; top: 52px; right: 24px; z-index: 99999; display: none;">
        <div style="display:flex; align-items:center; gap:12px; padding:12px 18px; background:#22aa5b; color:#fff; border-radius:4px; box-shadow:0 4px 12px rgba(0,0,0,0.18); font-size:13px;">
            <span style="display:inline-flex; align-items:center; justify-content:center; width:18px; height:18px; border-radius:50%; border:2px solid #fff; font-size:11px; line-height:1;">&#10003;</span>
            <span><?php echo esc_html($success_message); ?></span>
            <button type="button" id="ipb-popup-success-toast-close" style="margin-left:16px; padding:4px 10px; background:#ffffff; color:#1e7b3b; border-radius:3px; border:none; cursor:pointer; font-size:12px;">
                <?php esc_html_e('Close', 'instant-popup-builder'); ?>
            </button>
        </div>
    </div>
    <script>
        jQuery(document).ready(function($) {
            $('#ipb-popup-success-toast').fadeIn(200);

            // Auto-hide after a few seconds
            setTimeout(function() {
                $('#ipb-popup-success-toast').fadeOut(200);
            }, 2500);

            $('#ipb-popup-success-toast-close').on('click', function() {
                $('#ipb-popup-success-toast').fadeOut(150);
            });

            // Remove published parameter from URL without reload
            if (window.history && window.history.replaceState) {
                var url = new URL(window.location);
                url.searchParams.delete('published');
                window.history.replaceState({}, '', url);
            }
        });
    </script>
    <?php
}
?>

<div id="edit_popup">
    <div class="intant_new_popup_type">
        <div class="instant_inner_wrapper">
            <div class="heading">
                <h1>POPUP TYPE: HTML</h1>
                <div class="update_messsage">
                    <?php
                    if (isset($instant_popup_builder_message)) {
                        $message = is_string($instant_popup_builder_message) ? $instant_popup_builder_message : '';
                        echo wp_kses_post( (string) ( $message ?? '' ) );
                    }
                    ?>
                </div>
            </div>
            <form method="post">
                <?php wp_nonce_field('instant_popup_builder_edit_nonce_action', 'instant_popup_builder_edit_nonce'); ?>

                <div class="instant_left_col">
                    <div class="input_wrapper">
                        <input type="text" required name="popup_title" id="popup_title" placeholder="Enter Your popup name" value="<?php echo esc_attr($instant_popup_builder_row[0]->title); ?>">
                    </div>

                    <div class="input_wrapper">
                        <!-- <div class="label"><label for="">Write Your Code</label></div> -->
                        <div id="editor">HTML CODE HERE..</div>
                        <textarea name="popup_type_value" id="popup_type_value" style="height:200px; display: none;">
                        <?php
                        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- setting_edit_navigation() returns safe, sanitized HTML
                        // Safe JSON decode with error handling
                        $content_json = isset($instant_popup_builder_row[0]->content) ? $instant_popup_builder_row[0]->content : '';
                        $decoded_content = json_decode($content_json);
                        if (json_last_error() === JSON_ERROR_NONE && $decoded_content !== null) {
                            echo esc_textarea(wp_unslash(trim(ipb_string($decoded_content))));
                        } ?>
                        </textarea>

                        <!-- <input type="hidden" name="popup_type_value" id="popup_type_value" value=""> -->
                        <input type="hidden" name="popup_temp_type" value="popup_<?php echo esc_attr($instant_popup_builder_row[0]->type); ?>">
                    </div>
                </div>
                <div class="instant-right_col postbox">
                        <div id="ipb_actions_wrapper">
                            <div id="ipb_pop_action">
                                <p class='preview_links'>
                                    <a href="#" class="enhanced-preview-trigger"><i class="fa-solid fa-eye"></i> Preview<span></span></a>
                                </p>
                            </div>
                            <div id="ipb_pop_action">
                               <button type="submit" name="instant_popup_builder_edit_submit" value="Save" class="ipb-save-draft">
                                    <i class="fa-solid fa-save"></i> Save Draft
                                </button>
                            </div>
                            <div id="ipb_pop_action">
                                <button type="submit" name="instant_popup_builder_edit_submit" value="Update" class="ipb-publish">
                                    <i class="fa-solid fa-paper-plane"></i> Update
                                </button>
                            </div>
                        </div>
                    </div>
                <div class="instant_popup_setting">
                    <?php
                    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- setting_edit_navigation() returns safe, sanitized HTML
                    echo  $instant_popup_builder_setting_edit->setting_edit_navigation(); ?>
                    <?php
                    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- setting_edit_navigation() returns safe, sanitized HTML
                    echo $instant_popup_builder_setting_edit->setting_edit_screen($instant_popup_builder_row, 'html'); ?>
                </div>
            </form>
        </div>
    </div>
</div>
