<?php
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.NamingConventions.PrefixAllGlobals -- Shortcode template uses plugin-owned data and established extension hooks.

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

// Include the reusable close button component
require_once plugin_dir_path(__FILE__) . 'components/close-button.php';

global $wpdb;
$instant_popup_builder_id = get_transient('instant_popup_builder_popup_id');
$instant_popup_builder_is_active = get_transient('instant_popup_builder_popup_class' . $instant_popup_builder_id);
$instant_popup_builder_delay = json_decode(get_transient('instant_popup_builder_delay'));
$instant_popup_builder_class_hover = get_transient('instant_popup_builder_class_hover' . $instant_popup_builder_id);
$instant_popup_builder_class_click = get_transient('instant_popup_builder_class_click' . $instant_popup_builder_id);
$instant_popup_builder_trigger_option = get_transient('instant_popup_builder_trigger' . $instant_popup_builder_id);
$instant_popup_builder_target_device = get_transient('instant_popup_builder_target_device' . $instant_popup_builder_id);
$instant_popup_builder_exit_sensivity = get_transient('exit_sensivity' . $instant_popup_builder_id);
$instant_popup_builder_exit_intent_options = json_decode(get_transient('exit_intent_options' . $instant_popup_builder_id), true);
if (!is_array($instant_popup_builder_exit_intent_options)) {
    $instant_popup_builder_exit_intent_options = array(
        'mouse_leave' => '1', // Default enabled
        'lost_focus' => '0',
        'back_button' => '0',
        'link_click' => '0',
    );
}
$instant_popup_builder_scroll_type = get_transient('instant_popup_builder_scroll_type'. $instant_popup_builder_id);
$instant_popup_builder_scroll_distance = get_transient('instant_popup_builder_scroll_distance'. $instant_popup_builder_id);
$instant_popup_builder_scroll_trigger_settings = get_transient('instant_popup_builder_scroll_trigger'. $instant_popup_builder_id);
$instant_popup_builder_woo_trigger = get_transient('instant_popup_builder_woo_trigger'. $instant_popup_builder_id);
$instant_popup_builder_woo_condition = get_transient('instant_popup_builder_woo_condition'. $instant_popup_builder_id);
$instant_popup_builder_woo_trigger_settings = get_transient('instant_popup_builder_woocommerce_trigger'. $instant_popup_builder_id);
$instant_popup_builder_row = $wpdb->get_results($wpdb->prepare("SELECT * FROM  {$wpdb->prefix}instant_popup_builder where id=%d", $instant_popup_builder_id));
// Validate array access before using
if (empty($instant_popup_builder_row) || !isset($instant_popup_builder_row[0])) {
    return; // Exit early if no popup data found
}
$instant_popup_builder_image_url = json_decode($instant_popup_builder_row[0]->content);
$instant_popup_builder_title = isset($instant_popup_builder_row[0]->title) ? $instant_popup_builder_row[0]->title : '';
$ipb_closing_parsed = function_exists( 'ipb_parse_closing_settings_from_json' )
    ? ipb_parse_closing_settings_from_json( isset( $instant_popup_builder_row[0]->closing ) ? (string) $instant_popup_builder_row[0]->closing : '' )
    : array(
        'position' => 'top-right',
        'escape'   => 'no',
        'outside'  => 'no',
        'hide'     => 'no',
    );
$instant_popup_builder_close_position = $ipb_closing_parsed['position'];
$instant_popup_builder_close_escape     = $ipb_closing_parsed['escape'];
$instant_popup_builder_close_outside    = $ipb_closing_parsed['outside'];
$instant_popup_builder_hide_close       = $ipb_closing_parsed['hide'];
$instant_popup_builder_hover_close = get_transient('instant_popup_builder_hover_close');
$instant_popup_builder_limit_count = get_transient('instant_popup_builder_limit_count');
$instant_popup_builder_limit_expiry = get_transient('instant_popup_builder_limit_expiry');
$instant_popup_builder_popup_position = get_transient('instant_popup_builder_popup_position');
$instant_popup_builder_back_color_toggle = get_transient('back_color_toggle');
$instant_popup_builder_popup_theme = get_transient('popup_theme');
$instant_popup_builder_background_color = get_transient('background_color');
$instant_popup_builder_back_image_toggle = get_transient('back_image_toggle');
$instant_popup_builder_background_image = get_transient('background_image');
$instant_popup_builder_back_image_pos_toggle = get_transient('back_image_pos_toggle');
$instant_popup_builder_back_img_position = get_transient('back_img_position');
$instant_popup_builder_back_image_size = get_transient('back_image_size');
$instant_popup_builder_backcolor_opacity = get_transient('backcolor_opacity');
$instant_popup_builder_backimage_opacity = get_transient('backimage_opacity');
$instant_popup_builder_design_width = get_transient('design_width' . $instant_popup_builder_id);
$instant_popup_builder_design_height = get_transient('design_height' . $instant_popup_builder_id);
$instant_popup_builder_design_percentage = get_transient('design_percentage' . $instant_popup_builder_id);
$instant_popup_builder_design_percentage_toggle = get_transient('design_percentage_toggle' . $instant_popup_builder_id);
$instant_popup_builder_animate_type = get_transient('animate_type');
$instant_popup_builder_animate_speed = get_transient('animate_speed');
$instant_popup_builder_animate_origin = get_transient('animate_origin');
$instant_popup_builder_action = get_transient('action');
$instant_popup_builder_action_type = get_transient('action_type') ?: 'redirect';
$instant_popup_builder_action_popup_id = get_transient('action_popup_id') ?: '';
$instant_popup_builder_url = get_transient('url');
$instant_popup_builder_redirect_delay_seconds = get_transient('redirect_delay_seconds') !== false ? absint(get_transient('redirect_delay_seconds')) : 0;
$instant_popup_builder_sound_open = get_transient('sound_open');
$instant_popup_builder_sound_close = get_transient('sound_close');
$instant_popup_builder_sound_open_file = get_transient('sound_open_file');
$instant_popup_builder_sound_close_file = get_transient('sound_close_file');
// Exit intent is now handled by the extension plugin

