<?php
if ( ! is_array( $this->params['data']['UptimeUrl'] ) ) {  // is it object retrieved for monitor editing?
	$url = $this->params['data']['UptimeUrl'];
	$this->params['data']['UptimeUrl'] = array();
	$this->params['data']['UptimeUrl']['url_friendly_name'] = $url->url_friendly_name;
	$this->params['data']['UptimeUrl']['url_api_key'] = $url->url_api_key;
	$this->params['data']['UptimeUrl']['url_address'] = $url->url_address;
	$this->params['data']['UptimeUrl']['url_not_email'] = $url->url_not_email;
	$this->params['data']['UptimeUrl']['url_monitor_type'] = $url->url_monitor_type;
	$this->params['data']['UptimeUrl']['url_monitor_subtype'] = $url->url_monitor_subtype;
	$this->params['data']['UptimeUrl']['url_monitor_keywordtype'] = $url->url_monitor_keywordtype;
	$this->params['data']['UptimeUrl']['url_monitor_keywordvalue'] = $url->url_monitor_keywordvalue;
	$this->params['data']['UptimeUrl']['monitor_interval'] = $url->monitor_interval;
  $this->params['data']['UptimeUrl']['http_username'] = $url->http_username;
  $this->params['data']['UptimeUrl']['http_password'] = $url->http_password;
	$this->params['data']['UptimeUrl']['url_id'] = $url->url_id;
}

// For test on local host
global $wpdb;

// process monitor that don't exist
global $current_user;

$orderby = 'wp.url';

global $wpdb;

$sql = 'SELECT url_address FROM ' . $wpdb->prefix . 'aum_urls';
$result = $wpdb->get_results( $sql );
$current_sites_addresses = array();

for ( $i = 0; $i < count( $result ); $i++ ) {
	$current_sites_addresses[ $i ] = $result[ $i ]->url_address;
}

global $mainwpAdvancedUptimeMonitorExtensionActivator;
$pWebsites = apply_filters( 'mainwp-getsites', $mainwpAdvancedUptimeMonitorExtensionActivator->get_child_file(), $mainwpAdvancedUptimeMonitorExtensionActivator->get_child_key(), null );
if ( count( $current_sites_addresses ) > 0 ) {
	foreach ( $pWebsites as $website ) {
		$url = rtrim( $website['url'], '/' );
		if ( ! in_array( $url, $current_sites_addresses ) ) {
			$other_site_urls[ $url ] = stripslashes( $website['name'] );
		}
	}
} else {
	foreach ( $pWebsites as $website ) {
		$url = rtrim( $website['url'], '/' );
		$other_site_urls[ $url ] = stripslashes( $website['name'] );
	}
}


if ( count( $other_site_urls ) > 0 ) {
	$_urls = array_keys( $other_site_urls );
	$tring_result = array_shift( $_urls );
} else {
	$tring_result = 'http://';
}

$edit_url_id  = 0;
$list_notification_contact = Advanced_Uptime_Monitor_Extension::get_install()->get_option( 'list_notification_contact' );
?>

