<?php
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL,WordPress.NamingConventions.PrefixAllGlobals -- Settings partial uses plugin-owned tables and local variables.

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

// Get existing values for edit mode
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameter used for popup ID retrieval, value is sanitized
$instant_popup_builder_edit_id = isset($_GET['edit_id']) && !empty($_GET['edit_id']) ? absint(sanitize_text_field(wp_unslash($_GET['edit_id']))) : 0;
$instant_popup_builder_advance_data = null;

if ($instant_popup_builder_edit_id > 0) {
    global $wpdb;
    $instant_popup_builder_popup_data = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}instant_popup_builder WHERE id=%d", $instant_popup_builder_edit_id));
    if ($instant_popup_builder_popup_data) {
        $instant_popup_builder_popup_data = $instant_popup_builder_popup_data[0];
        $instant_popup_builder_advance_data = isset($instant_popup_builder_popup_data->advance) ? json_decode($instant_popup_builder_popup_data->advance, true) : null;
    }
}

// Get values
$instant_popup_builder_action_click = $instant_popup_builder_advance_data && isset($instant_popup_builder_advance_data['action']) ? $instant_popup_builder_advance_data['action'] : 'no';
$instant_popup_builder_action_type = $instant_popup_builder_advance_data && isset($instant_popup_builder_advance_data['action_type']) ? $instant_popup_builder_advance_data['action_type'] : 'redirect';
$instant_popup_builder_redirect_url = $instant_popup_builder_advance_data && isset($instant_popup_builder_advance_data['url']) ? $instant_popup_builder_advance_data['url'] : '';
$instant_popup_builder_redirect_delay_seconds = $instant_popup_builder_advance_data && isset($instant_popup_builder_advance_data['redirect_delay_seconds']) ? absint($instant_popup_builder_advance_data['redirect_delay_seconds']) : 0;
$instant_popup_builder_action_new_tab = $instant_popup_builder_advance_data && isset($instant_popup_builder_advance_data['tab']) ? $instant_popup_builder_advance_data['tab'] : 'no';
$instant_popup_builder_action_popup_id = $instant_popup_builder_advance_data && isset($instant_popup_builder_advance_data['action_popup_id']) ? $instant_popup_builder_advance_data['action_popup_id'] : '';

// Get all available popups for dropdown
global $wpdb;
$table_name = $wpdb->prefix . 'instant_popup_builder';
$escaped_table_name = esc_sql($table_name);
// Safe query - table name is escaped, status is hardcoded
$instant_popup_builder_all_popups = $wpdb->get_results($wpdb->prepare("SELECT id, title, type FROM `{$escaped_table_name}` WHERE status=%s ORDER BY title ASC", 'publish'));

// Check if selected popup is inactive
$instant_popup_builder_selected_popup_status = '';
if ($instant_popup_builder_action_popup_id) {
    $instant_popup_builder_selected_popup = $wpdb->get_row($wpdb->prepare("SELECT id, title, status FROM {$wpdb->prefix}instant_popup_builder WHERE id=%d", $instant_popup_builder_action_popup_id));
    if ($instant_popup_builder_selected_popup) {
        $instant_popup_builder_selected_popup_status = $instant_popup_builder_selected_popup->status;
    }
}

?>
<div class="ipb-section ipb-actions-events">
 <div class="ipb-section-header">
    <h3>Actions & Events</h3>