if (!$instant_popup_builder_sound_open_file) {

    $instant_popup_builder_sound_open_file = plugin_dir_url(dirname(dirname(__FILE__))) . 'assets/uploads/sound.mp3';
}
if (!$instant_popup_builder_sound_close_file) {

    $instant_popup_builder_sound_close_file = plugin_dir_url(dirname(dirname(__FILE__))) . 'assets/uploads/sound.mp3';
}
$instant_popup_builder_new_tab = get_transient('tab');
$instant_popup_builder_back_zindex = get_transient('back_zindex');
$instant_popup_builder_border_enabled = get_transient('border_enabled');
$instant_popup_builder_border_width = get_transient('border_width');
$instant_popup_builder_border_color = get_transient('border_color');
// Get popup date from database if available, otherwise use current date
$popup_date_from_db = isset($instant_popup_builder_row[0]->Date) ? $instant_popup_builder_row[0]->Date : null;
if ($popup_date_from_db) {
    try {
        $instant_popup_builder_date = new DateTime($popup_date_from_db);
    } catch (Exception $e) {
        $instant_popup_builder_date = new DateTime();
    }
} else {
    $instant_popup_builder_date = new DateTime();
}

$instant_popup_builder_currentDate = new DateTime();
$instant_popup_builder_currentDate->modify('+20 days');

// Calculate difference between current date + 20 days and popup date
$instant_popup_builder_diff = $instant_popup_builder_currentDate->diff($instant_popup_builder_date);
$instant_popup_builder_days_diff = $instant_popup_builder_diff->days;
$instant_popup_builder_views = get_transient('instant_popup_builder_popup_views');
if(!empty($instant_popup_builder_image_url)){
    // Validate that the content is actually an image URL, not HTML content
    $is_valid_image_url = false;
    if (is_string($instant_popup_builder_image_url)) {
        // Normalize to string for safety
        $safe_image_url = (string) ( $instant_popup_builder_image_url ?? '' );
        // Check if it's a URL (starts with http:// or https://) or a file path
        $is_url = (strpos($safe_image_url, 'http://') === 0 || strpos($safe_image_url, 'https://') === 0);
        $is_file_path = (strpos($safe_image_url, '/') === 0 || strpos($safe_image_url, '\\') !== false);

        // Check if it contains HTML tags (which would indicate it's HTML content, not an image URL)
        $contains_html = (strpos($safe_image_url, '<') !== false || strpos($safe_image_url, '&lt;') !== false);

        // Only proceed if it looks like a valid image URL/path and doesn't contain HTML
        if (($is_url || $is_file_path) && !$contains_html) {
            $is_valid_image_url = true;
        }
    }

    if ($is_valid_image_url) {
        // Use proper error handling instead of @ suppression
        $instant_popup_builder_dimensions = false;
        if (function_exists('getimagesize') && filter_var($instant_popup_builder_image_url, FILTER_VALIDATE_URL)) {
            $instant_popup_builder_dimensions = getimagesize($instant_popup_builder_image_url);
        }
        if ($instant_popup_builder_dimensions && is_array($instant_popup_builder_dimensions) && isset($instant_popup_builder_dimensions[0], $instant_popup_builder_dimensions[1])) {
            $instant_popup_builder_width = $instant_popup_builder_dimensions[0];
            $instant_popup_builder_height = $instant_popup_builder_dimensions[1];
        } else {
            $instant_popup_builder_width = '';
            $instant_popup_builder_height = '';
        }
    } else {
        $instant_popup_builder_width = '';
        $instant_popup_builder_height = '';
    }
}else{
    $instant_popup_builder_width = '';
    $instant_popup_builder_height = '';
}