<?php echo $this->form->create( $model->name ); ?>
<!-- Add New Monitor Form -->
<div class="ui form">
	<div id="popup_message_info_box" class="ui green message" style="display: none"></div>
	<div id="popup_message_error_box" class="ui red message" style="display: none"></div>
	<?php $this->display_flash(); ?>

	<input type="hidden" name="title" value="<?php echo $title ?>" />

	<?php
	if ( isset( $this->params['url_id'] ) ) {
		$edit_url_id = $this->params['url_id'];
		echo $this->form->hidden_input( 'url_id', array( 'value' => $this->params['url_id'] ) );
	} elseif ( isset( $this->params['data']['UptimeUrl']['url_id'] ) )
		$edit_url_id = $this->params['data']['UptimeUrl']['url_id'];
		echo $this->form->hidden_input( 'url_id', array( 'value' => $this->params['data']['UptimeUrl']['url_id'] ) );

	if ( isset( $monitor ) ) {
		echo $this->form->hidden_input( 'monitor_id', array( 'value' => $monitor->monitor_id ) );
	} elseif ($this->params['monitor_id'] )
		echo $this->form->hidden_input( 'monitor_id', array( 'value' => $this->params['monitor_id'] ) );

  if ( isset( $this->params['api_key'] ) ) {
    echo $this->form->hidden_input( 'add_monitor_api_key', array( 'value' => $this->params['api_key'] ) );
  }

 ?>

	<div class="ui diving header"><?php echo __( 'Monitor Information', 'advanced-uptime-monito-extension' ); ?></div>

	<div class="ui grid field monitor_type">
		<label class="six wide column middle aligned"><?php _e( 'Monitor type', 'advanced-uptime-monitor-extension' ); ?></label>
		<div class="ten wide column">
			<?php
			$args = array( 'options' => Advanced_Uptime_Monitor_Extension::get_install()->monitor_types );
			if ( isset( $this->params['data']['UptimeUrl'] ) ) {
				$args['value'] = $this->params['data']['UptimeUrl']['url_monitor_type'];
			}
			echo $this->form->select( 'data[UptimeUrl][url_monitor_type]', $args );
			?>
		</div>
	</div>

	<div class="ui grid field monitor_subtype" style="display:none">
		<label class="six wide column middle aligned"><?php _e( 'Monitor subtype', 'advanced-uptime-monitor-extension' ); ?></label>
		<div class="ten wide column">
			<?php
			$monitors_subtypes = array(
				'1' => 'HTTP',
				'2' => 'HTTPS',
				'3' => 'FTP',
				'4' => 'SMTP',
				'5' => 'POP3',
				'6' => 'IMAP',
			);

			$args = array( 'options' => $monitors_subtypes );
			if ( isset( $this->params['data']['UptimeUrl'] ) ) {
				$args['value'] = $this->params['data']['UptimeUrl']['url_monitor_subtype'];
			}
			echo $this->form->select( 'data[UptimeUrl][url_monitor_subtype]', $args );
			?>
		</div>
	</div>

	<div class="ui grid field url_monitor_keywordtype" style="display:none">
		<label class="six wide column middle aligned"><?php _e( 'Alert when', 'advanced-uptime-monitor-extension' ); ?></label>
		<div class="ten wide column">
			<div class="ui radio checkbox"><input type="radio" name="data[UptimeUrl][url_monitor_keywordtype]" value=1 id="keywordtype1" <?php echo (isset( $this->params['data']['UptimeUrl'] ) && $this->params['data']['UptimeUrl']['url_monitor_keywordtype'] == '1' ? 'checked=checked' : '') ?> /><label for="keywordtype1"><?php _e( 'exists', 'advanced-uptime-monitor-extension' ); ?></label></div><br />
			<div class="ui radio checkbox"><input type="radio" name="data[UptimeUrl][url_monitor_keywordtype]" value=2 id="keywordtype2" <?php echo (isset( $this->params['data']['UptimeUrl'] ) && $this->params['data']['UptimeUrl']['url_monitor_keywordtype'] == '2' ? 'checked=checked' : '') ?> /><label for="keywordtype2"><?php _e( 'not exists', 'advanced-uptime-monitor-extension' ); ?></label></div>
		</div>
	</div>

	<div class="ui grid field url_monitor_keywordvalue" style="display:none">
		<label class="six wide column middle aligned"><?php _e( 'Keyword', 'advanced-uptime-monitor-extension' ); ?></label>
		<div class="ten wide column">
			<input type="text" name="data[UptimeUrl][url_monitor_keywordvalue]" value="<?php echo (isset( $this->params['data']['UptimeUrl'] ) ? esc_textarea( $this->params['data']['UptimeUrl']['url_monitor_keywordvalue'] ) : '') ?>">
		</div>
	</div>

	<?php
	$style_select = 'style="display:none"';
    $style_text = 'style="display:flex"';
	if ( isset( $this->params['checkbox_show_select'] ) && count( $other_site_urls ) >= 1 ) {
		$style_select = 'style="display:flex"';
		$style_text = 'style="display:none"';
	} else {
		$friendly_n = '';
		if ( isset( $this->params['data']['UptimeUrl']['url_friendly_name'] ) ) {
			$friendly_n = $this->params['data']['UptimeUrl']['url_friendly_name'];
		}
	}
	?>

	<div class="ui grid field monitor_url_friendly_name_text" <?php echo $style_text; ?>>
		<label class="six wide column middle aligned"><?php _e( 'Friendly name', 'advanced-uptime-monitor-extension' ); ?></label>
		<div class="ten wide column">
			<input type="text" name="url_friendly_name_textbox" value="<?php echo esc_attr( $friendly_n ); ?>">
		</div>
	</div>



	<div class="ui grid field" >
		<label class="six wide column middle aligned"><?php _e( 'URL (or IP)', 'advanced-uptime-monitor-extension' ); ?></label>
		<div class="ten wide column">
			<?php
					if ( isset( $this->params['data']['UptimeUrl']['url_address'] ) ) {
						echo $this->form->input( 'url_address', array( 'label' => '', 'value' => $this->params['data']['UptimeUrl']['url_address'] ) );
					} else {
						echo $this->form->input( 'url_address', array( 'label' => '', 'value' => 'http://' ) );
					}
			?>
		</div>
	</div>

	<?php
		if ( isset( $this->params['data']['UptimeUrl'] ) && ! empty( $this->params['data']['UptimeUrl']['url_api_key'] ) ) {
				echo $this->form->input( 'url_api_key', array( 'label' => __( 'Monitor API key:', 'advanced-uptime-monitor-extension' ), 'value' => (isset( $this->params['data']['UptimeUrl'] ) ? $this->params['data']['UptimeUrl']['url_api_key'] : '') ) );
		}
	?>

	<div class="ui grid field" >
		<label class="six wide column middle aligned"><?php _e( 'Monitoring interval (in minutes)', 'advanced-uptime-monitor-extension' ); ?></label>
		<div class="ten wide column">
			<?php echo $this->form->input( 'monitor_interval', array( 'label' => '', 'value' => !empty($this->params['data']['UptimeUrl']['monitor_interval'] ) ? $this->params['data']['UptimeUrl']['monitor_interval'] : 5 ) ); ?>
		</div>
	</div>

	<?php if ( is_array( $list_notification_contact ) && count( $list_notification_contact ) > 0 ) { ?>

	<?php
	$alert_contacts = array();
	if ( ! empty( $this->params['monitor_contacts_notification'] ) ) {
		$alert_contacts = explode( '-', $this->params['monitor_contacts_notification'] );
	} else if ( isset( $this->params['data']['UptimeUrl']['url_not_email'] ) && count( $this->params['data']['UptimeUrl']['url_not_email'] ) > 0 ) {
		$alert_contacts = $this->params['data']['UptimeUrl']['url_not_email'];
	}

	$default_contact_id = Advanced_Uptime_Monitor_Extension::get_install()->get_option( 'uptime_default_notification_contact_id' ); ?>

	<div class="ui grid field" >
		<label class="six wide column middle aligned"><?php _e( 'Select alert contacts to notify', 'advanced-uptime-monitor-extension' ); ?></label>
		<div class="ten wide column">
			<?php
			if ( count( $alert_contacts ) > 0 ) {
				foreach ( $list_notification_contact as $key => $val ) {
					$checked_flag = '';
					if ( in_array( $key, $alert_contacts ) ) {
						$checked_flag = 'checked="checked"';
					}

                    echo '<label class="label2"><input type="checkbox" name="checkbox_contact" value="' . esc_attr( $key ) . '"' . $checked_flag . '> ' . esc_html( $val ) . '</label><br/>';
				}
			} else {

				foreach ( $list_notification_contact as $key => $val ) {
					if ( $default_contact_id == $key ) {
						$checked = empty( $this->params['data']['UptimeUrl']['url_id'] ) ? ' checked="checked"' : '';
					} else {
						$checked = '';
					}
						echo '<label class="label2"><input type="checkbox" name="checkbox_contact" value="' . esc_attr( $key ) . '" ' . $checked . '> ' . esc_html( $val ) . '</label><br/>';
				}
			}
			?>
		</div>
	</div>

	<div class="ui diving header"><?php echo __( 'HTTP Basic Authentication Settings', 'advanced-uptime-monito-extension' ); ?></div>

	<div class="ui grid field" >
		<label class="six wide column middle aligned"><?php _e( 'HTTP Username (Optional)', 'advanced-uptime-monitor-extension' ); ?></label>
		<div class="ten wide column">
			<?php echo $this->form->input( 'http_username', array( 'label' => '', 'value' => !empty($this->params['data']['UptimeUrl']['http_username'] ) ? $this->params['data']['UptimeUrl']['http_username'] : '') ); ?>
		</div>
	</div>

	<div class="ui grid field" >
		<label class="six wide column middle aligned"><?php _e( 'HTTP Password (Optional)', 'advanced-uptime-monitor-extension' ); ?></label>
		<div class="ten wide column">
			<?php echo $this->form->input( 'http_password', array( 'label' => '', 'value' => !empty($this->params['data']['UptimeUrl']['http_password'] ) ? $this->params['data']['UptimeUrl']['http_password'] : '' ) ); ?>
		</div>
	</div>

	<?php } ?>