</div>
<div class="ipb-section-content" data-section="display">
<div class="design_background">
    <div class="ipb_background_wrapper ipb_action_wrapper">

        <div class="background_field" id="action_wrapper">
            <!-- Click Action Toggle Row -->
            <div class="ipb-actions-row">
                <div class="ipb-actions-label">
                    <label for="action_click">Click action</label>
                </div>
                <div class="ipb-actions-control">
                    <div class="input toggle switch">
                        <!-- Submit a deterministic value even if JS doesn't run -->
                        <input type="hidden" name="action_click" value="no">
                        <input type="checkbox" name="action_click" id="action_click" value="yes" <?php checked($instant_popup_builder_action_click, 'yes'); ?>>
                        <span class="slider round"></span>
                    </div>
                    <?php if ($instant_popup_builder_action_click !== 'yes'): ?>
                    <p class="ipb-actions-helper">Enable to add a click action.</p>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Collapsed Content Wrapper -->
            <div class="ipb-actions-content" id="ipb_actions_content" style="display: <?php echo esc_attr($instant_popup_builder_action_click === 'yes' ? 'block' : 'none'); ?>;">
                
                <!-- Action Type Row -->
                <div class="ipb-actions-row" id="action_type_wrapper">
                    <div class="ipb-actions-label">
                        <label for="action_type">Action Type</label>
                    </div>
                    <div class="ipb-actions-control">
                        <select name="action_type" id="action_type" class="regular-text">
                            <option value="redirect" <?php selected($instant_popup_builder_action_type, 'redirect'); ?>>Redirect to URL</option>
                            <option value="open_popup" <?php selected($instant_popup_builder_action_type, 'open_popup'); ?>>Open Another Popup</option>
                        </select>
                    </div>
                </div>

                <!-- Redirect URL Section -->
                <div class="ipb-actions-redirect-section" id="action_redirect" style="display: <?php echo esc_attr(($instant_popup_builder_action_click === 'yes' && $instant_popup_builder_action_type === 'redirect') ? 'block' : 'none'); ?>;">
                    
                    <!-- Redirect URL Input Row -->
                    <div class="ipb-actions-row">
                        <div class="ipb-actions-label">
                            <label for="redirect_url">Redirect URL</label>
                        </div>
                        <div class="ipb-actions-control">
                            <input type="url" name="redirect_url" id="redirect_url" class="regular-text" placeholder="https://example.com" value="<?php echo esc_attr($instant_popup_builder_redirect_url); ?>" style="height: 40px;">
                            <p class="ipb-actions-helper">Include https:// in the URL.</p>
                        </div>
                    </div>

                    <!-- Redirect Timing & New Tab Row -->
                    <div class="ipb-actions-row">
                        <div class="ipb-actions-label">
                            <label for="redirect_delay_seconds">When to redirect</label>
                        </div>
                        <div class="ipb-actions-control">
                            <div style="display: flex; align-items: center; gap: 16px; flex-wrap: wrap;">
                                <?php $ipb_rds_mode = ($instant_popup_builder_redirect_delay_seconds > 0) ? 'custom' : '0'; ?>
                                <select name="redirect_delay_seconds" id="redirect_delay_seconds" class="regular-text" style="flex: 1; min-width: 200px;">
                                    <option value="0" <?php echo ($ipb_rds_mode === '0') ? 'selected' : ''; ?>><?php esc_html_e( 'Instantly', 'instant-popup-builder' ); ?></option>
                                    <option value="custom" <?php echo ($ipb_rds_mode === 'custom') ? 'selected' : ''; ?>><?php esc_html_e( 'Custom', 'instant-popup-builder' ); ?></option>
                                </select>
                                <div id="redirect_delay_custom_wrapper" style="display: <?php echo ($ipb_rds_mode === 'custom') ? 'flex' : 'none'; ?>; align-items: center; gap: 6px;">
                                    <input type="number" name="redirect_delay_custom_seconds" id="redirect_delay_custom_seconds" min="1" max="60" step="1" value="<?php echo esc_attr($instant_popup_builder_redirect_delay_seconds > 0 ? $instant_popup_builder_redirect_delay_seconds : 3); ?>" style="width: 80px; height: 40px;">
                                    <span><?php esc_html_e( 'seconds', 'instant-popup-builder' ); ?></span>
                                </div>
                                <label style="display: flex; align-items: center; gap: 6px; margin: 0; font-weight: 400;">
                                    <!-- Submit a deterministic value even if JS doesn't run -->
                                    <input type="hidden" name="action_new_tab" value="no">
                                    <input type="checkbox" name="action_new_tab" id="action_new_tab" value="yes" <?php checked($instant_popup_builder_action_new_tab, 'yes'); ?>>
                                    Open in new tab
                                </label>
                            </div>
                            <p class="ipb-actions-helper">Choose "Instantly" to redirect immediately, or "Custom" to set a delay in seconds and show a message first.</p>
                        </div>
                    </div>
                </div>

                <!-- Popup Selector Section -->
                <div class="ipb-actions-popup-section" id="action_popup_selector" style="display: <?php echo esc_attr(($instant_popup_builder_action_click === 'yes' && $instant_popup_builder_action_type === 'open_popup') ? 'block' : 'none'); ?>;">
                    <div class="ipb-actions-row">
                        <div class="ipb-actions-label">
                            <label for="action_popup_id">Select Popup to Open</label>
                        </div>
                        <div class="ipb-actions-control">
                            <select name="action_popup_id" id="action_popup_id" class="regular-text">
                                <option value="">-- Select a Popup --</option>
                                <?php
                                if ($instant_popup_builder_all_popups) {
                                    foreach ($instant_popup_builder_all_popups as $popup) {
                                        // Don't show current popup in the list to prevent recursion
                                        if ($instant_popup_builder_edit_id > 0 && $popup->id == $instant_popup_builder_edit_id) {
                                            continue;
                                        }
                                        $popup_label = esc_html($popup->title ?? '') . ' (' . esc_html(ucfirst($popup->type ?? '')) . ')';
                                        echo '<option value="' . esc_attr($popup->id ?? '') . '" ' . selected($instant_popup_builder_action_popup_id, $popup->id, false) . '>' . esc_html($popup_label) . '</option>';
                                    }
                                }
                                ?>
                            </select>
                            <?php if ($instant_popup_builder_action_popup_id && $instant_popup_builder_selected_popup_status && $instant_popup_builder_selected_popup_status !== 'publish'): ?>
                                <div class="ipb-warning-message" style="margin-top: 10px; padding: 10px; background: #fff3cd; border-left: 4px solid #ffc107; color: #856404;">
                                    <strong>⚠️ Warning:</strong> The selected popup is currently <strong><?php echo esc_html(ucfirst($instant_popup_builder_selected_popup_status)); ?></strong> and will not be shown to visitors. Please publish it to make this action work.
                                </div>
                            <?php elseif ($instant_popup_builder_action_popup_id && !$instant_popup_builder_selected_popup_status): ?>
                                <div class="ipb-error-message" style="margin-top: 10px; padding: 10px; background: #f8d7da; border-left: 4px solid #dc3545; color: #721c24;">
                                    <strong>❌ Error:</strong> The selected popup no longer exists. Please select a different popup.
                                </div>
                            <?php endif; ?>
                            <p class="ipb-actions-helper">Only published popups will be shown to visitors. If the selected popup is inactive, the action will not work.</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</div>
</div>
</div>