$instant_popup_builder_margins = explode('-', (string) ( $instant_popup_builder_popup_position ?? '' ));
$instant_popup_builder_marginy = isset($instant_popup_builder_margins[0]) ? $instant_popup_builder_margins[0] : '';
$instant_popup_builder_marginx = isset($instant_popup_builder_margins[1]) ? $instant_popup_builder_margins[1] : '';

$instant_popup_builder_margin_style = '';

if ($instant_popup_builder_marginy === 'end' && $instant_popup_builder_marginx === 'start') {
    $instant_popup_builder_margin_style .= 'margin-left: 70px; ';
    $instant_popup_builder_margin_style .= 'margin-bottom: 70px; ';
} elseif ($instant_popup_builder_marginy === 'end' && $instant_popup_builder_marginx === 'end') {
    $instant_popup_builder_margin_style .= 'margin-right: 70px; ';
    $instant_popup_builder_margin_style .= 'margin-bottom: 70px; ';
} elseif ($instant_popup_builder_marginy === 'end' && $instant_popup_builder_marginx === 'center') {
    $instant_popup_builder_margin_style .= 'margin-bottom: 70px; ';
} elseif ($instant_popup_builder_marginy === 'center' && $instant_popup_builder_marginx === 'end') {
    $instant_popup_builder_margin_style .= 'margin-right: 70px; ';
} elseif ($instant_popup_builder_marginy === 'start' && $instant_popup_builder_marginx === 'start') {
    $instant_popup_builder_margin_style .= 'margin-left: 70px; ';
    $instant_popup_builder_margin_style .= 'margin-top: 70px; ';
} elseif ($instant_popup_builder_marginy === 'start' && $instant_popup_builder_marginx === 'center') {
    // $instant_popup_builder_margin_style .= 'margin-left: 70px; '
    $instant_popup_builder_margin_style .= 'margin-top: 70px; ';
} elseif ($instant_popup_builder_marginy === 'start' && $instant_popup_builder_marginx === 'end') {
    $instant_popup_builder_margin_style .= 'margin-right: 70px; ';
    $instant_popup_builder_margin_style .= 'margin-top: 70px; ';
} else {
}