</div>


<input type="hidden" name="monitor_contacts_notification" value="<?php echo (isset( $this->params['monitor_contacts_notification'] ) ? esc_attr( $this->params['monitor_contacts_notification'] ) : esc_attr( $default_contact_id )); ?>" />
<?php
$timestamp = time();
$submit_text = empty( $this->params['data']['UptimeUrl']['url_id'] ) ? __( 'Create Monitor', 'advanced-uptime-monitor-extension' ) : __( 'Save Monitor', 'advanced-uptime-monitor-extension' );
?>
<input type="hidden" name="action" value="admin_uptime_monitors_url_form">
<input type="hidden" name="wp_nonce" value="<?php echo wp_create_nonce( 'aum_nonce_url_form' ); ?>">
<div class="ui divider"></div>
<input type="button" value="<?php echo $submit_text; ?>" class="ui green button" id="aum_edit_monitor_button_<?php echo $timestamp;?>">
</form>
<!-- End Add New Monitor Form -->

<script type="text/javascript">
    jQuery(document).ready(function () {
		jQuery( '#aum_edit_monitor_button_<?php echo $timestamp; ?>' ).on('click', function (event) {
			event.preventDefault();
			var errors = [];
			jQuery('div.error').hide();

            var contacts_chossen = '';
            jQuery('input:checkbox[name=checkbox_contact]').each(function () {
                if (this.checked)
                {
                    contacts_chossen += jQuery.trim(jQuery(this).val()) + '-';
                }
            });
            contacts_chossen = contacts_chossen.slice(0, -1);
            jQuery('input[name=monitor_contacts_notification]').val(contacts_chossen);

			if (jQuery('input[name=monitor_contacts_notification]').val() == '')
            {
				errors.push('Please select at least one Alert Contact');
            }
			if (!jQuery('input[name=checkbox_show_select]').is(':checked') && jQuery('input[name=url_friendly_name_textbox]').val() == '')
            {
				errors.push('Please enter Monitor Friendly Name');

            }
			if (jQuery('#UptimeUrlUrlAddress').val() == '')
            {
				errors.push('Please enter URL (or IP)');

            }

			if (errors.length > 0) {
				jQuery('#popup_message_error_box').html(errors.join('<br />')).show();
				return false;
			}

            jQuery('div.monitor_url_friendly_name select option').each(function () {
                      var html_name = jQuery(this).html();
                      jQuery(this).val( html_name );
            } )

			jQuery('#popup_message_info_box').html('<i class="notched circle loading icon"></i> Action in progress. Please wait...').show();
			jQuery('#popup_message_error_box').html('').hide();
			jQuery(this).attr('disabled', 'disabled');
			var data = jQuery(this).closest('form').serialize();
			jQuery.ajax({
				url: ajaxurl,
				type: 'GET',
				data: data,
				error: function () {
					jQuery('#mainwp-create-edit-monitor-modal #popup_message_error_box').html('Unexpected error. Please try again.');
				},
				success: function (response) {
					jQuery('#mainwp-create-edit-monitor-modal').find('.content').html( response );
				},
				timeout: 20000
			});
			return false;
		});

        jQuery('input[name=checkbox_show_select]').change(function () {
            var item = '<?php echo $tring_result; ?>';
            if (jQuery(this).is(':checked')) {
                jQuery('tr.monitor_url_friendly_name_text').hide(); // css('display', 'none');
                jQuery('tr.monitor_url_friendly_name').show(); // css('display', 'block');
                jQuery('tr.monitor_url_friendly_name div select').prop('selectedIndex', 0);

                jQuery('input#UptimeUrlUrlAddress').val(item);
                jQuery('input#UptimeUrlUrlAddress').attr('readonly', 'readonly');
            } else {
                jQuery('tr.monitor_url_friendly_name').hide(); //css('display', 'none');
                jQuery('tr.monitor_url_friendly_name_text').show(); //css('display', 'block');
                jQuery('tr.monitor_url_friendly_name_text input').val('');
                jQuery('input#UptimeUrlUrlAddress').val('http://');
                jQuery('input#UptimeUrlUrlAddress').removeAttr('readonly');
            }
        });

        jQuery('.monitor_type select').change(function () {
            if (jQuery(this).val() == '4')
                jQuery('.monitor_subtype').show();
            else
                jQuery('.monitor_subtype').hide();

            if (jQuery(this).val() == '2') {
                jQuery('.url_monitor_keywordtype').show();
                jQuery('.url_monitor_keywordvalue').show();
            } else {
                jQuery('.url_monitor_keywordtype').hide();
                jQuery('.url_monitor_keywordvalue').hide();
            }
        })

        jQuery('div.monitor_url_address select').attr('disabled', 'disabled');

        jQuery('.monitor_url_friendly_name').change(function ()
        {
            var select = jQuery('.monitor_url_friendly_name select option:selected').val();
            jQuery('input#UptimeUrlUrlAddress').val(select);
        })

        jQuery('tr.aum_contacts_list').change(function () {
//            var contacts_chossen = '';
//            jQuery('input:checkbox[name=checkbox_contact]').each(function () {
//                if (this.checked)
//                {
//                    // jQuery.trim(contacts_chossen);
//                    contacts_chossen += jQuery.trim(jQuery(this).val()) + '-';
//                }
//            });
//            contacts_chossen = contacts_chossen.slice(0, -1);
//            jQuery('input[name=monitor_contacts_notification]').val(contacts_chossen);
        });
<?php
if ( isset( $this->params['data']['UptimeUrl'] ) && $this->params['data']['UptimeUrl']['url_monitor_type'] == '4' ) {
	echo "jQuery('.monitor_subtype').show();";
}

if ( isset( $this->params['data']['UptimeUrl'] ) && $this->params['data']['UptimeUrl']['url_monitor_type'] == '2' ) {
	echo "jQuery('.url_monitor_keywordtype').show();jQuery('.url_monitor_keywordvalue').show();";
}
if ( isset($url_saved) && $url_saved ) {
	?>
            jQuery('.url_form').find('input').attr('disabled', 'disabled');
            jQuery('.url_form').find('select').attr('disabled', 'disabled');
            jQuery('.url_form').find('textarea').attr('disabled', 'disabled');
            setTimeout(function () {
//                parent.location.reload(true);
                location.href = location.href
            }, 3000);
    <?php
}
?>
    });
</script>
