<?php

// Settings page renderer shared between tab and submenu.
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
if ( !function_exists( 'teoai_render_settings_page' ) ) {
    function teoai_render_settings_page(  $nonce, $active_tab = 'tab-ignored-fields-objects'  ) {
        ?>

			<!-- General tab -->
			<div class="nav-tab-content<?php 
        echo ( $active_tab === 'tab-general' ? ' nav-tab-content-active' : '' );
        ?>" id="nav-tab-content-tab-general">
				<div>
				
					<form action='' method='POST' id='settings_form_general'>

							<br><h3><?php 
        esc_html_e( 'License', 'events-optimizer' );
        ?></h3>
                            <div class="teoai-info-box">
								<?php 
        esc_html_e( 'Upgrade to Events Optimizer Pro and turn your events calendar into a powerful, automated growth tool:', 'events-optimizer' );
        ?>
								<ul>
								<li><?php 
        esc_html_e( 'Create engaging, high-quality event, venue, and organizer descriptions with AI', 'events-optimizer' );
        ?></li>
								<li><?php 
        esc_html_e( 'Automatically find and add latest events specific to your location', 'events-optimizer' );
        ?></li>
								<li><?php 
        esc_html_e( 'Clean up your database by detecting and merging duplicate venues and organizers', 'events-optimizer' );
        ?></li>
								<li><?php 
        esc_html_e( 'Enhance venue and organizer details with accurate data from Google Places', 'events-optimizer' );
        ?></li>
								<li><?php 
        esc_html_e( 'Discover all premium features and unlock the full potential of Events Optimizer on', 'events-optimizer' );
        ?>				
								<a href="https://www.events-optimizer.com" target="_blank" rel="noopener noreferrer">
								<?php 
        esc_html_e( 'our website!', 'events-optimizer' );
        ?>
								</a></li>
								</ul>
								<a href="https://checkout.freemius.com/mode/dialog/plugin/8391/plan/13936/" class="button" target="_blank" rel="noopener noreferrer"><?php 
        esc_attr_e( 'Get licence key', 'events-optimizer' );
        ?></a>
							</div>

							<br><br><h3><?php 
        esc_html_e( 'Pagination', 'events-optimizer' );
        ?></h3>
							<div class="teoai-info-box">
								<?php 
        esc_html_e( 'Controls how many items are processed at once. Lower values are safer and help avoid timeouts on slower servers.', 'events-optimizer' );
        ?>
							</div>					
							<table class="form-table">
								<tr valign="top">
								<th scope="row"><?php 
        esc_html_e( 'Maximum results per page', 'events-optimizer' );
        ?></th>
								<td><input type="text" name="max_results_per_page" id="max_results_per_page" size="5" value="<?php 
        echo esc_attr( get_option( 'teoai_max_results_per_page' ) );
        ?>"/>
									<?php 
        esc_html_e( 'Maximum: 20', 'events-optimizer' );
        ?></td>
								</tr>
								<!--
								<tr valign="top">
								<th scope="row"><?php 
        esc_html_e( 'Remove settings during uninstall?', 'events-optimizer' );
        ?> </th>
								<td><input type="checkbox" name="remove_settings" id="remove_settings" value="1" <?php 
        checked( get_option( 'teoai_remove_settings' ), 1 );
        ?>/></td>
								</tr>
								-->
							</table>

							<br><h3><?php 
        esc_html_e( 'Duplicate venues / organizers', 'events-optimizer' );
        ?></h3>											
                        	<div class="teoai-info-box">
								<?php 
        esc_html_e( 'These settings control how strictly Events Optimizer detects duplicates.', 'events-optimizer' );
        ?>
								<?php 
        esc_html_e( 'Lower values reduce false matches but may miss similar entries.', 'events-optimizer' );
        ?><br>
								<?php 
        esc_html_e( 'How duplicates are detected:', 'events-optimizer' );
        ?>
								<ul>
								<li><?php 
        esc_html_e( 'Venues are compared by name, address, and the first three characters of the ZIP code.', 'events-optimizer' );
        ?></li>
								<li><?php 
        esc_html_e( 'Organizers are compared by name only.', 'events-optimizer' );
        ?></li>				
								</ul>
							</div>
							<table class="form-table">	
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'How strictly venues are matched', 'events-optimizer' );
        ?></th>
									<td>
										<input type="text" name="duplicate_venues_levenshtein" id="duplicate_venues_levenshtein" size="5" value="<?php 
        echo esc_attr( get_option( 'teoai_duplicate_venues_levenshtein' ) );
        ?>"/>
										<?php 
        esc_html_e( '0 = exact match, recommended: 0.3 - 0.5', 'events-optimizer' );
        ?>
									</td>
								</tr>
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'How strictly organizers are matched', 'events-optimizer' );
        ?></th>
									<td>
										<input type="text" name="duplicate_organizers_levenshtein" id="duplicate_organizers_levenshtein" size="5" value="<?php 
        echo esc_attr( get_option( 'teoai_duplicate_organizers_levenshtein' ) );
        ?>"/>
										<?php 
        esc_html_e( '0 = exact match, recommended: 0.15 - 0.3', 'events-optimizer' );
        ?>
									</td>
								</tr>								
							</table>

							<br><br>
							<input type='submit' name='action' class='button-primary teoai-save-settings' value='<?php 
        esc_html_e( 'Save changes', 'events-optimizer' );
        ?>' />
						<p>
							<div class="teoai-status" style="display:none;"></div>
							<div class="teoai-loading" style="display:none;"><?php 
        esc_html_e( 'SAVING', 'events-optimizer' );
        ?></div>
						</p>
					</form>
				</div>
			</div>

            <!-- Add Settings content to tabs -->
			<div class="nav-tab-content<?php 
        echo ( $active_tab === 'tab-ignored-fields-objects' ? ' nav-tab-content-active' : '' );
        ?>" id="nav-tab-content-tab-ignored-fields-objects">
				<div>
					<form action='' method='POST' id='settings_form'>
						<div>

							<br><h3><?php 
        esc_html_e( 'Ignored fields', 'events-optimizer' );
        ?></h3>				
							<div class="teoai-info-box">
								<?php 
        esc_html_e( 'Selected fields will be skipped during data validation checks.', 'events-optimizer' );
        ?><br>				
							</div>
											
							<br><h3><?php 
        esc_html_e( 'Venues', 'events-optimizer' );
        ?></h3>
							<table class="form-table">	
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Description', 'events-optimizer' );
        ?></th>
									<td>
										<input type="checkbox" name="ignored_field_venue_description" id="ignored_field_venue_description" value="true" <?php 
        checked( get_option( 'teoai_ignored_field_venue_description' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									</td>
								</tr>                        
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Address', 'events-optimizer' );
        ?></th>
									<td>
										<input type="checkbox" name="ignored_field_venue_address" id="ignored_field_venue_address" value="true" <?php 
        checked( get_option( 'teoai_ignored_field_venue_address' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									</td>
								</tr>
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'ZIP', 'events-optimizer' );
        ?></th>
									<td>
										<input type="checkbox" name="ignored_field_venue_zip" id="ignored_field_venue_zip" value="true" <?php 
        checked( get_option( 'teoai_ignored_field_venue_zip' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									</td>
								</tr>
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'City', 'events-optimizer' );
        ?></th>
									<td>
										<input type="checkbox" name="ignored_field_venue_city" id="ignored_field_venue_city" value="true" <?php 
        checked( get_option( 'teoai_ignored_field_venue_city' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									</td>
								</tr>
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Province', 'events-optimizer' );
        ?></th>
									<td><input type="checkbox" name="ignored_field_venue_province" id="ignored_field_venue_province" value="true" <?php 
        checked( get_option( 'teoai_ignored_field_venue_province' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									</td>
								</tr>
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'State', 'events-optimizer' );
        ?></th>
									<td><input type="checkbox" name="ignored_field_venue_state" id="ignored_field_venue_state" value="true" <?php 
        checked( get_option( 'teoai_ignored_field_venue_state' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									</td>
								</tr>
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Country', 'events-optimizer' );
        ?></th>
									<td><input type="checkbox" name="ignored_field_venue_country" id="ignored_field_venue_country" value="true" <?php 
        checked( get_option( 'teoai_ignored_field_venue_country' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									</td>
								</tr>  
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Phone', 'events-optimizer' );
        ?></th>
									<td><input type="checkbox" name="ignored_field_venue_phone" id="ignored_field_venue_phone" value="true" <?php 
        checked( get_option( 'teoai_ignored_field_venue_phone' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									</td>
								</tr>  
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Website', 'events-optimizer' );
        ?></th>
									<td><input type="checkbox" name="ignored_field_venue_website" id="ignored_field_venue_website" value="true" <?php 
        checked( get_option( 'teoai_ignored_field_venue_website' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									</td>
								</tr>
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Business Status', 'events-optimizer' );
        ?></th>
									<td><input type="checkbox" name="ignored_field_venue_business_status" id="ignored_field_venue_business_status" value="true" <?php 
        checked( get_option( 'teoai_ignored_field_venue_business_status' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									</td>
								</tr>																											
							</table>

							<br><h3><?php 
        esc_html_e( 'Organizers', 'events-optimizer' );
        ?></h3>
							<table class="form-table">	
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Description', 'events-optimizer' );
        ?></th>
									<td><input type="checkbox" name="ignored_field_organizer_description" id="ignored_field_organizer_description" value="true" <?php 
        checked( get_option( 'teoai_ignored_field_organizer_description' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									</td>
								</tr>								
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Phone', 'events-optimizer' );
        ?></th>
									<td><input type="checkbox" name="ignored_field_organizer_phone" id="ignored_field_organizer_phone" value="true" <?php 
        checked( get_option( 'teoai_ignored_field_organizer_phone' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									</td>
								</tr>	
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Website', 'events-optimizer' );
        ?></th>
									<td><input type="checkbox" name="ignored_field_organizer_website" id="ignored_field_organizer_website" value="true" <?php 
        checked( get_option( 'teoai_ignored_field_organizer_website' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									</td>
								</tr>																				
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Mail', 'events-optimizer' );
        ?></th>
									<td><input type="checkbox" name="ignored_field_organizer_mail" id="ignored_field_organizer_mail" value="true" <?php 
        checked( get_option( 'teoai_ignored_field_organizer_mail' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									</td>
								</tr>
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Business Status', 'events-optimizer' );
        ?></th>
									<td><input type="checkbox" name="ignored_field_organizer_business_status" id="ignored_field_organizer_business_status" value="true" <?php 
        checked( get_option( 'teoai_ignored_field_organizer_business_status' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									</td>
								</tr>	
							</table>

							<br><h3><?php 
        esc_html_e( 'Events', 'events-optimizer' );
        ?></h3>
							<table class="form-table">	
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Description', 'events-optimizer' );
        ?></th>
									<td><input type="checkbox" name="ignored_field_event_description" id="ignored_field_event_description" value="true" <?php 
        checked( get_option( 'teoai_ignored_field_event_description' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									</td>
								</tr>      
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Start', 'events-optimizer' );
        ?></th>
									<td><input type="checkbox" name="ignored_field_event_start" id="ignored_field_event_start" value="true" <?php 
        checked( get_option( 'teoai_ignored_field_event_start' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									</td>
								</tr>  
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'End', 'events-optimizer' );
        ?></th>
									<td><input type="checkbox" name="ignored_field_event_end" id="ignored_field_event_end" value="true" <?php 
        checked( get_option( 'teoai_ignored_field_event_end' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									</td>
								</tr>                              
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Venue', 'events-optimizer' );
        ?></th>
									<td><input type="checkbox" name="ignored_field_event_venue" id="ignored_field_event_venue" value="true" <?php 
        checked( get_option( 'teoai_ignored_field_event_venue' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									</td>
								</tr>                                         
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Organizer', 'events-optimizer' );
        ?></th>
									<td><input type="checkbox" name="ignored_field_event_organizer" id="ignored_field_event_organizer" value="true" <?php 
        checked( get_option( 'teoai_ignored_field_event_organizer' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									</td>
								</tr>
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Website', 'events-optimizer' );
        ?></th>
									<td><input type="checkbox" name="ignored_field_event_website" id="ignored_field_event_website" value="true" <?php 
        checked( get_option( 'teoai_ignored_field_event_website' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									</td>
								</tr>  
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Currency Symbol', 'events-optimizer' );
        ?></th>
									<td><input type="checkbox" name="ignored_field_event_currency_symbol" id="ignored_field_event_currency_symbol" value="true" <?php 
        checked( get_option( 'teoai_ignored_field_event_currency_symbol' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									</td>
								</tr>
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Cost', 'events-optimizer' );
        ?></th>
									<td><input type="checkbox" name="ignored_field_event_cost" id="ignored_field_event_cost" value="true" <?php 
        checked( get_option( 'teoai_ignored_field_event_cost' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									</td>
								</tr>
							</table>

							<br><h3><?php 
        esc_html_e( 'Ignored objects', 'events-optimizer' );
        ?></h3>				
							<div class="teoai-info-box">
								<?php 
        esc_html_e( 'These venues, organizers, and events were manually marked as “Ignore”.', 'events-optimizer' );
        ?>
								<ul>
								<li><?php 
        esc_html_e( 'They are excluded from validation checks and Google Events imports.', 'events-optimizer' );
        ?></li>
								<li><?php 
        esc_html_e( 'You can reset this list if you want to checked these objects again.', 'events-optimizer' );
        ?></li>				
								</ul>
							</div>
							<table class="form-table">	
								<tr valign="top">
								<th scope="row">
									<input type="button" name="action" class="button reset-objects-ignored-button" data-status="ignored" value="<?php 
        esc_html_e( 'Reset list', 'events-optimizer' );
        ?>" <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
								</th>
								<td>
									<div class="row">					
										<?php 
        $ignored_and_added_objects = maybe_unserialize( get_option( 'teoai_ignored_and_added_objects' ) );
        echo '<p><strong>' . esc_html__( 'Venues', 'events-optimizer' ) . '</strong></p>';
        if ( is_array( $ignored_and_added_objects ) ) {
            $venues = array_filter( $ignored_and_added_objects, function ( $object ) {
                return isset( $object['status'], $object['type'] ) && $object['status'] === 'ignored' && $object['type'] === 'tribe_venue';
            } );
            if ( empty( $venues ) ) {
                echo '--<br>';
            } else {
                foreach ( $venues as $venue ) {
                    $object_id = $venue['id'];
                    $post_id = $venue['post_id'];
                    $post_title = get_the_title( $post_id );
                    $edit_url = "/wp-admin/post.php?post=' . {$post_id} . '&action=edit";
                    echo "<div id='object_" . esc_attr( $object_id ) . "'>" . esc_html( $post_title ) . "</div>";
                }
            }
        } else {
            echo '--<br>';
        }
        echo '</div><br>';
        echo '<p><strong>' . esc_html__( 'Organizers', 'events-optimizer' ) . '</strong></p>';
        if ( is_array( $ignored_and_added_objects ) ) {
            $organizers = array_filter( $ignored_and_added_objects, function ( $object ) {
                return $object['status'] === 'ignored' && $object['type'] === 'tribe_organizer';
            } );
            if ( empty( $organizers ) ) {
                echo '--<br>';
            } else {
                foreach ( $organizers as $organizer ) {
                    $object_id = $organizer['id'];
                    $post_id = $organizer['post_id'];
                    $post_title = stripslashes( get_the_title( $post_id ) );
                    $edit_url = "/wp-admin/post.php?post=' . {$post_id} . '&action=edit";
                    echo "<div id='object_" . esc_attr( $object_id ) . "'>" . esc_html( $post_title ) . "</div>";
                }
            }
        } else {
            echo '--<br>';
        }
        echo '</div><br>';
        echo '<p><strong>' . esc_html__( 'Events', 'events-optimizer' ) . '</strong></p>';
        if ( is_array( $ignored_and_added_objects ) ) {
            $events = array_filter( $ignored_and_added_objects, function ( $object ) {
                return $object['status'] === 'ignored' && $object['type'] === 'tribe_events';
            } );
            if ( empty( $events ) ) {
                echo '--<br>';
            } else {
                foreach ( $events as $event ) {
                    $object_id = esc_attr( $event['id'] );
                    $post_id = esc_attr( $event['post_id'] );
                    $title_gp = esc_html( stripslashes( $event['title_gp'] ) );
                    $post_title = esc_html( get_the_title( $post_id ) );
                    $edit_url = esc_url( "/wp-admin/post.php?post={$post_id}&action=edit" );
                    $start_datetime_gp = esc_html( date_format( date_create( $event['start_datetime_gp'] ), get_option( 'date_format' ) . ", H:i" ) );
                    if ( $post_id !== '' ) {
                        echo "<div id='object_" . esc_attr( $object_id ) . "'>" . esc_html( $post_title ) . "</div>";
                    } else {
                        echo "<div id='object_" . esc_attr( $object_id ) . "'>" . esc_html( $title_gp ) . " (" . esc_html( $start_datetime_gp ) . ")</div>";
                    }
                }
            }
        } else {
            echo '--<br>';
        }
        echo '</div>';
        ?>
									</div>						
								</td>
								</tr>							
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Show ignored objects', 'events-optimizer' );
        ?></th>
									<td>
										<input type="checkbox" name="show_ignored_objects" id="show_ignored_objects" value="true" <?php 
        checked( filter_var( get_option( 'teoai_show_ignored_objects' ), FILTER_VALIDATE_BOOLEAN ), true );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
										<?php 
        esc_html_e( 'Display items that are currently excluded from checks and imports.', 'events-optimizer' );
        ?>
									</td>
								</tr>
							</table>

							<script type="text/javascript">
								if ( typeof window.remove_object !== 'function' ) {
									window.remove_object = function(id, $row) {
										var $target = ($row && $row.length) ? $row : jQuery(".teoai-remove-object[data-object-id='" + id + "']").closest("[id^='object_']");
										if ( ! $target.length ) {
											return false;
										}

										$target.attr('disabled','disabled').css('opacity',0.4);
										jQuery.ajax({
											type: "POST",
											url: "<?php 
        echo esc_url( admin_url( 'admin-ajax.php' ) );
        ?>",
											data: {
												action: 'remove_obj',
												_ajax_nonce: '<?php 
        echo esc_attr( $nonce );
        ?>',
												id: id
											},
											beforeSend: function() {
												$target.fadeOut('fast');
											},
											success: function() {
												$target.remove();
											},
											error: function() {
												$target.css('opacity', 1).fadeIn('fast');
											}
										});
										return false;
									};
								}
							</script>

							<br><br>
							<input type='submit' name='action' class='button-primary teoai-save-settings' value='<?php 
        esc_html_e( 'Save changes', 'events-optimizer' );
        ?>' />
						</div>
					</form>
					<p>
						<div id='show_tab_settings' class="teoai-status" style="display:none;"></div>
						<div id='loading_tab_settings' class="teoai-loading" style="display:none;"><?php 
        esc_html_e( 'SAVING', 'events-optimizer' );
        ?></div>
					</p>
				</div>
			</div>

			<div class="nav-tab-content<?php 
        echo ( $active_tab === 'tab-api-credentials' ? ' nav-tab-content-active' : '' );
        ?>" id="nav-tab-content-tab-api-credentials">
				<div>
					<form action='' method='POST' id='settings_form_api'>
						<div>
							<br><h3><?php 
        esc_html_e( 'API credentials', 'events-optimizer' );
        ?></h3>
							<div class="teoai-info-box">
								<?php 
        echo '<strong>' . esc_html__( 'To use Events Optimizer with its full feature set, you need API access for data enrichment and AI-powered content generation.', 'events-optimizer' ) . '</strong><br>';
        echo esc_html__( 'Required for full functionality:', 'events-optimizer' ) . '<br>';
        echo '<ul>';
        echo '<li>' . esc_html__( 'DataForSEO API', 'events-optimizer' ) . '<br>';
        echo '<li>' . esc_html__( 'Google API', 'events-optimizer' ) . '<br>';
        echo '<li>' . esc_html__( 'At least one AI provider (for example OpenAI, Anthropic, Mistral, Google or OpenRouter)', 'events-optimizer' ) . '</li>';
        echo '</ul>';
        echo '<strong>' . esc_html__( 'If you are unsure which AI provider or model to choose, we recommend OpenRouter. It gives you access to multiple AI models from different providers using a single API key.', 'events-optimizer' ) . '</strong>';
        echo '<ul>';
        echo '<li>' . esc_html__( 'Compare AI model quality, speed, and pricing on ', 'events-optimizer' ) . ' <a href="https://artificialanalysis.ai/models" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Artificial Analysis', 'events-optimizer' ) . '</a></li>';
        echo '<li>' . esc_html__( 'Step-by-step instructions for setting up API keys are available via the tutorials. Setup usually takes less than 5 minutes.', 'events-optimizer' ) . '</li>';
        echo '<li>' . esc_html__( 'If available, the Google API key is automatically preset from the', 'events-optimizer' ) . ' ';
        // Path to Events Calendar settings changed from V5.9 to V6.0
        $plugin_arr = get_plugin_data( WP_PLUGIN_DIR . '/the-events-calendar/the-events-calendar.php', false, false );
        if ( $plugin_arr['Version'] < 6 ) {
            echo '<a href="/wp-admin/edit.php?page=tribe-common&tab=addons&post_type=tribe_events" target="_blank" rel="noopener noreferrer">';
        } else {
            echo '<a href="/wp-admin/edit.php?page=tec-events-settings&tab=addons&post_type=tribe_events" target="_blank" rel="noopener noreferrer">';
        }
        echo esc_html__( 'Events Calendar settings', 'events-optimizer' ) . '</a>.</li> ';
        echo '</ul>';
        ?>
							</div>			
							<table class="form-table">		
							<tr valign="top">							
								<th scope="row"><?php 
        esc_html_e( 'DataForSEO API login', 'events-optimizer' );
        ?>*</th>
								<td>
									<input type="text" name="dataforseo_api_login" id="dataforseo_api_login" size="40"  value="<?php 
        echo esc_attr( get_option( 'teoai_dataforseo_api_login' ) );
        ?>"  <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									<?php 
        echo '<a href="https://www.events-optimizer.com/events-optimizer/settings/dataforseo-setup/" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Manual', 'events-optimizer' ) . ' <img src="' . esc_url( plugin_dir_url( __FILE__ ) ) . 'assets/images/external-link.png" class="external-link-icon" alt="External Link"></a>&nbsp;&nbsp;';
        echo '<a href="https://app.dataforseo.com/api-access?aff=142846" target="_blank" rel="noopener noreferrer">' . esc_html__( 'API Credentials', 'events-optimizer' ) . ' <img src="' . esc_url( plugin_dir_url( __FILE__ ) ) . 'assets/images/external-link.png" class="external-link-icon" alt="External Link"></a>&nbsp;&nbsp;';
        echo '<a href="https://dataforseo.com/pricing/serp/serp-api?aff=142846" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Pricing', 'events-optimizer' ) . ' <img src="' . esc_url( plugin_dir_url( __FILE__ ) ) . 'assets/images/external-link.png" class="external-link-icon" alt="External Link"></a>&nbsp;&nbsp;';
        ?>
								</td>
							</tr>	
							<tr valign="top">							
								<th scope="row"><?php 
        esc_html_e( 'DataForSEO API password', 'events-optimizer' );
        ?>*</th>
								<td>
									<input type="text" name="dataforseo_api_password" id="dataforseo_api_password" size="40"  value="<?php 
        echo esc_attr( get_option( 'teoai_dataforseo_api_password' ) );
        ?>"  <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
								</td>
							</tr>	
							<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Google API key', 'events-optimizer' );
        ?>*</th>
									<td>
										<input type="text" name="google_places_api_key" id="google_places_api_key" size="40" value="<?php 
        echo esc_attr( get_option( 'teoai_google_places_api_key' ) );
        ?>" <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
										<?php 
        echo '<a href="https://www.events-optimizer.com/events-optimizer/settings/google-cloud-console-setup/" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Manual', 'events-optimizer' ) . ' <img src="' . esc_url( plugin_dir_url( __FILE__ ) ) . 'assets/images/external-link.png" class="external-link-icon" alt="External Link"></a>&nbsp;&nbsp;';
        echo '<a href="https://console.cloud.google.com/apis/credentials" target="_blank" rel="noopener noreferrer">' . esc_html__( 'API keys', 'events-optimizer' ) . ' <img src="' . esc_url( plugin_dir_url( __FILE__ ) ) . 'assets/images/external-link.png" class="external-link-icon" alt="External Link"></a>&nbsp;&nbsp;';
        echo '<a href="https://ai.google.dev/" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Documentation', 'events-optimizer' ) . ' <img src="' . esc_url( plugin_dir_url( __FILE__ ) ) . 'assets/images/external-link.png" class="external-link-icon" alt="External Link"></a>&nbsp;&nbsp;';
        ?>
									</td>                        
								</tr>		
							</tr>								
							<tr valign="top">					
									<th scope="row"><?php 
        esc_html_e( 'OpenRouter API key', 'events-optimizer' );
        ?></th>
									<td>
										<input type="text" name="openrouter_api_key" id="openrouter_api_key" size="40"  value="<?php 
        echo esc_attr( get_option( 'teoai_openrouter_api_key' ) );
        ?>"  <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
										<?php 
        echo '<a href="https://www.events-optimizer.com/events-optimizer/settings/openrouter-setup/" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Manual', 'events-optimizer' ) . ' <img src="' . esc_url( plugin_dir_url( __FILE__ ) ) . 'assets/images/external-link.png" class="external-link-icon" alt="External Link"></a>&nbsp;&nbsp;';
        echo '<a href="https://openrouter.ai/settings/keys" target="_blank" rel="noopener noreferrer">' . esc_html__( 'API keys', 'events-optimizer' ) . ' <img src="' . esc_url( plugin_dir_url( __FILE__ ) ) . 'assets/images/external-link.png" class="external-link-icon" alt="External Link"></a>&nbsp;&nbsp;';
        echo '<a href="https://openrouter.ai/models?order=pricing-low-to-high" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Models & Pricing', 'events-optimizer' ) . ' <img src="' . esc_url( plugin_dir_url( __FILE__ ) ) . 'assets/images/external-link.png" class="external-link-icon" alt="External Link"></a>&nbsp;&nbsp;';
        ?>
									</td>
								</tr>
							</tr>									
							<tr valign="top">					
									<th scope="row"><?php 
        esc_html_e( 'OpenAI API key', 'events-optimizer' );
        ?></th>
									<td>
										<input type="text" name="openai_api_key" id="openai_api_key" size="40"  value="<?php 
        echo esc_attr( get_option( 'teoai_openai_api_key' ) );
        ?>"  <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
										<?php 
        echo '<a href="https://www.events-optimizer.com/events-optimizer/settings/open-ai-platform-setup/" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Manual', 'events-optimizer' ) . ' <img src="' . esc_url( plugin_dir_url( __FILE__ ) ) . 'assets/images/external-link.png" class="external-link-icon" alt="External Link"></a>&nbsp;&nbsp;';
        echo '<a href="https://platform.openai.com/api-keys" target="_blank" rel="noopener noreferrer">' . esc_html__( 'API keys', 'events-optimizer' ) . ' <img src="' . esc_url( plugin_dir_url( __FILE__ ) ) . 'assets/images/external-link.png" class="external-link-icon" alt="External Link"></a>&nbsp;&nbsp;';
        echo '<a href="https://platform.openai.com/docs/pricing" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Pricing', 'events-optimizer' ) . ' <img src="' . esc_url( plugin_dir_url( __FILE__ ) ) . 'assets/images/external-link.png" class="external-link-icon" alt="External Link"></a>&nbsp;&nbsp;';
        ?>
									</td>
								</tr>
							</tr>
							<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Anthropic API key', 'events-optimizer' );
        ?></th>
									<td>
										<input type="text" name="anthropic_claude_api_key" id="anthropic_claude_api_key" size="40" value="<?php 
        echo esc_attr( get_option( 'teoai_anthropic_claude_api_key' ) );
        ?>" <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
										<?php 
        echo '<a href="https://www.events-optimizer.com/events-optimizer/settings/anthropic-console-setup/" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Manual', 'events-optimizer' ) . ' <img src="' . esc_url( plugin_dir_url( __FILE__ ) ) . 'assets/images/external-link.png" class="external-link-icon" alt="External Link"></a>&nbsp;&nbsp;';
        echo '<a href="https://console.anthropic.com/settings/keys" target="_blank" rel="noopener noreferrer">' . esc_html__( 'API keys', 'events-optimizer' ) . ' <img src="' . esc_url( plugin_dir_url( __FILE__ ) ) . 'assets/images/external-link.png" class="external-link-icon" alt="External Link"></a>&nbsp;&nbsp;';
        echo '<a href="https://www.anthropic.com/pricing" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Pricing', 'events-optimizer' ) . ' <img src="' . esc_url( plugin_dir_url( __FILE__ ) ) . 'assets/images/external-link.png" class="external-link-icon" alt="External Link"></a>&nbsp;&nbsp;';
        ?>
									</td>                        
								</tr>		
							</tr>	
							<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Mistral API key', 'events-optimizer' );
        ?></th>
									<td>
										<input type="text" name="mistral_api_key" id="mistral_api_key" size="40" value="<?php 
        echo esc_attr( get_option( 'teoai_mistral_api_key' ) );
        ?>" <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
										<?php 
        echo '<a href="https://www.events-optimizer.com/events-optimizer/settings/mistral-platform-setup/" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Manual', 'events-optimizer' ) . ' <img src="' . esc_url( plugin_dir_url( __FILE__ ) ) . 'assets/images/external-link.png" class="external-link-icon" alt="External Link"></a>&nbsp;&nbsp;';
        echo '<a href="https://console.mistral.ai/api-keys/" target="_blank" rel="noopener noreferrer">' . esc_html__( 'API keys', 'events-optimizer' ) . ' <img src="' . esc_url( plugin_dir_url( __FILE__ ) ) . 'assets/images/external-link.png" class="external-link-icon" alt="External Link"></a>&nbsp;&nbsp;';
        echo '<a href="https://mistral.ai/technology/#pricing" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Pricing', 'events-optimizer' ) . ' <img src="' . esc_url( plugin_dir_url( __FILE__ ) ) . 'assets/images/external-link.png" class="external-link-icon" alt="External Link"></a>&nbsp;&nbsp;';
        ?>
									</td>                        
								</tr>		
							</tr>		
							<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Groq API key', 'events-optimizer' );
        ?></th>
									<td>
										<input type="text" name="groq_api_key" id="groq_api_key" size="40" value="<?php 
        echo esc_attr( get_option( 'teoai_groq_api_key' ) );
        ?>" <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
										<?php 
        echo '<a href="https://www.events-optimizer.com/events-optimizer/settings/groq-cloud-platform-setup/" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Manual', 'events-optimizer' ) . ' <img src="' . esc_url( plugin_dir_url( __FILE__ ) ) . 'assets/images/external-link.png" class="external-link-icon" alt="External Link"></a>&nbsp;&nbsp;';
        echo '<a href="https://console.groq.com/keys" target="_blank" rel="noopener noreferrer">' . esc_html__( 'API keys', 'events-optimizer' ) . ' <img src="' . esc_url( plugin_dir_url( __FILE__ ) ) . 'assets/images/external-link.png" class="external-link-icon" alt="External Link"></a>&nbsp;&nbsp;';
        echo '<a href="https://groq.com/pricing/" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Pricing', 'events-optimizer' ) . ' <img src="' . esc_url( plugin_dir_url( __FILE__ ) ) . 'assets/images/external-link.png" class="external-link-icon" alt="External Link"></a>&nbsp;&nbsp;';
        ?>	
									</td>                        
								</tr>		
							</tr>														
							<tr valign="top">							
								<td scope="row" colspan="2"><?php 
        echo esc_html__( '* Required for full functionality of the plugin', 'events-optimizer' );
        ?></td>
							</tr>	
							</table>
							<br><br>
							<input type='submit' name='action' class='button-primary teoai-save-settings' value='<?php 
        esc_html_e( 'Save changes', 'events-optimizer' );
        ?>' />
							<p>
								<div class="teoai-status" style="display:none;"></div>
								<div class="teoai-loading" style="display:none;"><?php 
        esc_html_e( 'SAVING', 'events-optimizer' );
        ?></div>
							</p>
						</div>
					</form>
				</div>
			</div>

			<div class="nav-tab-content<?php 
        echo ( $active_tab === 'tab-google-places' ? ' nav-tab-content-active' : '' );
        ?>" id="nav-tab-content-tab-google-places">
				<div>
					<form action='' method='POST' id='settings_form_google_places'>
						<div>
							<br><h3><?php 
        esc_html_e( 'Google Places', 'events-optimizer' );
        ?></h3>
                                <div class="teoai-info-box">

							<?php 
        echo esc_html__( 'Automatically validate and enrich venue and organizer data using the Google Places API.', 'events-optimizer' ) . '<br>';
        echo esc_html__( 'This helps keep your events information accurate, complete, and up to date.', 'events-optimizer' );
        echo '<ul>';
        echo '<li>' . esc_html__( 'Activate the Google PLACES API for your project in the', 'events-optimizer' ) . ' <a href="https://console.cloud.google.com/marketplace/product/google/places-backend.googleapis.com" target="_blank"  rel="noopener noreferrer">' . esc_html__( 'Google Cloud Console', 'events-optimizer' ) . '</a>.</li>';
        echo '<li> ' . esc_html__( 'Follow the', 'events-optimizer' ) . ' <a href="https://www.events-optimizer.com/events-optimizer/settings/google-cloud-console-setup/" target="_blank" rel="noopener noreferrer">' . esc_html__( 'setup guide', 'events-optimizer' ) . '</a> ' . esc_html__( 'to configure your API key', 'events-optimizer' ) . '.';
        echo ' ' . esc_html__( 'Find more information in the', 'events-optimizer' ) . ' <a href="https://developers.google.com/maps/documentation/places/web-service" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Google Places API documentation', 'events-optimizer' ) . '</a>.</li>';
        echo '<li><a href="https://developers.google.com/maps/documentation/places/web-service/usage-and-billing" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Review Google’s pricing', 'events-optimizer' ) . '</a> ';
        echo esc_html__( 'before enabling this feature.', 'events-optimizer' ) . '</li>';
        echo '</ul>';
        ?>		
							</div>	
																
							<table class="form-table">
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Language', 'events-optimizer' );
        ?></th>
									<td>
										<?php 
        $places_language = get_option( 'teoai_google_places_language' );
        $places_lang_meta = ( function_exists( 'teoai_get_google_translation_languages_meta' ) ? teoai_get_google_translation_languages_meta() : array() );
        $places_lang_last_label = '';
        // if ( isset( $places_lang_meta['last_updated'] ) && $places_lang_meta['last_updated'] ) {
        // 	$places_lang_last_label = sprintf(
        // 		__( 'Last updated: %1$s', 'events-optimizer' ),
        // 		date_i18n( 'd.m.Y, H:i', $places_lang_meta['last_updated'] )
        // 	);
        // }
        $google_places_api_key = get_option( 'teoai_google_places_api_key', '' );
        $places_requires_key = empty( $google_places_api_key );
        ?>
										<div class="teoai-language-picker">
											<select name="google_places_language" id="google_places_language" class="teoai-location-select" data-current="<?php 
        echo esc_attr( $places_language );
        ?>" <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?>></select>
											<!-- <button type="button" class="button" id="google_places_update_languages" data-requires-key="<?php 
        echo ( $places_requires_key ? 'true' : 'false' );
        ?>" <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() || $places_requires_key );
        ?>>
												<?php 
        esc_html_e( 'Update list', 'events-optimizer' );
        ?>
											</button> -->
											<span class="teoai-inline-status">
												<span id="google_places_languages_loading" class="teoai-loading" style="display:none;"></span>
												<span id="google_places_languages_message" class="teoai-status-message" style="display:none;"></span>
											</span>
										</div>
										<div id="google_places_languages_last_updated" class="description teoai-status-line" <?php 
        echo ( empty( $places_lang_last_label ) ? 'style="display:none;"' : '' );
        ?>>
											<?php 
        echo esc_html( $places_lang_last_label );
        ?>
										</div>
									</td>
								</tr>

								<tr valign="top">
								<th scope="row"><?php 
        esc_html_e( 'Phone number format', 'events-optimizer' );
        ?></th>
								<td>
                                    <?php 
        $phone_number_format = sanitize_text_field( get_option( 'teoai_phone_number_format' ) );
        if ( empty( $phone_number_format ) ) {
            $phone_number_format = 'international_phone_number';
            update_option( 'teoai_phone_number_format', $phone_number_format );
        }
        ?>
									<select name="phone_number_format" id="phone_number_format"  <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> >
										<option value="international_phone_number" <?php 
        echo ( $phone_number_format === "international_phone_number" ? 'selected="selected"' : '' );
        ?>><?php 
        esc_html_e( 'International', 'events-optimizer' );
        ?></option>
										<option value="formatted_phone_number" <?php 
        echo ( $phone_number_format === "formatted_phone_number" ? 'selected="selected"' : '' );
        ?>><?php 
        esc_html_e( 'Local', 'events-optimizer' );
        ?></option>
									</select>
								<?php 
        esc_html_e( 'International: +4912345678, local: (089) 12345678', 'events-optimizer' );
        ?>
								</td>
								</tr>

								<tr valign="top">
								<th scope="row"><?php 
        esc_html_e( 'Address format', 'events-optimizer' );
        ?></th>
								<td>
                                    <?php 
        $address_format = sanitize_text_field( get_option( 'teoai_address_format' ) );
        if ( empty( $address_format ) ) {
            $address_format = 'street_number';
            update_option( 'teoai_address_format', $address_format );
        }
        ?>
									<select name="address_format" id="address_format"  <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> >
										<option value="street_number" <?php 
        echo ( $address_format === "street_number" ? 'selected="selected"' : '' );
        ?>><?php 
        esc_html_e( 'Street name + number', 'events-optimizer' );
        ?></option>
										<option value="number_street" <?php 
        echo ( $address_format === "number_street" ? 'selected="selected"' : '' );
        ?>><?php 
        esc_html_e( 'Street number + name', 'events-optimizer' );
        ?></option>
									</select>
								<?php 
        esc_html_e( 'Sesame street 42 vs. 42th Sesame street', 'events-optimizer' );
        ?>
								</td>
								</tr>

								<tr valign="top">
								<th scope="row"><?php 
        esc_html_e( 'Preselection', 'events-optimizer' );
        ?></th>
								<td>
                                    <?php 
        $preselection = sanitize_text_field( get_option( 'teoai_preselection' ) );
        if ( empty( $preselection ) ) {
            $preselection = 'auto_completion';
            update_option( 'teoai_preselection', $preselection );
        }
        ?>
									<select name="preselection" id="preselection"  <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> >
										<option value="auto_completion" <?php 
        echo ( $preselection === "auto_completion" ? 'selected="selected"' : '' );
        ?>><?php 
        esc_html_e( 'Auto completion of missing data', 'events-optimizer' );
        ?></option>
										<option value="full_replacement" <?php 
        echo ( $preselection === "full_replacement" ? 'selected="selected"' : '' );
        ?>><?php 
        esc_html_e( 'Full replacement via Google Places', 'events-optimizer' );
        ?></option>
									</select>
								</td>
								</tr>
							</table>

							<br><h3><?php 
        esc_html_e( 'Fetch data within the organizer form', 'events-optimizer' );
        ?></h3>				
                                <div class="teoai-info-box">
								<strong><?php 
        esc_html_e( 'For advanced users familiar with', 'events-optimizer' );
        ?> 
								<a href="<?php 
        echo esc_url( 'https://www.hostinger.com/tutorials/wordpress-custom-fields' );
        ?>" target="_blank" rel="noopener noreferrer">Custom Fields</a></strong><br><br>
								<?php 
        esc_html_e( 'This feature allows you to fetch and populate organizer data while editing an organizer directly. Learn more about at', 'events-optimizer' );
        ?> 
								<a href="<?php 
        echo esc_url( 'https://developers.google.com/maps/documentation/places/web-service/details#Place' );
        ?>" target="_blank" rel="noopener noreferrer">
								<?php 
        esc_html_e( 'Google Places', 'events-optimizer' );
        ?></a>.<br>
								<ul>
								<li><?php 
        esc_html_e( 'If the following custom field IDs exist, they will be filled automatically to the single organizer form:', 'events-optimizer' );
        ?><br>		
								<?php 
        esc_html_e( 'OrganizerAddress, OrganizerCity, OrganizerZip, OrganizerProvince, OrganizerState, OrganizerCountry, OrganizerCurrentOpeningHours, OrganizerRating', 'events-optimizer' );
        ?></li>												
								<li><?php 
        esc_html_e( 'Optionally map the complete address to any input or textarea field.', 'events-optimizer' );
        ?></li>				
								</ul>
							</div>

							<table class="form-table">	
								<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Field id for full address', 'events-optimizer' );
        ?></th>
									<td>
										<input type="text" name="element_id" id="element_id" size="30" value="<?php 
        echo esc_attr( get_option( 'teoai_element_id' ) );
        ?>"  <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
										<?php 
        esc_html_e( 'Example: content or excerpt', 'events-optimizer' );
        ?>
									</td>
								</tr>
							</table>

							<br><br>
							<input type='submit' name='action' class='button-primary teoai-save-settings' value='<?php 
        esc_html_e( 'Save changes', 'events-optimizer' );
        ?>' />
							<p>
								<div class="teoai-status" style="display:none;"></div>
								<div class="teoai-loading" style="display:none;"><?php 
        esc_html_e( 'SAVING', 'events-optimizer' );
        ?></div>
							</p>
						</div>
					</form>
				</div>
			</div>

			<div class="nav-tab-content<?php 
        echo ( $active_tab === 'tab-ai-content-generation' ? ' nav-tab-content-active' : '' );
        ?>" id="nav-tab-content-tab-ai-content-generation">
				<div>
					<form action='' method='POST' id='settings_form_ai'>
						<div>
							<br><h3><?php 
        esc_html_e( 'Generate descriptions for events, venues and organizers', 'events-optimizer' );
        ?></h3>
                                <div class="teoai-info-box">
								<?php 
        echo esc_html__( 'Descriptions are generated automatically using AI models from OpenAI, Google, Anthropic, or Mistral.', 'events-optimizer' ) . "<br>";
        echo esc_html__( 'If you are unsure which model to choose, we recommend Claude 4.5 Sonnet or GPT-4.1 Mini, as they typically produce high-quality and engaging results.', 'events-optimizer' );
        echo '<ul>';
        echo '<li><strong>' . esc_html__( 'Please note that AI-generated content may contain inaccuracies. Always review and fact-check the generated text before publishing.', 'events-optimizer' ) . '</strong></li>';
        echo '<li>' . esc_html__( 'In rare cases, AI services may be temporarily unavailable. You can check here the status here:', 'events-optimizer' ) . ' <a href="https://status.openai.com/" target="_blank" rel="noopener noreferrer">' . esc_html__( 'OpenAI API', 'events-optimizer' ) . '</a>, ';
        echo '<a href="https://status.gemini.com/" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Google Gemini API', 'events-optimizer' ) . '</a>, ';
        echo '<a href="https://status.anthropic.com/" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Anthropic API', 'events-optimizer' ) . '</a>, ';
        echo '<a href="https://status.mistral-data.com/" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Mistral API', 'events-optimizer' ) . '</a>, ';
        echo '<a href="https://www.helicone.ai/status/provider/Groq" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Groq API', 'events-optimizer' ) . '</a>.</li>';
        echo '</ul>';
        ?>
							</div>
																
							<table class="form-table">

								<tr valign="top">					
								<th scope="row"><?php 
        esc_html_e( 'AI Model', 'events-optimizer' );
        ?></th>
								<td>
								<select name="openai_model" id="openai_model" <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> >  
								<?php 
        $selected_openai_model = sanitize_text_field( get_option( 'teoai_openai_model' ) );
        $openai_model_options = array(
            'claude-opus-4-5'                                     => esc_html__( 'Claude Opus 4.5', 'events-optimizer' ),
            'claude-haiku-4-5'                                    => esc_html__( 'Claude Haiku 4.5', 'events-optimizer' ),
            'claude-sonnet-4-5'                                   => esc_html__( 'Claude Sonnet 4.5', 'events-optimizer' ),
            'gemini-2.5-flash'                                    => esc_html__( 'Gemini 2.5 Flash', 'events-optimizer' ),
            'gemini-2.5-flash-lite'                               => esc_html__( 'Gemini 2.5 Flash-Lite', 'events-optimizer' ),
            'gemini-2.5-pro'                                      => esc_html__( 'Gemini 2.5 Pro', 'events-optimizer' ),
            'gpt-4'                                               => esc_html__( 'GPT-4', 'events-optimizer' ),
            'gpt-4-turbo'                                         => esc_html__( 'GPT-4 Turbo', 'events-optimizer' ),
            'gpt-4o'                                              => esc_html__( 'GPT-4o (Omni)', 'events-optimizer' ),
            'gpt-4o-mini'                                         => esc_html__( 'GPT-4o Mini', 'events-optimizer' ),
            'gpt-4.1'                                             => esc_html__( 'GPT-4.1', 'events-optimizer' ),
            'gpt-4.1-mini'                                        => esc_html__( 'GPT-4.1 Mini', 'events-optimizer' ),
            'gpt-5'                                               => esc_html__( 'GPT-5', 'events-optimizer' ),
            'mistral-small-latest'                                => esc_html__( 'Mistral Small 3.2', 'events-optimizer' ),
            'mistral-medium-latest'                               => esc_html__( 'Mistral Medium 3.1', 'events-optimizer' ),
            'mistral-large-latest'                                => esc_html__( 'Mistral Large 2.1', 'events-optimizer' ),
            'groq/llama-3.1-8b-instant'                           => esc_html__( 'Groq → Llama 3.1-8B', 'events-optimizer' ),
            'groq/llama-3.3-70b-versatile'                        => esc_html__( 'Groq → Llama 3.3-70B', 'events-optimizer' ),
            'openrouter/anthropic/claude-opus-4.5'                => esc_html__( 'OpenRouter -> Claude Opus 4.5', 'events-optimizer' ),
            'openrouter/anthropic/claude-haiku-4.5'               => esc_html__( 'OpenRouter -> Claude Haiku 4.5', 'events-optimizer' ),
            'openrouter/anthropic/claude-sonnet-4.5'              => esc_html__( 'OpenRouter -> Claude Sonnet 4.5', 'events-optimizer' ),
            'openrouter/deepseek/deepseek-r1:nitro'               => esc_html__( 'OpenRouter -> DeepSeek R1 (nitro)', 'events-optimizer' ),
            'openrouter/deepseek/deepseek-r1'                     => esc_html__( 'OpenRouter -> DeepSeek R1', 'events-optimizer' ),
            'openrouter/deepseek/deepseek-v3.2-exp'               => esc_html__( 'OpenRouter -> DeepSeek V3.2-Exp', 'events-optimizer' ),
            'openrouter/deepseek/deepseek-reasoner-v3.2-exp'      => esc_html__( 'OpenRouter -> DeepSeek Reasoner V3.2-Exp', 'events-optimizer' ),
            'openrouter/google/gemini-2.5-flash'                  => esc_html__( 'OpenRouter -> Gemini 2.5 Flash', 'events-optimizer' ),
            'openrouter/google/gemini-2.5-flash-lite'             => esc_html__( 'OpenRouter -> Gemini 2.5 Flash Lite', 'events-optimizer' ),
            'openrouter/google/gemini-2.5-pro'                    => esc_html__( 'OpenRouter -> Gemini 2.5 Pro', 'events-optimizer' ),
            'openrouter/google/gemini-3-pro-preview'              => esc_html__( 'OpenRouter -> Gemini 3.0 Pro (Preview)', 'events-optimizer' ),
            'openrouter/google/gemma-3-4b-it'                     => esc_html__( 'OpenRouter -> Gemma 3 4B-IT', 'events-optimizer' ),
            'openrouter/openai/gpt-4'                             => esc_html__( 'OpenRouter -> GPT-4', 'events-optimizer' ),
            'openrouter/openai/gpt-4-turbo'                       => esc_html__( 'OpenRouter -> GPT-4 Turbo', 'events-optimizer' ),
            'openrouter/openai/gpt-4o'                            => esc_html__( 'OpenRouter -> GPT-4o', 'events-optimizer' ),
            'openrouter/openai/gpt-4o-mini'                       => esc_html__( 'OpenRouter -> GPT-4o Mini', 'events-optimizer' ),
            'openrouter/openai/gpt-4.1'                           => esc_html__( 'OpenRouter -> GPT-4.1', 'events-optimizer' ),
            'openrouter/openai/gpt-4.1-mini'                      => esc_html__( 'OpenRouter -> GPT-4.1 Mini', 'events-optimizer' ),
            'openrouter/openai/gpt-5'                             => esc_html__( 'OpenRouter -> GPT-5', 'events-optimizer' ),
            'openrouter/meta-llama/llama-3-70b-instruct:nitro'    => esc_html__( 'OpenRouter -> Llama 3 70B Instruct (nitro)', 'events-optimizer' ),
            'openrouter/meta-llama/llama-3-8b-instruct'           => esc_html__( 'OpenRouter -> Llama 3 8B Instruct', 'events-optimizer' ),
            'openrouter/meta-llama/llama-3.1-8b-instruct:nitro'   => esc_html__( 'OpenRouter -> Llama 3.1 8B Instruct (nitro)', 'events-optimizer' ),
            'openrouter/meta-llama/llama-4-maverick'              => esc_html__( 'OpenRouter -> Llama 4 Maverick', 'events-optimizer' ),
            'openrouter/mistralai/ministral-3b'                   => esc_html__( 'OpenRouter -> Ministral 3B', 'events-optimizer' ),
            'openrouter/mistralai/ministral-8b'                   => esc_html__( 'OpenRouter -> Ministral 8B', 'events-optimizer' ),
            'openrouter/mistralai/mistral-small-3.2-24b-instruct' => esc_html__( 'OpenRouter -> Mistral Small 3.2 24B', 'events-optimizer' ),
            'openrouter/mistralai/mistral-medium-3.1'             => esc_html__( 'OpenRouter -> Mistral Medium 3.1', 'events-optimizer' ),
            'openrouter/mistralai/mistral-large-2411'             => esc_html__( 'OpenRouter -> Mistral Large 24.11', 'events-optimizer' ),
            'openrouter/mistralai/magistral-small-2506'           => esc_html__( 'OpenRouter -> Magistral Small 2506', 'events-optimizer' ),
            'openrouter/mistralai/magistral-medium-2506'          => esc_html__( 'OpenRouter -> Magistral Small 2506', 'events-optimizer' ),
            'openrouter/qwen/qwen-turbo'                          => esc_html__( 'OpenRouter -> Qwen-Turbo', 'events-optimizer' ),
            'openrouter/qwen/qwen-plus'                           => esc_html__( 'OpenRouter -> Qwen-Plus', 'events-optimizer' ),
            'openrouter/qwen/qwen-max'                            => esc_html__( 'OpenRouter -> Qwen-Max', 'events-optimizer' ),
        );
        foreach ( $openai_model_options as $openai_model_value => $openai_model_decription ) {
            echo '<option value="' . esc_attr( $openai_model_value ) . '" ' . selected( $selected_openai_model, $openai_model_value, false ) . '>' . esc_attr( $openai_model_decription ) . '</option>';
        }
        ?>
								</select>
								<?php 
        /* Translators: All placeholders are for the links to the AI model details */
        printf(
            esc_html__( 'AI Model details: %1$sOpenRouter%2$s, %3$sOpenAI%4$s, %5$sGoogle%6$s, %7$sAnthropic%8$s, %9$sMistral%10$s, %11$sDeepSeek%12$s %13$sor%14$s %15$sGroq%16$s', 'events-optimizer' ),
            '<a href="https://openrouter.ai/models?order=pricing-low-to-high" target="_blank" rel="noopener noreferrer">',
            '</a>',
            '<a href="https://platform.openai.com/docs/models/overview" target="_blank" rel="noopener noreferrer">',
            '</a>',
            '<a href="https://ai.google.dev/gemini-api/docs/models/gemini" target="_blank" rel="noopener noreferrer">',
            '</a>',
            '<a href="https://docs.anthropic.com/en/docs/about-claude/models#model-names" target="_blank" rel="noopener noreferrer">',
            '</a>',
            '<a href="https://docs.mistral.ai/getting-started/models/models_overview/" target="_blank" rel="noopener noreferrer">',
            '</a>',
            '<a href="https://api-docs.deepseek.com/api/list-models" target="_blank" rel="noopener noreferrer">',
            '</a>',
            '',
            '',
            '<a href="https://console.groq.com/docs/models" target="_blank" rel="noopener noreferrer">',
            '</a>'
        );
        ?>							
								</td>
								</tr>

								<tr valign="top">					
									<th scope="row"><?php 
        esc_html_e( 'Output Language', 'events-optimizer' );
        ?></th>
									<td>
									<?php 
        $openai_language = sanitize_text_field( get_option( 'teoai_openai_language' ) );
        $teoai_output_languages = array(
            'Albanian, Albania',
            'Arabic, Arab World',
            'Armenian, Armenia',
            'Awadhi, India',
            'Azerbaijani, Azerbaijan',
            'Bashkir, Russia',
            'Basque, Spain',
            'Belarusian, Belarus',
            'Bengali, Bangladesh',
            'Bhojpuri, India',
            'Bosnian, Bosnia and Herzegovina',
            'Bulgarian, Bulgaria',
            'Cantonese (Yue), China',
            'Catalan, Spain',
            'Chinese (Traditional), Taiwan',
            'Chinese (Traditional), Hong Kong',
            'Chinese (Mandarin), China',
            'Chinese (Simplified), China',
            'Chhattisgarhi, India',
            'Croatian, Croatia',
            'Czech, Czech Republic',
            'Danish, Denmark',
            'Dogri, India',
            'Dutch, Netherlands',
            'English, United Kingdom',
            'English, United States',
            'Estonian, Estonia',
            'Faroese, Faroe Islands',
            'Finnish, Finland',
            'French, France',
            'Galician, Spain',
            'Georgian, Georgia',
            'German, Germany',
            'Greek, Greece',
            'Gujarati, India',
            'Hebrew, Israel',
            'Haryanvi, India',
            'Hindi, India',
            'Hungarian, Hungary',
            'Icelandic, Iceland',
            'Indonesian, Indonesia',
            'Irish, Ireland',
            'Italian, Italy',
            'Japanese, Japan',
            'Javanese, Indonesia',
            'Kannada, India',
            'Kashmiri, India',
            'Kazakh, Kazakhstan',
            'Konkani, India',
            'Korean, South Korea',
            'Kyrgyz, Kyrgyzstan',
            'Latvian, Latvia',
            'Lithuanian, Lithuania',
            'Macedonian, North Macedonia',
            'Maithili, India',
            'Malay, Malaysia',
            'Maltese, Malta',
            'Malayalam, India',
            'Mandarin, China',
            'Mandarin Chinese, China',
            'Marathi, India',
            'Marwari, India',
            'Min Nan, China',
            'Moldovan, Moldova',
            'Mongolian, Mongolia',
            'Montenegrin, Montenegro',
            'Nepali, Nepal',
            'Norwegian, Norway',
            'Oriya, India',
            'Pashto, Afghanistan',
            'Persian (Farsi), Iran',
            'Polish, Poland',
            'Portuguese, Angola',
            'Portuguese, Portugal',
            'Portuguese, Brazil',
            'Punjabi, India',
            'Rajasthani, India',
            'Romanian, Romania',
            'Russian, Russia',
            'Spanish, Spain',
            'Spanish, Mexico',
            'Sanskrit, India',
            'Santali, India',
            'Serbian, Serbia',
            'Sindhi, Pakistan',
            'Sinhala, Sri Lanka',
            'Slovak, Slovakia',
            'Slovenian, Slovenia',
            'Swedish, Sweden',
            'Tagalog, Philippines',
            'Filipino, Philippines',
            'Tamil, India',
            'Telugu, India',
            'Thai, Thailand',
            'Turkish, Turkey',
            'Ukrainian, Ukraine',
            'Urdu, Pakistan',
            'Uzbek, Uzbekistan',
            'Vietnamese, Vietnam',
            'Welsh, Wales',
            'Wu, China'
        );
        ?>
									<select name="openai_language" id="openai_language" <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?>>
										<?php 
        foreach ( $teoai_output_languages as $language ) {
            echo '<option value="' . esc_attr( $language ) . '" ' . selected( $openai_language, $language, false ) . '>' . esc_html( $language ) . '</option>';
        }
        ?>
									</select>
									<?php 
        printf(
            '%s <a href="%s">%s</a>',
            esc_html__( 'Do you miss a language?', 'events-optimizer' ),
            esc_url( admin_url( 'admin.php?page=events_optimizer-contact' ) ),
            esc_html__( 'Contact us!', 'events-optimizer' )
        );
        ?>
									</td>
								</tr>
							

								<tr valign="top">					
								<th scope="row"><?php 
        esc_html_e( 'Writing Tone', 'events-optimizer' );
        ?></th>
								<td>
								<select name="openai_prompt_tone" id="openai_prompt_tone" <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> >  
								<?php 
        $selected_openai_prompt_tone = urldecode( get_option( 'teoai_openai_prompt_tone' ) );
        $prompt_tones = array(
            esc_html__( '- no specific tone -', 'events-optimizer' ),
            esc_html__( 'enthusiastic and energetic', 'events-optimizer' ),
            esc_html__( 'professional and informative', 'events-optimizer' ),
            esc_html__( 'warm and welcoming', 'events-optimizer' ),
            esc_html__( 'inspirational and motivational', 'events-optimizer' ),
            esc_html__( 'mysterious and intriguing', 'events-optimizer' ),
            esc_html__( 'elegant and sophisticated', 'events-optimizer' ),
            esc_html__( 'humorous and lighthearted', 'events-optimizer' ),
            esc_html__( 'educational and enlightening', 'events-optimizer' ),
            esc_html__( 'adventurous and exciting', 'events-optimizer' ),
            esc_html__( 'relaxing and tranquil', 'events-optimizer' )
        );
        foreach ( $prompt_tones as $prompt_tone ) {
            echo '<option value="' . esc_attr( $prompt_tone ) . '" ' . selected( $selected_openai_prompt_tone, $prompt_tone, false ) . '>' . esc_attr( $prompt_tone ) . '</option>';
        }
        ?>
								</select>
								<?php 
        esc_html_e( 'Read more how using the right tone can', 'events-optimizer' );
        ?> 
								<a href="https://www.events-optimizer.com/events-optimizer/settings/set-the-tone-of-ai-generated-descriptions/" target="_blank"  rel="noopener noreferrer">
								<?php 
        esc_html_e( 'impact the audience\'s perception', 'events-optimizer' );
        ?></a>
								</td>
								</tr>
								
								<tr valign="top">					
									<th scope="row"><?php 
        esc_html_e( 'Maximum Length', 'events-optimizer' );
        ?></th>
									<td><input type="text" name="openai_max_tokens" id="openai_max_tokens" size="5"  value="<?php 
        echo esc_attr( get_option( 'teoai_openai_max_tokens' ) );
        ?>"  <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									<?php 
        esc_html_e( 'Limits the maximum length of the generated text. 2048 tokens are about 900 words. Calculate them', 'events-optimizer' );
        ?> 
									<a href="https://platform.openai.com/tokenizer" target="_blank"  rel="noopener noreferrer">
									<?php 
        esc_html_e( 'here.', 'events-optimizer' );
        ?></a>
									</td>
								</tr>					
								<tr valign="top">
								<th scope="row"><?php 
        esc_html_e( 'Add Headings', 'events-optimizer' );
        ?></th>
								<td>
									<input type="checkbox" name="openai_prompt_headings" id="openai_prompt_headings" value="true" <?php 
        checked( get_option( 'teoai_openai_prompt_headings' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									<?php 
        esc_html_e( 'Automatically structure the content with headings for better readability. Requires Output as HTML to be enabled.', 'events-optimizer' );
        ?>
								</td>
								</tr>
								<tr valign="top">
								<th scope="row"><?php 
        esc_html_e( 'Add FAQ', 'events-optimizer' );
        ?></th>
								<td>
									<input type="checkbox" name="openai_prompt_faq" id="openai_prompt_faq" value="true" <?php 
        checked( get_option( 'teoai_openai_prompt_faq' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									<?php 
        esc_html_e( 'Adds a FAQ section. Can improve user experience and search engine visibility. Requires Output as HTML to be enabled.', 'events-optimizer' );
        ?>
								</td>
								</tr>								
								<tr valign="top">
								<th scope="row"><?php 
        esc_html_e( 'Output as HTML', 'events-optimizer' );
        ?></th>
								<td>
									<input type="checkbox" name="openai_prompt_html" id="openai_prompt_html" value="true" <?php 
        checked( get_option( 'teoai_openai_prompt_html' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									<?php 
        esc_html_e( 'Outputs the generated content as HTML. Some AI models may generate Markdown instead of HTML.', 'events-optimizer' );
        ?>
								</td>								
								</tr>  								
								<tr valign="top">
								<th scope="row"><?php 
        esc_html_e( 'Add Emojis', 'events-optimizer' );
        ?></th>
								<td>
									<input type="checkbox" name="openai_prompt_emojis" id="openai_prompt_emojis" value="true" <?php 
        checked( get_option( 'teoai_openai_prompt_emojis' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									<?php 
        esc_html_e( 'Adds appropriate emojis to the text to make it more engaging.', 'events-optimizer' );
        ?>
								</td>
								</tr>  								

								<tr valign="top">
								<th scope="row"><?php 
        esc_html_e( 'Use website content for better descriptions', 'events-optimizer' );
        ?></th>
								<td>
									<input type="checkbox" name="openai_prompt_use_website" id="openai_prompt_use_website" value="true" <?php 
        checked( get_option( 'teoai_openai_prompt_use_website' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									<?php 
        esc_html_e( 'Uses content from the event, venue, or organizer website to generate more accurate and relevant descriptions. Requires the DataForSEO API.', 'events-optimizer' );
        ?>
								</td>
								</tr>									                                                  
								<tr valign="top">
								<th scope="row"><?php 
        esc_html_e( 'Replace existing Content', 'events-optimizer' );
        ?></th>
								<td>
									<input type="checkbox" name="openai_replace_content" id="openai_replace_content" value="true" <?php 
        checked( get_option( 'teoai_openai_replace_content' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									<?php 
        esc_html_e( 'Replace existing content or add new content to it', 'events-optimizer' );
        ?>
								</td>
								</tr>
								<tr valign="top">
								<th scope="row"><?php 
        esc_html_e( 'Hide Generate Description Buttons', 'events-optimizer' );
        ?></th>
								<td>
									<input type="checkbox" name="openai_hide_generate_description_buttons" id="openai_hide_generate_description_buttons" value="true" <?php 
        checked( get_option( 'teoai_openai_hide_generate_description_buttons' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									<?php 
        esc_html_e( 'Hide buttons in the single event, venue and organizer form', 'events-optimizer' );
        ?>
								</td>
								</tr>							
							</table>									
							<br><br>
							<input type='submit' name='action' class='button-primary teoai-save-settings' value='<?php 
        esc_html_e( 'Save changes', 'events-optimizer' );
        ?>' />
							<p>
								<div class="teoai-status" style="display:none;"></div>
								<div class="teoai-loading" style="display:none;"><?php 
        esc_html_e( 'SAVING', 'events-optimizer' );
        ?></div>
							</p>
						</div>
					</form>
				</div>
			</div>

			<div class="nav-tab-content<?php 
        echo ( $active_tab === 'tab-google-images' ? ' nav-tab-content-active' : '' );
        ?>" id="nav-tab-content-tab-google-images">
				<div>
					<form action='' method='POST' id='settings_form_google_images'>
						<div>
							<br><h3><?php 
        esc_html_e( 'Google Images', 'events-optimizer' );
        ?></h3>
                                <div class="teoai-info-box">
								<?php 
        esc_html_e( 'This feature allows you to automatically enrich events, venues, and organizers with relevant images sourced from Google.', 'events-optimizer' );
        ?></li>
								<ul>
								<li><?php 
        esc_html_e( 'Images are retrieved using the DataForSEO Google Images API.', 'events-optimizer' );
        ?></li>
								<li><?php 
        esc_html_e( 'Please use this feature responsibly and ensure compliance with copyright and licensing laws.', 'events-optimizer' );
        ?></li>
								</ul>
							</div>
																
							<table class="form-table">
								<tr valign="top">					
									<th scope="row"><?php 
        esc_html_e( 'Maximum images to search', 'events-optimizer' );
        ?></th>
									<td>
										<input type="text" name="max_images" id="max_images" size="2"  value="<?php 
        echo esc_attr( get_option( 'teoai_max_images' ) );
        ?>"  <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									</td>
								</tr>	
							</table>								
							<br><br>
							<input type='submit' name='action' class='button-primary teoai-save-settings' value='<?php 
        esc_html_e( 'Save changes', 'events-optimizer' );
        ?>' />
							<p>
								<div class="teoai-status" style="display:none;"></div>
								<div class="teoai-loading" style="display:none;"><?php 
        esc_html_e( 'SAVING', 'events-optimizer' );
        ?></div>
							</p>
						</div>
					</form>
				</div>
			</div>

			<div class="nav-tab-content<?php 
        echo ( $active_tab === 'tab-google-events' ? ' nav-tab-content-active' : '' );
        ?>" id="nav-tab-content-tab-google-events">
				<div>
					<form action='' method='POST' id='settings_form_google_events'>
						<div>
							<br><h3><?php 
        esc_html_e( 'Google Events', 'events-optimizer' );
        ?><span class='beta_version'>BETA</span></h3>
                                <div class="teoai-info-box">
								<?php 
        esc_html_e( 'This feature helps you to discover and import public events from Google to keep your event database up to date.', 'events-optimizer' );
        ?>
								<ul>
								<li><?php 
        esc_html_e( 'To automatically add Google Events the DataForSEO API is used.', 'events-optimizer' );
        ?></li>
								<li><?php 
        esc_html_e( 'Play around with the search results in', 'events-optimizer' );
        ?> 
								<a href="https://www.google.com/search?q=event&ibp=htl;events&rciv=evn#fpstate=tldetail" target="_blank" rel="noopener noreferrer">
								<?php 
        esc_html_e( 'Google Events', 'events-optimizer' );
        ?></a>.</li>
								<li><?php 
        esc_html_e( 'The choices below are used as the defaults when manually or bulk importing events.', 'events-optimizer' );
        ?></li>
								</ul>
							</div>
																
								<table class="form-table">						
									<tr valign="top">							
										<th scope="row"><?php 
        esc_html_e( 'Date range', 'events-optimizer' );
        ?></th>
										<td>
											<select name="dataforseo_date_range" id="dataforseo_date_range" <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?>>
											<?php 
        $date_range_options = array(
            'all'        => esc_html__( 'All upcoming events', 'events-optimizer' ),
            'today'      => esc_html__( 'Today', 'events-optimizer' ),
            'tomorrow'   => esc_html__( 'Tomorrow', 'events-optimizer' ),
            'weekend'    => esc_html__( 'This weekend', 'events-optimizer' ),
            'week'       => esc_html__( 'This week', 'events-optimizer' ),
            'next_week'  => esc_html__( 'Next week', 'events-optimizer' ),
            'month'      => esc_html__( 'This month', 'events-optimizer' ),
            'next_month' => esc_html__( 'Next month', 'events-optimizer' ),
        );
        foreach ( $date_range_options as $dr_value => $dr_decription ) {
            echo '<option value="' . esc_attr( $dr_value ) . '"' . selected( $dr_value, get_option( 'teoai_dataforseo_date_range' ), false ) . '>' . esc_attr( $dr_decription ) . '</option>';
        }
        ?>
											</select>  
										</td>
									</tr>
									<tr valign="top">							
										<th scope="row"><?php 
        esc_html_e( 'Language', 'events-optimizer' );
        ?></th>
										<td>
											<?php 
        $dataforseo_login = get_option( 'teoai_dataforseo_api_login', '' );
        $dataforseo_password = get_option( 'teoai_dataforseo_api_password', '' );
        $credentials_are_present = !empty( $dataforseo_login ) && !empty( $dataforseo_password );
        $selected_lang = get_option( 'teoai_dataforseo_language_code' );
        $languages = teoai_read_dataforseo_languages_cache();
        ?>
											<div class="teoai-language-picker">
												<select name="dataforseo_language_code" id="dataforseo_language_code" <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?>>
													<?php 
        if ( !is_wp_error( $languages ) && is_array( $languages ) ) {
            foreach ( $languages as $lang_item ) {
                if ( !isset( $lang_item['language_code'], $lang_item['language_name'] ) ) {
                    continue;
                }
                echo '<option value="' . esc_attr( $lang_item['language_code'] ) . '" ' . selected( $selected_lang, $lang_item['language_code'], false ) . '>' . esc_html( $lang_item['language_name'] ) . '</option>';
            }
        }
        ?>
												</select>
												<button type="button" class="button" id="dataforseo_update_languages" data-requires-creds="false" <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?>>
													<?php 
        esc_html_e( 'Update list', 'events-optimizer' );
        ?>
												</button>
												<span class="teoai-inline-status">
													<span id="dataforseo_languages_loading" class="teoai-loading" style="display:none;"></span>
													<span id="dataforseo_languages_message" class="teoai-status-message" style="display:none;"></span>
												</span>
											</div>
												<?php 
        $lang_meta = ( function_exists( 'teoai_get_dataforseo_languages_meta' ) ? teoai_get_dataforseo_languages_meta() : array() );
        $lang_last_label = '';
        if ( isset( $lang_meta['last_updated'] ) && $lang_meta['last_updated'] ) {
            /* translators: %1$s: datetime of last update */
            $lang_last_label = sprintf( __( 'Last updated: %1$s', 'events-optimizer' ), date_i18n( 'd.m.Y, H:i', $lang_meta['last_updated'] ) );
        }
        ?>
											<div id="dataforseo_languages_last_updated" class="description teoai-status-line" <?php 
        echo ( empty( $lang_last_label ) ? 'style="display:none;"' : '' );
        ?>>
												<?php 
        echo esc_html( $lang_last_label );
        ?>
											</div>
										</td>
									</tr>							
									<tr valign="top">							
										<th scope="row"><?php 
        esc_html_e( 'Location', 'events-optimizer' );
        ?></th>
										<td>
											<?php 
        $current_location_code = get_option( 'teoai_dataforseo_location_code' );
        $current_location_label = get_option( 'teoai_dataforseo_location_label', '' );
        if ( !$current_location_label && function_exists( 'teoai_find_dataforseo_location_label' ) ) {
            $current_location_label = teoai_find_dataforseo_location_label( $current_location_code );
        }
        $locations_meta = teoai_get_dataforseo_locations_meta();
        $dataforseo_login = get_option( 'teoai_dataforseo_api_login', '' );
        $dataforseo_password = get_option( 'teoai_dataforseo_api_password', '' );
        $credentials_are_present = !empty( $dataforseo_login ) && !empty( $dataforseo_password );
        ?>
											<div class="teoai-location-picker">
												<select
													id="dataforseo_location_select"
													name="dataforseo_location_code"
													class="teoai-location-select"
													data-current="<?php 
        echo esc_attr( $current_location_code );
        ?>"
													data-current-label="<?php 
        echo esc_attr( $current_location_label );
        ?>"
													<?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?>
												>
													<?php 
        if ( $current_location_code && $current_location_label ) {
            ?>
														<option value="<?php 
            echo esc_attr( $current_location_code );
            ?>" selected><?php 
            echo esc_html( $current_location_label );
            ?></option>
													<?php 
        }
        ?>
												</select>
												<input type="hidden" name="dataforseo_location_label" id="dataforseo_location_label" value="<?php 
        echo esc_attr( $current_location_label );
        ?>" />
												<button type="button" class="button" id="dataforseo_update_locations" data-locked="<?php 
        echo ( teoai_fs()->can_use_premium_code__premium_only() ? 'false' : 'true' );
        ?>" data-requires-creds="false" <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?>>
													<?php 
        esc_html_e( 'Update list', 'events-optimizer' );
        ?>
												</button>
												<span class="teoai-inline-status">
													<span id="dataforseo_locations_loading" class="teoai-loading" style="display:none;"></span>
													<span id="dataforseo_locations_message" class="teoai-status-message" style="display:none;"></span>
												</span>
											</div>
											<?php 
        $location_last_label = '';
        if ( $locations_meta['last_updated'] ) {
            /* translators: %1$s: datetime of last update */
            $location_last_label = sprintf( __( 'Last updated: %1$s', 'events-optimizer' ), date_i18n( 'd.m.Y, H:i', $locations_meta['last_updated'] ) );
        }
        ?>
											<div id="dataforseo_locations_status" class="description teoai-status-line" <?php 
        echo ( empty( $location_last_label ) ? 'style="display:none;"' : '' );
        ?>>
												<?php 
        echo esc_html( $location_last_label );
        ?>
											</div>
										</td>
									</tr>
									<tr valign="top">
										<th scope="row"><?php 
        esc_html_e( 'Prefill currency symbol', 'events-optimizer' );
        ?></th>
										<td>
											<input type="checkbox" name="prefill_currency_symbol" id="prefill_currency_symbol" value="true" <?php 
        checked( get_option( 'teoai_prefill_currency_symbol' ), 'true' );
        ?> <?php 
        disabled( teoai_fs()->can_use_premium_code__premium_only(), false );
        ?> />
											<?php 
        echo esc_html_e( 'Pre-fill the currency symbol field with the standard currency from the', 'events-optimizer' ) . ' ';
        // Path to Events Calendar settings changed from V5.9 to V6.0
        $plugin_arr = get_plugin_data( WP_PLUGIN_DIR . '/the-events-calendar/the-events-calendar.php', false, false );
        if ( $plugin_arr['Version'] < 6 ) {
            echo '<a href="/wp-admin/edit.php?page=tribe-common&tab=display&post_type=tribe_events" target="_blank" rel="noopener noreferrer">';
        } else {
            echo '<a href="/wp-admin/edit.php?page=tec-events-settings&tab=display-currency-tab&post_type=tribe_events" target="_blank" rel="noopener noreferrer">';
        }
        echo esc_html__( 'settings of the Events Calendar', 'events-optimizer' ) . '</a>';
        ?>
										</td>
									</tr>								
								</table>
								<br><h3><?php 
        esc_html_e( 'Imported Google Events', 'events-optimizer' );
        ?></h3>	
								<?php 
        esc_html_e( 'Events already imported from Google Events are shown now in the', 'events-optimizer' );
        ?> <a href="<?php 
        echo esc_url( admin_url( 'edit.php?post_type=tribe_events' ) );
        ?>"><?php 
        esc_html_e( 'Events Calendar list', 'events-optimizer' );
        ?></a>.
								<table class="form-table">
									<tr valign="top">
										<th scope="row"><?php 
        esc_html_e( 'Show events imported already', 'events-optimizer' );
        ?></th>
										<td>
											<input type="checkbox" name="show_added_objects" id="show_added_objects" value="true" <?php 
        checked( filter_var( get_option( 'teoai_show_added_objects' ), FILTER_VALIDATE_BOOLEAN ), true );
        ?> <?php 
        disabled( teoai_fs()->can_use_premium_code__premium_only(), false );
        ?> />
										</td>
									</tr>										
									<tr valign="top">
										<th scope="row"><?php 
        esc_html_e( 'Cleanup completed import runs after', 'events-optimizer' );
        ?></th>
										<td>
											<?php 
        $cleanup_completed = intval( get_option( 'teoai_cleanup_completed_runs_after_days', 30 ) );
        $cleanup_choices = array(
            1,
            14,
            30,
            60
        );
        ?>
											<select name="cleanup_completed_runs_after_days" id="cleanup_completed_runs_after_days" <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?>>
												<?php 
        foreach ( $cleanup_choices as $choice ) {
            ?>
													<option value="<?php 
            echo esc_attr( $choice );
            ?>" <?php 
            selected( $cleanup_completed, $choice );
            ?>><?php 
            echo esc_html( $choice . ' ' . __( 'days', 'events-optimizer' ) );
            ?></option>
												<?php 
        }
        ?>
											</select>
											<?php 
        esc_html_e( 'Automatically remove completed import runs.', 'events-optimizer' );
        ?>
										</td>
									</tr>
									<tr valign="top">
										<th scope="row"><?php 
        esc_html_e( 'Cleanup failed / warning import runs after', 'events-optimizer' );
        ?></th>
										<td>
											<?php 
        $cleanup_problem = intval( get_option( 'teoai_cleanup_problem_runs_after_days', 60 ) );
        ?>
											<select name="cleanup_problem_runs_after_days" id="cleanup_problem_runs_after_days" <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?>>
												<?php 
        foreach ( $cleanup_choices as $choice ) {
            ?>
													<option value="<?php 
            echo esc_attr( $choice );
            ?>" <?php 
            selected( $cleanup_problem, $choice );
            ?>><?php 
            echo esc_html( $choice . ' ' . __( 'days', 'events-optimizer' ) );
            ?></option>
												<?php 
        }
        ?>
											</select>
											<?php 
        esc_html_e( 'Automatically remove failed, aborted, or warning import runs.', 'events-optimizer' );
        ?></p>
										</td>
									</tr>
								</table>

								<br><br>
								<input type='submit' name='action' class='button-primary teoai-save-settings' value='<?php 
        esc_html_e( 'Save changes', 'events-optimizer' );
        ?>' />
								<p>
								<div class="teoai-status" style="display:none;"></div>
								<div class="teoai-loading" style="display:none;"><?php 
        esc_html_e( 'SAVING', 'events-optimizer' );
        ?></div>
							</p>
						</div>
					</form>
				</div>
			</div>

			<div class="nav-tab-content<?php 
        echo ( $active_tab === 'tab-security' ? ' nav-tab-content-active' : '' );
        ?>" id="nav-tab-content-tab-security">
				<div>
					<form action='' method='POST' id='settings_form_security'>
						<div>
							<br><h3><?php 
        esc_html_e( 'Permissions', 'events-optimizer' );
        ?></h3>

							<div id="teoai-info-box"">
									<?php 
        echo esc_html__( 'By default, only administrators can access Events Optimizer.', 'events-optimizer' ) . '<br>';
        echo esc_html__( 'You can allow access for other user roles. ', 'events-optimizer' );
        echo wp_kses_post( sprintf( 
            /* translators: %s: link to User Role Editor plugin */
            __( 'Manage additional roles with a plugin like %s.', 'events-optimizer' ),
            '<a href="' . esc_url( 'https://wordpress.org/plugins/user-role-editor/' ) . '" target="_blank" rel="noopener noreferrer">' . esc_html__( 'User Role Editor', 'events-optimizer' ) . '</a>'
         ) );
        ?>
									<br>
							</div>

							<table class="form-table">			
								<tr valign="top">							
									<th scope="row"><?php 
        esc_html_e( 'Grant access to roles', 'events-optimizer' );
        ?></th>
									<td>
										<?php 
        $all_roles = wp_roles()->roles;
        // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- core filter name.
        $editable_roles = apply_filters( 'editable_roles', $all_roles );
        $stored_roles = get_option( 'teoai_allowed_role', array() );
        $selected_roles = array();
        if ( is_array( $stored_roles ) ) {
            $selected_roles = array_map( 'sanitize_key', $stored_roles );
        } elseif ( !empty( $stored_roles ) ) {
            $selected_roles = array(sanitize_key( $stored_roles ));
        }
        foreach ( $editable_roles as $role => $details ) {
            $name = translate_user_role( $details['name'] );
            if ( $role === 'administrator' ) {
                $name = esc_html__( 'Only the administrator', 'events-optimizer' );
            }
            $is_checked = in_array( $role, $selected_roles, true );
            ?>
													<label>
														<?php 
            if ( 'administrator' === $role ) {
                ?>
															<input type="hidden" name="allowed_role[]" value="<?php 
                echo esc_attr( $role );
                ?>" />
															<input type="checkbox" value="<?php 
                echo esc_attr( $role );
                ?>" class="teoai-allowed-role" checked disabled />
														<?php 
            } else {
                ?>
															<input type="checkbox" name="allowed_role[]" value="<?php 
                echo esc_attr( $role );
                ?>" class="teoai-allowed-role" <?php 
                checked( $is_checked );
                ?> <?php 
                disabled( !teoai_fs()->can_use_premium_code__premium_only() );
                ?> />
														<?php 
            }
            ?>
														<?php 
            echo esc_html( $name );
            ?>
													</label><br>
												<?php 
        }
        ?>
									</td>
								</tr>
							</table>

							<br><h3><?php 
        esc_html_e( 'Security', 'events-optimizer' );
        ?></h3>				
                                <div class="teoai-info-box">
								<?php 
        echo esc_html__( 'Protect your users from unsafe external links.', 'events-optimizer' ) . '<br>';
        echo esc_html__( 'Events Optimizer can automatically check event and venue websites for potential risks such as malware, phishing, or social engineering.', 'events-optimizer' ) . '<br>';
        echo '<ul>';
        echo '<li> ' . esc_html__( 'To use it activate the free Google SAFE BROWSING API for the relevant project in the', 'events-optimizer' ) . ' <a href="https://console.cloud.google.com/marketplace/product/google/safebrowsing.googleapis.com" target="_blank"  rel="noopener noreferrer">' . esc_html__( 'Google Cloud Console', 'events-optimizer' ) . '</a>.</li>';
        echo '<li> ' . esc_html__( 'Follow the', 'events-optimizer' ) . ' <a href="https://www.events-optimizer.com/events-optimizer/settings/google-cloud-console-setup/" target="_blank" rel="noopener noreferrer">' . esc_html__( 'tutorial', 'events-optimizer' ) . '</a> ' . esc_html__( 'to set it up.', 'events-optimizer' );
        echo ' ' . esc_html__( 'Learn more about', 'events-optimizer' ) . ' <a href="https://developers.google.com/safe-browsing" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Google Safe Browsing', 'events-optimizer' ) . '</a> ' . esc_html__( 'or', 'events-optimizer' ) . ' <a href="https://transparencyreport.google.com/safe-browsing/search?url=https://testsafebrowsing.appspot.com/s/phishing.html" target="_blank" rel="noopener noreferrer"> ' . esc_html__( 'test it here', 'events-optimizer' ) . '</a>.</li>';
        echo '</ul>';
        ?>
							</div>
							<table class="form-table">	
									<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Check URLs for potential risks', 'events-optimizer' );
        ?></th>
									<td>
										<input type="checkbox" name="google_safe_browsing" id="google_safe_browsing" value="true" <?php 
        checked( get_option( 'teoai_google_safe_browsing' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									</td>
									</tr>
									<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Check URLs on missing https/ http', 'events-optimizer' );
        ?></th>
									<td>
										<input type="checkbox" name="validate_url_https" id="validate_url_https" value="true" <?php 
        checked( get_option( 'teoai_validate_url_https' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									</td>
									</tr>	
									<tr valign="top">
									<th scope="row"><?php 
        esc_html_e( 'Check if URLs are redirected or permanently moved', 'events-optimizer' );
        ?></th>
									<td>
										<input type="checkbox" name="validate_url_redirected_moved" id="validate_url_redirected_moved" value="true" <?php 
        checked( get_option( 'teoai_validate_url_redirected_moved' ), 'true' );
        ?> <?php 
        disabled( !teoai_fs()->can_use_premium_code__premium_only() );
        ?> />
									</td>
									</tr>														
							</table>

							<br><br>
							<input type='submit' name='action' class='button-primary teoai-save-settings' value='<?php 
        esc_html_e( 'Save changes', 'events-optimizer' );
        ?>' />
							<p>
								<div class="teoai-status" style="display:none;"></div>
								<div class="teoai-loading" style="display:none;"><?php 
        esc_html_e( 'SAVING', 'events-optimizer' );
        ?></div>
							</p>
						</div>
					</form>
				</div>
			</div>

			<script type='text/javascript'>
				jQuery(document).ready(function(){
					var $htmlCheckbox = jQuery('#openai_prompt_html');
					var $headingCheckbox = jQuery('#openai_prompt_headings');
					var $faqCheckbox = jQuery('#openai_prompt_faq');

					var ensureHtmlChecked = function() {
						if ( ($headingCheckbox.length && $headingCheckbox.is(':checked')) || ($faqCheckbox.length && $faqCheckbox.is(':checked')) ) {
							$htmlCheckbox.prop('checked', true);
						}
					};

					$headingCheckbox.on('change', ensureHtmlChecked);
					$faqCheckbox.on('change', ensureHtmlChecked);
					ensureHtmlChecked();

					jQuery(document).on('click', '.teoai-remove-object', function(event) {
						event.preventDefault();
						var $el = jQuery(this);
						var id = $el.data('object-id');
						var $row = $el.closest("[id^='object_']");

						if ( typeof window.remove_object === 'function' && typeof id !== 'undefined' ) {
							window.remove_object( id, $row );
						}
					});

					// DataForSEO locations search & update
					var $locationSelect = jQuery('#dataforseo_location_select');
					var $locationUpdated = jQuery('#dataforseo_locations_status');
					var $locationMessage = jQuery('#dataforseo_locations_message');
					var $locationLabelInput = jQuery('#dataforseo_location_label');
					var $updateLocationsButton = jQuery('#dataforseo_update_locations');
					var locationButtonLocked = $updateLocationsButton.data('locked') === true || $updateLocationsButton.data('locked') === 'true';
					$locationSelect.on('change', function() {
						var val = jQuery(this).val();
						jQuery(this).data('current', val).attr('data-current', val);
						syncLocationLabel();
					});

					var $updateLanguagesButton = jQuery('#dataforseo_update_languages');
					var $languageStatus = jQuery('#dataforseo_languages_message');
					var $languageUpdated = jQuery('#dataforseo_languages_last_updated');
					var $languageLoading = jQuery('#dataforseo_languages_loading');
					var $locationLoading = jQuery('#dataforseo_locations_loading');
					var $placesLangSelect = jQuery('#google_places_language');
					var $placesLangUpdate = jQuery('#google_places_update_languages');
					var $placesLangLoading = jQuery('#google_places_languages_loading');
					var $placesLangMessage = jQuery('#google_places_languages_message');
					var $placesLangUpdated = jQuery('#google_places_languages_last_updated');
					var toggleUpdateLanguagesButton = function() {
						var requiresCreds = $updateLanguagesButton.data('requires-creds') === true || $updateLanguagesButton.data('requires-creds') === 'true';
						if ( requiresCreds ) {
							var hasCreds = jQuery('#dataforseo_api_login').val() && jQuery('#dataforseo_api_password').val();
							$updateLanguagesButton.prop('disabled', ! hasCreds);
						}
					};
					var toggleUpdatePlacesButton = function() {
						if ( ! $placesLangUpdate.length ) {
							return;
						}
						var requiresKey = $placesLangUpdate.data('requires-key') === true || $placesLangUpdate.data('requires-key') === 'true';
						if ( requiresKey ) {
							var hasKey = jQuery('#google_places_api_key').val();
							$placesLangUpdate.prop('disabled', ! hasKey);
						}
					};
					var updateLanguageStatus = function(message, isError) {
						if ( ! $languageStatus.length ) {
							return;
						}
						$languageStatus.text(message || '');
						$languageStatus.toggleClass('field-status-error', !!isError);
						$languageStatus.toggle(!!message);
					};
					var formatTs = function(ts) {
						if ( ! ts ) {
							return '';
						}
						var d = new Date( ts * 1000 );
						var pad = function(num) {
							return num < 10 ? '0' + num : '' + num;
						};
						return pad(d.getDate()) + '.' + pad(d.getMonth() + 1) + '.' + d.getFullYear() + ', ' + pad(d.getHours()) + ':' + pad(d.getMinutes());
					};
					var updateLanguageLastUpdated = function(timestamp) {
						if ( ! $languageUpdated.length ) {
							return;
						}
						var label = formatTs(timestamp);
						if ( label ) {
							$languageUpdated.text('<?php 
        echo esc_js( __( 'Last updated: ', 'events-optimizer' ) );
        ?>' + label).show();
						} else {
							$languageUpdated.hide().text('');
						}
					};
					var repopulateLanguages = function() {
						var $languageSelect = jQuery('#dataforseo_language_code');
						if ( ! $languageSelect.length ) {
							return;
						}
						var current = $languageSelect.val();
						jQuery.ajax({
							type: 'GET',
							url: '<?php 
        echo esc_url( admin_url( 'admin-ajax.php' ) );
        ?>',
							data: {
								action: 'teoai_get_dataforseo_languages',
								_ajax_nonce: '<?php 
        echo esc_attr( $nonce );
        ?>'
							},
							success: function(response) {
								if ( response && response.success && response.data && response.data.items ) {
									$languageSelect.empty();
									response.data.items.forEach(function(item) {
										if ( ! item.language_code || ! item.language_name ) {
											return;
										}
										var $opt = jQuery('<option></option>').val(item.language_code).text(item.language_name);
										if ( current && String(current) === String(item.language_code) ) {
											$opt.prop('selected', true);
										}
										$languageSelect.append($opt);
									});
									updateLanguageStatus('', false);
								} else if ( response && response.data && response.data.message ) {
									updateLanguageStatus(response.data.message, true);
								}
							},
							error: function() {
								updateLanguageStatus('<?php 
        echo esc_js( __( 'Could not load languages. Please refresh and try again.', 'events-optimizer' ) );
        ?>', true);
							}
						});
					};

					var updateLocationStatus = function(message, isError) {
						if ( ! $locationMessage.length ) {
							return;
						}
						$locationMessage.text(message || '');
						$locationMessage.toggleClass('field-status-error', !!isError);
						$locationMessage.toggle(!!message);
						syncLocationLabel();
					};
					var updateLocationLastUpdated = function(timestamp) {
						if ( ! $locationUpdated.length ) {
							return;
						}
						var label = formatTs(timestamp);
						if ( label ) {
							$locationUpdated.text('<?php 
        echo esc_js( __( 'Last updated: ', 'events-optimizer' ) );
        ?>' + label).show();
						} else {
							$locationUpdated.hide().text('');
						}
					};

					var syncLocationLabel = function() {
						if ( ! $locationLabelInput.length ) {
							return;
						}
						var label = '';
						if ( typeof $locationSelect.select2 === 'function' && $locationSelect.data('select2') ) {
							var data = $locationSelect.select2('data');
							if ( data && data.length ) {
								label = data[0].text || '';
							}
						}
						if ( ! label ) {
							label = $locationSelect.find('option:selected').text();
						}
						$locationLabelInput.val( label );
					};

					var updatePlacesLangStatus = function(message, isError) {
						if ( ! $placesLangMessage.length ) {
							return;
						}
						$placesLangMessage.text(message || '');
						$placesLangMessage.toggleClass('field-status-error', !!isError);
						$placesLangMessage.toggle(!!message);
					};
					var updatePlacesLangLastUpdated = function(timestamp) {
						if ( ! $placesLangUpdated.length ) {
							return;
						}
						var label = formatTs(timestamp);
						if ( label ) {
							$placesLangUpdated.text('<?php 
        echo esc_js( __( 'Last updated: ', 'events-optimizer' ) );
        ?>' + label).show();
						} else {
							$placesLangUpdated.hide().text('');
						}
					};

            var repopulateLocations = function(searchTerm) {
                // Fallback loader when select2 is not available.
                if ( ! $locationSelect.length || typeof $locationSelect.select2 === 'function' ) {
                    return;
                }
                var current = $locationSelect.data('current') || $locationSelect.val();
                var currentLabel = $locationSelect.data('current-label') || '';
                jQuery.ajax({
                    type: 'GET',
                    url: '<?php 
        echo esc_url( admin_url( 'admin-ajax.php' ) );
        ?>',
                    data: {
                        action: 'teoai_search_dataforseo_locations',
                        term: searchTerm || '',
                        limit: 200,
                        _ajax_nonce: '<?php 
        echo esc_attr( $nonce );
        ?>'
                    },
                    success: function(response) {
                        if ( response && response.success && response.data && response.data.items ) {
                            $locationSelect.empty();
                            var hasCurrent = false;
                            response.data.items.forEach(function(item) {
                                var $opt = jQuery('<option></option>').val(item.code).text(item.label || item.code);
                                if ( current && String(current) === String(item.code) ) {
                                    $opt.prop('selected', true);
                                    hasCurrent = true;
                                }
                                $locationSelect.append($opt);
                            });
                            if ( current && ! hasCurrent && currentLabel ) {
                                var $currentOpt = jQuery('<option></option>').val(current).text(currentLabel).prop('selected', true);
                                $locationSelect.prepend($currentOpt);
                            }
                            var selectedVal = $locationSelect.val();
                            $locationSelect.data('current', selectedVal).attr('data-current', selectedVal);
                            $locationSelect.trigger('change');
                            syncLocationLabel();
                            updateLocationStatus('', false);
                        } else if ( response && response.data && response.data.message ) {
                            updateLocationStatus(response.data.message, true);
                        }
                    },
                    error: function() {
                        updateLocationStatus('<?php 
        echo esc_js( __( 'No cached locations available. Please update the list first.', 'events-optimizer' ) );
        ?>', true);
                    }
                });
            };

					var repopulatePlacesLanguages = function() {
						if ( ! $placesLangSelect.length ) {
							return;
						}
						var current = $placesLangSelect.data('current') || $placesLangSelect.val();
						jQuery.ajax({
							type: 'GET',
							url: '<?php 
        echo esc_url( admin_url( 'admin-ajax.php' ) );
        ?>',
							data: {
								action: 'teoai_get_google_translation_languages',
								_ajax_nonce: '<?php 
        echo esc_attr( $nonce );
        ?>'
							},
							success: function(response) {
								if ( response && response.success && response.data && response.data.items ) {
									$placesLangSelect.empty();
									response.data.items.forEach(function(item) {
										if ( ! item.code ) {
											return;
										}
										var $opt = jQuery('<option></option>').val(item.code).text(item.label || item.code);
										if ( current && String(current) === String(item.code) ) {
											$opt.prop('selected', true);
										}
										$placesLangSelect.append($opt);
									});
									var selectedVal = $placesLangSelect.val();
									$placesLangSelect.data('current', selectedVal).attr('data-current', selectedVal);
									updatePlacesLangStatus('', false);
								} else if ( response && response.data && response.data.message ) {
									updatePlacesLangStatus(response.data.message, true);
								}
							},
							error: function() {
								updatePlacesLangStatus('<?php 
        echo esc_js( __( 'Could not load languages. Please refresh and try again.', 'events-optimizer' ) );
        ?>', true);
							}
						});
					};

					var toggleUpdateLocationsButton = function() {
						if ( locationButtonLocked ) {
							return;
						}
						$updateLocationsButton.prop('disabled', false);
					};

				toggleUpdateLocationsButton();
				toggleUpdateLanguagesButton();
				toggleUpdatePlacesButton();

					jQuery('#dataforseo_api_login, #dataforseo_api_password').on('input', function() {
						toggleUpdateLocationsButton();
						toggleUpdateLanguagesButton();
					});
					jQuery('#google_places_api_key').on('input', function() {
						toggleUpdatePlacesButton();
					});

					var initLocationSelect2 = function() {
						if ( ! $locationSelect.length ) {
							return;
						}
						var placeholder = '<?php 
        echo esc_js( __( 'Type to search locations…', 'events-optimizer' ) );
        ?>';
						if ( typeof $locationSelect.select2 === 'function' ) {
							$locationSelect.select2({
								placeholder: placeholder,
								allowClear: true,
								width: 'resolve',
								ajax: {
									url: '<?php 
        echo esc_url( admin_url( 'admin-ajax.php' ) );
        ?>',
									dataType: 'json',
									delay: 250,
									cache: true,
									data: function(params) {
										return {
											action: 'teoai_search_dataforseo_locations',
											term: params.term || '',
											limit: 50,
											_ajax_nonce: '<?php 
        echo esc_attr( $nonce );
        ?>'
										};
									},
									processResults: function(response) {
										if ( response && response.success && response.data && response.data.items ) {
											return {
												results: response.data.items.map(function(item) {
													return { id: item.code, text: item.label || item.code };
												})
											};
										}
										if ( response && response.data && response.data.message ) {
											updateLocationStatus(response.data.message, true);
										}
										return { results: [] };
									}
								}
							});

							var curVal = $locationSelect.data('current') || $locationSelect.val();
							var curLabel = $locationSelect.data('current-label');
							if ( curVal && curLabel && ! $locationSelect.find('option[value=\"' + curVal + '\"]').length ) {
								var opt = new Option(curLabel, curVal, true, true);
								$locationSelect.append(opt).trigger('change');
							}
						} else {
							repopulateLocations('');
						}
					};

				// Initial population of locations on page load (select2/ajax)
				initLocationSelect2();
				syncLocationLabel();
				repopulateLanguages();
				repopulatePlacesLanguages();

				// Update languages list
				$updateLanguagesButton.on('click', function(event) {
					event.preventDefault();
					if ( $updateLanguagesButton.is(':disabled') ) {
						return;
					}
					var hasCreds = jQuery('#dataforseo_api_login').val() && jQuery('#dataforseo_api_password').val();
					if ( $updateLanguagesButton.data('requires-creds') && ! hasCreds ) {
						updateLanguageStatus('<?php 
        echo esc_js( __( 'No cached locations available. Please update the list first.', 'events-optimizer' ) );
        ?>', true);
						return;
					}
					$updateLanguagesButton.prop('disabled', true).text('<?php 
        echo esc_js( __( 'Updating …', 'events-optimizer' ) );
        ?>');
					if ( $languageLoading.length ) {
						$languageLoading.fadeIn('fast');
					}
					updateLanguageStatus('<?php 
        echo esc_js( __( 'Updating …', 'events-optimizer' ) );
        ?>', true);
					jQuery.ajax({
						type: 'POST',
						url: '<?php 
        echo esc_url( admin_url( 'admin-ajax.php' ) );
        ?>',
						data: {
							action: 'teoai_update_dataforseo_languages',
							_ajax_nonce: '<?php 
        echo esc_attr( $nonce );
        ?>'
						},
						success: function(response) {
							if ( response && response.success ) {
								repopulateLanguages();
								updateLanguageStatus('', false);
								if ( response.data && response.data.meta && response.data.meta.last_updated ) {
									updateLanguageLastUpdated(response.data.meta.last_updated);
								}
							} else if ( response && response.data && response.data.message ) {
								updateLanguageStatus(response.data.message, true);
							} else {
								updateLanguageStatus('<?php 
        echo esc_js( __( 'Language update failed.', 'events-optimizer' ) );
        ?>', true);
							}
						},
						error: function() {
							updateLanguageStatus('<?php 
        echo esc_js( __( 'Could not update languages. Please check credentials and try again.', 'events-optimizer' ) );
        ?>', true);
						},
						complete: function() {
							$updateLanguagesButton.prop('disabled', false).text('<?php 
        echo esc_js( __( 'Update list', 'events-optimizer' ) );
        ?>');
							if ( $languageLoading.length ) {
								$languageLoading.fadeOut('slow');
							}
						}
					});
				});

				$updateLocationsButton.on('click', function(event) {
				event.preventDefault();
				if ( $updateLocationsButton.is(':disabled') ) {
					return;
				}
				var hasCreds = jQuery('#dataforseo_api_login').val() && jQuery('#dataforseo_api_password').val();
				if ( ! hasCreds ) {
					updateLocationStatus('<?php 
        echo esc_js( __( 'Could not update languages. Please check credentials and try again.', 'events-optimizer' ) );
        ?>', true);
					return;
				}
				$updateLocationsButton.prop('disabled', true).text('<?php 
        echo esc_js( __( 'Updating …', 'events-optimizer' ) );
        ?>');
				if ( $locationLoading.length ) {
					$locationLoading.fadeIn('fast');
				}
				updateLocationStatus('<?php 
        echo esc_js( __( 'Updating …', 'events-optimizer' ) );
        ?>', true);

				jQuery.ajax({
					type: 'POST',
					url: '<?php 
        echo esc_url( admin_url( 'admin-ajax.php' ) );
        ?>',
					dataType: 'json',
					data: {
						action: 'teoai_refresh_dataforseo_locations',
						_ajax_nonce: '<?php 
        echo esc_attr( $nonce );
        ?>'
					},
					success: function(response) {
						if ( response && response.success ) {
							if ( response.data && response.data.meta && response.data.meta.last_updated ) {
								updateLocationLastUpdated(response.data.meta.last_updated);
							}
							if ( typeof $locationSelect.select2 === 'function' && $locationSelect.data('select2') ) {
								$locationSelect.val(null).trigger('change');
							} else {
								repopulateLocations('');
							}
							updateLocationStatus('', false);
						} else if ( response && response.data && response.data.message ) {
							if ( typeof $locationSelect.select2 === 'function' && $locationSelect.data('select2') ) {
								$locationSelect.val(null).trigger('change');
							} else {
								repopulateLocations('');
							}
							updateLocationStatus(response.data.message, true);
						} else {
							if ( typeof $locationSelect.select2 === 'function' && $locationSelect.data('select2') ) {
								$locationSelect.val(null).trigger('change');
							} else {
								repopulateLocations('');
							}
							updateLocationStatus('<?php 
        echo esc_js( __( 'Could not update locations. Please check credentials and try again.', 'events-optimizer' ) );
        ?>', true);
						}
					},
					error: function(response) {
						if ( typeof $locationSelect.select2 === 'function' && $locationSelect.data('select2') ) {
							$locationSelect.val(null).trigger('change');
						} else {
							repopulateLocations('');
						}
						var errMsg = '';
						if ( response && response.responseJSON && response.responseJSON.data && response.responseJSON.data.message ) {
							errMsg = response.responseJSON.data.message;
						} else if ( response && response.responseJSON && response.responseJSON.message ) {
							errMsg = response.responseJSON.message;
						}
						updateLocationStatus(errMsg || '<?php 
        echo esc_js( __( 'Could not update locations. Please check credentials and try again.', 'events-optimizer' ) );
        ?>', true);
					},
					complete: function() {
						$updateLocationsButton.prop('disabled', false).text('<?php 
        echo esc_js( __( 'Update list', 'events-optimizer' ) );
        ?>');
						if ( $locationLoading.length ) {
							$locationLoading.fadeOut('slow');
						}
					}
				});
			});

			// Update Google Places languages (Translation API)
			$placesLangUpdate.on('click', function(event) {
				event.preventDefault();
				if ( $placesLangUpdate.is(':disabled') ) {
					return;
				}
				var apiKey = jQuery('#google_places_api_key').val();
				var requiresKey = $placesLangUpdate.data('requires-key') === true || $placesLangUpdate.data('requires-key') === 'true';
				if ( requiresKey && ! apiKey ) {
					updatePlacesLangStatus('<?php 
        echo esc_js( __( 'Please add a Google Cloud API key first.', 'events-optimizer' ) );
        ?>', true);
					return;
				}
				$placesLangUpdate.prop('disabled', true).text('<?php 
        echo esc_js( __( 'Updating …', 'events-optimizer' ) );
        ?>');
				if ( $placesLangLoading.length ) {
					$placesLangLoading.fadeIn('fast');
				}
				updatePlacesLangStatus('<?php 
        echo esc_js( __( 'Updating …', 'events-optimizer' ) );
        ?>', false);
				jQuery.ajax({
					type: 'POST',
					url: '<?php 
        echo esc_url( admin_url( 'admin-ajax.php' ) );
        ?>',
					data: {
						action: 'teoai_update_google_translation_languages',
						_ajax_nonce: '<?php 
        echo esc_attr( $nonce );
        ?>'
					},
					success: function(response) {
						if ( response && response.success ) {
							repopulatePlacesLanguages();
							if ( response.data && response.data.meta && response.data.meta.last_updated ) {
								updatePlacesLangLastUpdated(response.data.meta.last_updated);
							}
							updatePlacesLangStatus('', false);
						} else if ( response && response.data && response.data.message ) {
							updatePlacesLangStatus(response.data.message, true);
						} else {
							updatePlacesLangStatus('<?php 
        echo esc_js( __( 'Language update failed.', 'events-optimizer' ) );
        ?>', true);
						}
					},
					error: function() {
						updatePlacesLangStatus('<?php 
        echo esc_js( __( 'Could not update languages. Please check the API key and try again.', 'events-optimizer' ) );
        ?>', true);
					},
					complete: function() {
						$placesLangUpdate.prop('disabled', false).text('<?php 
        echo esc_js( __( 'Update list', 'events-optimizer' ) );
        ?>');
						if ( $placesLangLoading.length ) {
							$placesLangLoading.fadeOut('slow');
						}
					}
				});
			});

			// Save settings
			jQuery('.teoai-save-settings').on('click', function(event)  { //start function when button is clicked
				event.preventDefault();
				var $button = jQuery(this);
				$button.attr("disabled", true); // Disable button while saving
				var $container = $button.closest('.nav-tab-content');
				var $loading = $container.find('.teoai-loading').not('#dataforseo_languages_loading').not('#dataforseo_locations_loading').not('#google_places_languages_loading');
				var $status = $container.find('.teoai-status');
				if ( ! $loading.length ) {
					$loading = jQuery('#loading_tab_settings');
				}
				if ( ! $status.length ) {
					$status = jQuery('#show_tab_settings');
				}
				var getChecked = function(id) {
					var el = document.getElementById(id);
					return el ? el.checked : false;
				};

				var getCheckedValues = function(selector) {
					return jQuery(selector).map(function() {
						return this.checked ? this.value : null;
					}).get();
				};
				jQuery.ajax({
					type: "POST",
					url: "<?php 
        echo esc_url( admin_url( 'admin-ajax.php' ) );
        ?>",
					data: {
						action: 'save_set', // call function "Save settings"
						max_results_per_page: 					jQuery( '#max_results_per_page' ).val(),

						duplicate_organizers_levenshtein: 		jQuery( '#duplicate_organizers_levenshtein' ).length ? jQuery( '#duplicate_organizers_levenshtein' ).val() : '',
						duplicate_venues_levenshtein: 			jQuery( '#duplicate_venues_levenshtein' ).length ? jQuery( '#duplicate_venues_levenshtein' ).val() : '',

						google_places_api_key: 					jQuery( '#google_places_api_key' ).val(),
						google_places_language: 				jQuery( '#google_places_language' ).val(),
						
						dataforseo_keyword:						jQuery( '#dataforseo_keyword' ).val(),
						dataforseo_api_login:					jQuery( '#dataforseo_api_login' ).val(),
						dataforseo_api_password:				jQuery( '#dataforseo_api_password' ).val(),
						dataforseo_location_code:				(function() {
							var val = jQuery( '#dataforseo_location_select' ).val();
							if ( ! val ) {
								val = jQuery( '#dataforseo_location_select' ).data( 'current' ) || '';
							}
							return val;
						})(),
						dataforseo_language_code:				jQuery( '#dataforseo_language_code' ).val(),							
						dataforseo_date_range:					jQuery( '#dataforseo_date_range' ).val(),				
						prefill_currency_symbol: 				getChecked( 'prefill_currency_symbol' ),
						max_images:								jQuery( '#max_images' ).val(),		

						openrouter_api_key: 					jQuery( '#openrouter_api_key' ).val(),

						openai_api_key: 						jQuery( '#openai_api_key' ).val(),
						openai_model:							jQuery( '#openai_model' ).val(),							
						openai_max_tokens: 						jQuery( '#openai_max_tokens' ).val(),									
						openai_language: 						jQuery( '#openai_language' ).val() ,
						openai_prompt_tone: 					jQuery( '#openai_prompt_tone' ).val() ,							
						openai_prompt_headings: 				getChecked( 'openai_prompt_headings' ),										
						openai_prompt_faq: 						getChecked( 'openai_prompt_faq' ),	
						openai_prompt_html: 					getChecked( 'openai_prompt_html' ),
						openai_prompt_emojis: 					getChecked( 'openai_prompt_emojis' ),
						openai_prompt_use_website:				getChecked( 'openai_prompt_use_website' ),
						openai_replace_content: 				getChecked( 'openai_replace_content' ),	
						openai_hide_generate_description_buttons:	getChecked( 'openai_hide_generate_description_buttons' ),	

						anthropic_claude_api_key: 				jQuery( '#anthropic_claude_api_key' ).val(),

						mistral_api_key:						jQuery( '#mistral_api_key' ).val(),

						groq_api_key:							jQuery( '#groq_api_key' ).val(),

						google_safe_browsing: 					getChecked( 'google_safe_browsing' ),
						validate_url_https: 					getChecked( 'validate_url_https' ),
						validate_url_redirected_moved: 			getChecked( 'validate_url_redirected_moved' ),							

						phone_number_format: 					jQuery( '#phone_number_format' ).val(),
						address_format: 						jQuery( '#address_format' ).val(),		
						preselection: 							jQuery( '#preselection' ).val(),
						cleanup_completed_runs_after_days:      jQuery( '#cleanup_completed_runs_after_days' ).val(),
						cleanup_problem_runs_after_days:        jQuery( '#cleanup_problem_runs_after_days' ).val(),

						element_id: 							jQuery( '#element_id' ).val(),
						show_ignored_objects: 					getChecked( 'show_ignored_objects' ),	
						//show_events_added: 						getChecked( 'show_events_added' ),
						show_added_objects: 					getChecked( 'show_added_objects' ),
						
						ignored_field_venue_description: 		getChecked( 'ignored_field_venue_description' ),			
						ignored_field_venue_address: 			getChecked( 'ignored_field_venue_address' ),								
						ignored_field_venue_zip: 				getChecked( 'ignored_field_venue_zip' ),								
						ignored_field_venue_city: 				getChecked( 'ignored_field_venue_city' ),								
						ignored_field_venue_province: 			getChecked( 'ignored_field_venue_province' ),								
						ignored_field_venue_state: 				getChecked( 'ignored_field_venue_state' ),								
						ignored_field_venue_country: 			getChecked( 'ignored_field_venue_country' ),								
						ignored_field_venue_phone: 				getChecked( 'ignored_field_venue_phone' ),								
						ignored_field_venue_website: 			getChecked( 'ignored_field_venue_website' ),	
						ignored_field_venue_business_status: 	getChecked( 'ignored_field_venue_business_status' ),
																				
						ignored_field_organizer_description: 	getChecked( 'ignored_field_organizer_description' ),								
						ignored_field_organizer_phone: 			getChecked( 'ignored_field_organizer_phone' ),								
						ignored_field_organizer_website: 		getChecked( 'ignored_field_organizer_website' ),								
						ignored_field_organizer_mail: 			getChecked( 'ignored_field_organizer_mail' ),
						ignored_field_organizer_business_status:getChecked( 'ignored_field_organizer_business_status' ),
																					
						ignored_field_event_description: 		getChecked( 'ignored_field_event_description' ),								
						ignored_field_event_start: 				getChecked( 'ignored_field_event_start' ),								
						ignored_field_event_end: 				getChecked( 'ignored_field_event_end' ),								
						ignored_field_event_venue: 				getChecked( 'ignored_field_event_venue' ),								
						ignored_field_event_organizer: 			getChecked( 'ignored_field_event_organizer' ),
						ignored_field_event_website: 			getChecked( 'ignored_field_event_website' ),								
						ignored_field_event_currency_symbol: 	getChecked( 'ignored_field_event_currency_symbol' ),		
						ignored_field_event_cost: 				getChecked( 'ignored_field_event_cost' ),								

						allowed_role: 							getCheckedValues( 'input[name=\"allowed_role[]\"]' ),							
				
						//remove_settings: 						jQuery( '#remove_settings' ).val(),																							
						_wpnonce: '<?php 
        echo esc_attr( $nonce );
        ?>',
						_ajax_nonce: '<?php 
        echo esc_attr( $nonce );
        ?>'																		
					},
					beforeSend: function() {
						$loading.fadeIn('fast');
						$status.fadeOut("slow");
					}, 
					success: function(html){ //if data is retrieved, store it in html
						$loading.fadeOut('slow');
						$status.html( html ); //show the html inside formstatus div
						$status.fadeIn("fast"); //animation
						$button.attr("disabled", false);
						location.reload(); // reload setting page that everything is shown with updated data
					},
					error: function() {
						$button.attr("disabled", false);
					}
				}); //close jQuery.ajax
				return false;					
			});

			// Reset list with objects added
			jQuery('#reset_objects_added_button').on('click', function()  {
				jQuery("#reset_objects_added_button").attr("disabled", true);	
				jQuery.ajax({
					type: "POST",
					url: "<?php 
        echo esc_url( admin_url( 'admin-ajax.php' ) );
        ?>",
					data: { 
						action: 'reset_object_li', // call function "reset objects list"
						status: 'added',
						_ajax_nonce: '<?php 
        echo esc_attr( $nonce );
        ?>' 
					},
					beforeSend: function() {
					},
					success: function(html){
						jQuery("#reset_objects_added_button").attr("disabled", false);
						location.reload(); // reload setting page that everything is shown with updated data						
					}
				});
				return false;					
			});	

			// Reset list with objects ignored
			jQuery('.reset-objects-ignored-button').on('click', function()  {
				var $btn = jQuery(this);
				$btn.attr("disabled", true);	
				jQuery.ajax({
					type: "POST",
					url: "<?php 
        echo esc_url( admin_url( 'admin-ajax.php' ) );
        ?>",
					data: { 
						action: 'reset_object_li', // call function "reset objects list"
						status: $btn.data('status') || 'ignored',
						_ajax_nonce: '<?php 
        echo esc_attr( $nonce );
        ?>' 
					},
					beforeSend: function() {
					},
					success: function(html){
						$btn.attr("disabled", false);
						location.reload(); // reload setting page that everything is shown with updated data						
					}
				});
				return false;					
			});	
																		
			// Remove object from list (make available globally for inline onclick handlers)
			window.remove_object = function(id, $row) {
				var $target = ($row && $row.length) ? $row : jQuery(".teoai-remove-object[data-object-id='" + id + "']").closest("[id^='object_']");
				if ( ! $target.length ) {
					return false;
				}

				$target.attr('disabled','disabled').css('opacity',0.4);
				jQuery.ajax({
					type: "POST",
					url: "<?php 
        echo esc_url( admin_url( 'admin-ajax.php' ) );
        ?>",
					data: { 
						action: 'remove_obj',
						_ajax_nonce: '<?php 
        echo esc_attr( $nonce );
        ?>',
						id: id,
					},
					beforeSend: function() {
						$target.fadeOut('fast');	// Fade out status after data is ignored	
					},
					success: function() {					
						$target.remove();
					},
					error: function() {
						$target.css('opacity', 1).fadeIn('fast');
					}
				}); //close jQuery.ajax
				return false;	
			};
		});
		</script>
	<?php 
    }

}