?>
<?php if ($instant_popup_builder_is_active == 'yes'): ?>
    <div class="instant_popup-front instant-popup"
        data-id="<?php echo esc_attr($instant_popup_builder_id); ?>"
        data-close-positon="<?php echo esc_attr($instant_popup_builder_close_position); ?>"
        data-action="<?php echo esc_attr($instant_popup_builder_action); ?>"
        data-action-type="<?php echo esc_attr($instant_popup_builder_action_type); ?>"
        data-action-popup-id="<?php echo esc_attr($instant_popup_builder_action_popup_id); ?>"
        data-action-url="<?php echo esc_attr($instant_popup_builder_url); ?>"
        data-action-tab="<?php echo esc_attr($instant_popup_builder_new_tab); ?>"
        data-redirect-delay-seconds="<?php echo esc_attr($instant_popup_builder_redirect_delay_seconds); ?>"
        data-close-escape="<?php echo esc_attr($instant_popup_builder_close_escape); ?>"
        data-close-outside="<?php echo esc_attr($instant_popup_builder_close_outside); ?>"
        data-back_zindex="<?php echo esc_attr($instant_popup_builder_back_zindex); ?>"
        data-border-enabled="<?php echo esc_attr($instant_popup_builder_border_enabled); ?>"
        data-border-width="<?php echo esc_attr($instant_popup_builder_border_width); ?>"
        data-border-color="<?php echo esc_attr($instant_popup_builder_border_color); ?>"
        data-close-hide="<?php echo esc_attr($instant_popup_builder_hide_close); ?>"
        data-close-hover="<?php echo esc_attr($instant_popup_builder_hover_close); ?>"
        data-hover="<?php echo esc_attr($instant_popup_builder_class_hover); ?>"
        data-click="<?php echo esc_attr($instant_popup_builder_class_click); ?>"
        data-trigger="<?php echo esc_attr($instant_popup_builder_trigger_option); ?>"
        data-target="<?php echo esc_attr($instant_popup_builder_target_device); ?>"
        data-sensitivity="<?php echo esc_attr($instant_popup_builder_exit_sensivity); ?>"
        data-exit-mouse-leave="<?php echo esc_attr($instant_popup_builder_exit_intent_options['mouse_leave']); ?>"
        data-exit-lost-focus="<?php echo esc_attr($instant_popup_builder_exit_intent_options['lost_focus']); ?>"
        data-exit-back-button="<?php echo esc_attr($instant_popup_builder_exit_intent_options['back_button']); ?>"
        data-exit-link-click="<?php echo esc_attr($instant_popup_builder_exit_intent_options['link_click']); ?>"
        data-scroll-type = "<?php echo esc_attr($instant_popup_builder_scroll_type)?>"
        data-scroll-distance = "<?php echo esc_attr($instant_popup_builder_scroll_distance)?>"
        data-scroll-trigger-settings = "<?php echo esc_attr($instant_popup_builder_scroll_trigger_settings)?>"
        <?php
        // Generic extension data attributes
        // Allows extensions to add their own data attributes
        $extension_attributes = apply_filters('ipb_popup_data_attributes', [], $instant_popup_builder_id, $instant_popup_builder_trigger_option);
        if (!empty($extension_attributes) && is_array($extension_attributes)) {
            foreach ($extension_attributes as $attr_name => $attr_value) {
                echo 'data-' . esc_attr($attr_name) . '="' . esc_attr($attr_value) . '" ';
            }
        }
        ?>
        data-limit-count="<?php echo esc_attr($instant_popup_builder_limit_count); ?>"
        data-views-count="<?php echo esc_attr($instant_popup_builder_views); ?>"
        data-limit-expiry="<?php echo esc_attr($instant_popup_builder_days_diff); ?>"
        data-position="<?php echo esc_attr($instant_popup_builder_popup_position); ?>"
        data-back_color_toggle="<?php echo esc_attr($instant_popup_builder_back_color_toggle); ?>"
        data-popup_theme="<?php echo esc_attr($instant_popup_builder_popup_theme); ?>"
        data-background_color="<?php echo esc_attr($instant_popup_builder_background_color); ?>"
        data-back_image_toggle="<?php echo esc_attr($instant_popup_builder_back_image_toggle); ?>"
        data-background_image="<?php echo esc_attr($instant_popup_builder_background_image); ?>"
        data-back_image_pos_toggle="<?php echo esc_attr($instant_popup_builder_back_image_pos_toggle); ?>"
        data-back_img_position="<?php echo esc_attr($instant_popup_builder_back_img_position); ?>"
        data-back_image_size="<?php echo esc_attr($instant_popup_builder_back_image_size); ?>"
        data-backcolor_opacity="<?php echo esc_attr($instant_popup_builder_backcolor_opacity); ?>"
        data-backimage_opacity="<?php echo esc_attr($instant_popup_builder_backimage_opacity); ?>"
        data-design_width="<?php echo esc_attr($instant_popup_builder_design_width); ?>"
        data-design_height="<?php echo esc_attr($instant_popup_builder_design_height); ?>"
        data-design_percentage="<?php echo esc_attr($instant_popup_builder_design_percentage); ?>"
        data-design_percentage_toggle="<?php echo esc_attr($instant_popup_builder_design_percentage_toggle); ?>"
        data-animate_type="<?php echo esc_attr($instant_popup_builder_animate_type); ?>"
        data-animate_speed="<?php echo esc_attr($instant_popup_builder_animate_speed); ?>"
        data-animate_origin="<?php echo esc_attr($instant_popup_builder_animate_origin); ?>"
        id="instant-<?php echo esc_attr($instant_popup_builder_id); ?>"
        data-form-id="<?php echo esc_attr($instant_popup_builder_id); ?>"
        data-delay="<?php echo $instant_popup_builder_delay != '' ? esc_attr($instant_popup_builder_delay) : ''; ?>">
        <div class="instant_overlay">
            <div class="audio_wrapper">
                <?php if ($instant_popup_builder_sound_open): ?>
                    <audio id="ipb_audioOpen" class="audio_file" src="<?php echo esc_url($instant_popup_builder_sound_open_file); ?>" display="none"></audio>
                <?php endif; ?>
                <?php if ($instant_popup_builder_sound_close): ?>
                    <audio id="ipb_audioClose" class="audio_file" src="<?php echo esc_url($instant_popup_builder_sound_close_file); ?>" display="none"></audio>
                <?php endif; ?>
            </div>
            <div class="intant-popup-type-image instant-popup-content" style="<?php echo esc_attr($instant_popup_builder_margin_style); ?>">
                <?php ipb_render_close_button( array( 'popup_type' => 'image' ) ); ?>
                <div class="inner_content" style="height: 100%; width: 100%; overflow: auto; scrollbar-width: none;">
                    <img id="popup_image_front" src="<?php echo esc_url($instant_popup_builder_image_url);  ?>" alt="<?php echo esc_attr($instant_popup_builder_title);  ?>" style="width: 100%; height: 100%; object-fit: contain;">
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>
