<?php

function du_register_bulk_actions( $bulk_actions ) {
	if ( du_has_permission( 'upload' ) ) {
		$bulk_actions['du_bulk_upload'] = __( 'Upload to ', 'du' ) . DU_NAME;
	}

	return $bulk_actions;
}

function du_bulk_action_handler( $redirect_to, $doaction, $post_ids ) {
	if ( $doaction !== 'du_bulk_upload' ) {
		return $redirect_to;
	}

	if ( du_has_permission( 'upload' ) ) {
		foreach ( $post_ids as $post_id ) {
			du_handle_save_to_cloud( $post_id ); //slooooow
		}

		$redirect_to = add_query_arg( 'du_bulk_uploaded_layouts', count( $post_ids ), $redirect_to );
	}

	return $redirect_to;
}

function du_bulk_action_admin_notice() {
	if ( ! empty( $_REQUEST['du_bulk_uploaded_layouts'] ) ) {
		$uploaded_count = intval( $_REQUEST['du_bulk_uploaded_layouts'] );

		printf( '<div id="message" class="updated fade"><p>' .
		        _n( 'Uploaded %s layout to ',
			        'Uploaded %s layouts to ',
			        $uploaded_count,
			        'du'
		        ) . DU_NAME . '</p></div>', $uploaded_count );
	}
}

function du_admin_notices() {
	global $pagenow;

	$supported_types = apply_filters( 'du_gallery_pulldown_builder_supported_types', array(
		'post',
		'page',
		'product',
		'project',
		'testimonial',
	) );

	$pt      = ( isset( $_GET['post_type'] ) ? $_GET['post_type'] : 'post' );
	$builder = apply_filters( 'du_gallery_pulldown_builder', 'all', $pt );

	if ( $pagenow == 'edit.php' && in_array( $pt, $supported_types ) ) {
		echo '<div class="du-gallery du-gallery-pulldown">
				<a onclick="du_close_gallery_pulldown();" class="du_admin_button du_gallery_pulldown_close">Close ' . DU_NAME . '</a>
		        <div class="du" data-pt="' . $pt . '" data-layout_type="layout"></div>
		        <div class="du-tab"><div class="du-content" data-builder="' . $builder . '"><p>Loading. One moment please...</p></div></div>
		    </div>';
		echo '<a onclick="du_show_gallery_pulldown();" class="du_admin_button du_gallery_modal_trigger">Open ' . DU_NAME . '</a>';
	}
}

function du_admin_column_headers( $columns ) {
	if ( du_has_permission( 'upload' ) ) {
		$columns['du_cloud'] = '<span class="dashicons dashicons-cloud"></span>&nbsp;' . DU_NAME;
	}

	return $columns;
}

function du_admin_column_content( $column, $post_id ) {
	switch ( $column ) {
		case 'du_cloud' :
			echo du_import_export_col_detail( $post_id );
			break;
	}
}

function du_import_export_col_detail( $post_id ) {
	$uploaded = get_post_meta( $post_id, 'du_uploaded_to_cloud', true );
	$imported = get_post_meta( $post_id, 'du_imported_from_cloud', true );

	if ( $uploaded ) {
		echo '<div class="du-imported"><span title="Uploaded to ' . DU_NAME . '" class="dashicons dashicons-arrow-up-alt2"></span>&nbsp;' . $uploaded . '</div>';
	}

	if ( $imported ) {
		echo '<div class="du-imported"><span title="Imported from ' . DU_NAME . '" class="dashicons dashicons-arrow-down-alt2"></span>&nbsp;' . $imported . '</div>';
	}
}

function du_admin_footer() {
	echo '<div class="du-ajax-spinner" style="display: none;"><div class="du-spinner-container"><img src="' . DU_IMAGE_URL . 'ajax-loading.gif" alt="Loading Image" /><span class="du-api-feedback">One moment please...</span></div></div>';
}

function du_menu() {

	$default_link = ( du_has_permission( 'du_layouts' ) ? 'du_gallery_view' : ( du_has_permission( 'my_cloud' ) ? 'du_submenu_mc' : 'layouts_cloud' ) );

	add_menu_page(
		DU_NAME,
		DU_NAME,
		'manage_options',
		'du_admin_home',
		$default_link,
		'dashicons-cloud',
		500
	);

	if ( du_has_permission( 'du_layouts' ) ) {
		add_submenu_page(
			'du_admin_home',
			'All Layouts',
			'All Layouts',
			'manage_options',
			'du_gallery_view',
			'du_gallery_view'
		);
	}

	if ( du_has_permission( 'my_cloud' ) ) {
		add_submenu_page(
			'du_admin_home',
			'My Cloud',
			'My Cloud',
			'manage_options',
			'du_submenu_mc',
			'du_submenu_mc'
		);
	}

	if ( du_has_permission( 'snippets' ) ) {
		add_submenu_page(
			'du_admin_home',
			'Snippets',
			'Snippets',
			'manage_options',
			'du_submenu_sn',
			'du_submenu_sn'
		);
	}

	add_submenu_page(
		'du_admin_home',
		'Settings',
		'Settings',
		'manage_options',
		'layouts_cloud',
		'du_submenu_cb'
	);

	remove_submenu_page( 'du_admin_home', 'du_admin_home' );

}

function du_account_info( $key ) {
	global $du_remote_site;

	$url = $du_remote_site . '?du_api_key=' . $key . '&du_domain=' . urlencode( site_url() ) . '&du_action=get-account';

	if ( DU_DEBUG || ! get_option( 'du_api_key_active' ) ) {
		delete_option( 'du_premium' );
		delete_option( 'du_premium_cloud' );
		delete_transient( 'du-account-' . $key );
	}

	//echo $url;

	if ( ! $return = get_transient( 'du-account-' . $key ) ) { //this is important as we hit it a lot
		if ( $return = du_call( $url ) ) {
			$key_active    = 0;
			$premium       = 0;
			$premium_cloud = 0;

			//api key passed and an action 'get-account' to get info on the user to whom the key belongs
			if ( ! isset( $return['error'] ) || ! $return['error'] ) {
				$return['debug'] = false;

				if ( isset( $return['name'] ) && $return['name'] ) { //if we can link their account to a name then it's technically valid.
					$key_active = 1;

					if ( isset( $return['premium_cloud'] ) ) {
						if ( $return['premium_cloud'] ) {
							$premium_cloud = 1;
						}
					}

					if ( isset( $return['premium'] ) ) {
						if ( $return['premium'] ) {
							$premium = 1;
						}
					}
				}

				du_update_permissions( $return );

				set_transient( 'du-account-' . $key, $return, 3600 ); //cache for an hour. but this will be killed if visiting the account tab on the settings page
			} else {
				//the only error are that there is no user for the key sent so error means to disable du premium on this site
			}

			update_option( 'du_premium', $premium );
			update_option( 'du_premium_cloud', $premium_cloud );
			update_option( 'du_api_key_active', $key_active );
		}
	}

	return $return;
}

function du_upload_summary( $key = false ) {
	global $du_remote_site;

	if ( ! $key ) {
		$key = get_option( 'du_api_key' );
	}

	$url = $du_remote_site . '?du_api_key=' . $key . '&du_domain=' . urlencode( site_url() ) . '&du_action=get-upload-summary';

	if ( DU_DEBUG ) {
		delete_transient( 'du-upload_summary-' . $key );
	}

	if ( ! $return = get_transient( 'du-upload_summary-' . $key ) ) {
		if ( $return = du_call( $url ) ) {
			//api key passed and an action 'get-account' to get info on the user to whom the key belongs
			if ( ! isset( $return['error'] ) || ! $return['error'] ) {
				//there was no error
				$return['debug']     = false;
				$return['timestamp'] = date( 'Y-m-d H:i' );

				set_transient( 'du-upload_summary-' . $key, $return, 300 ); //five minutes. makes no odds if the numbers don't change often
			}
		}
	}

	return $return;
}

function du_gallery_view() {
	$key         = get_option( 'du_api_key' );
	$key_active  = get_option( 'du_api_key_active' );
	$white_label = get_option( 'du_white_labelling', array() );

	if ( ! $key && ! $key_active ) {
		echo '<script>window.location="' . admin_url( 'admin.php?page=layouts_cloud' ) . '";</script>';
		die; //redirecting to settings page
	}

	echo '<div class="wrap lc_wrap">
					<h2><span style="width: 30px; height: 30px; font-size: 30px;" class="dashicons dashicons-cloud"></span> ' . DU_NAME . ' - V' . DU_VERSION . '</h2>';

	echo '<div id="poststuff2">
					<div id="post-body" class="metabox-holder columns-2">';
	////////////////

	echo '<div style="clear: both;">';

	//echo du_box_start('Divi Cloud');

	echo '<div class="du-gallery">
					<div class="du" data-layout_type="layout"></div>';

	if ( ! isset( $white_label['disable_dc'] ) && du_has_permission( 'du_layouts' ) ) {
		echo '      <div class="du-gallery-layout-types">
						<div class="du-layout-type-filter active" data-layout_type="layout">Layouts</div>
						<div class="du-layout-type-filter" data-layout_type="section">Sections</div>
			        </div>';
	}

	echo '        <div class="du-tab"></div>
				</div>';

	echo '<script> jQuery(document).ready(function() {';

	if ( DU_DEFAULT_VIEW == 'my-cloud' || ! du_has_permission( 'du_layouts' ) ) {
		echo ' du_my_cloud(); ';
	} else {
		echo ' du_populate_frame(); ';
	}

	echo '}); </script>';

	//echo du_box_end();

	echo '</div>';

	////////////////
	echo '</div>'; //poststuff
	echo '</div>';
	echo '</div>';
}

function du_maybe_redirect_not_active() {
	$key        = get_option( 'du_api_key' );
	$key_active = get_option( 'du_api_key_active' );

	if ( ! $key || ! $key_active ) {
		echo '<script>window.location="' . admin_url( 'admin.php?page=layouts_cloud' ) . '";</script>';
		die; //redirecting to settings page
	}
}

function du_submenu_mc() {
	$white_label = get_option( 'du_white_labelling', array() );

	du_maybe_redirect_not_active();

	echo '<div class="wrap lc_wrap">
					<h2><span style="width: 30px; height: 30px; font-size: 30px;" class="dashicons dashicons-cloud"></span> ' . DU_NAME . ' - V' . DU_VERSION . '</h2>';

	echo '<div id="poststuff2">
					<div id="post-body" class="metabox-holder columns-2">';
	////////////////

	echo '<div style="clear: both;">';

	//echo du_box_start('Divi Cloud');

	echo '<div class="du-gallery">
					<div class="du" data-layout_type="layout"></div>';

	echo '        <div class="du-tab"></div>
				</div>';

	echo '<script> jQuery(document).ready(function() { du_my_cloud(); }); </script>';

	//echo du_box_end();

	echo '</div>';

	////////////////
	echo '</div>'; //poststuff
	echo '</div>';
	echo '</div>';
}

function du_submenu_sn() {
	du_maybe_redirect_not_active();

	echo '<div class="wrap lc_wrap">
					<h2><span style="width: 30px; height: 30px; font-size: 30px;" class="dashicons dashicons-cloud"></span> ' . DU_NAME . ' - V' . DU_VERSION . '</h2>';

	echo '<div id="poststuff2">
					<div id="post-body" class="metabox-holder columns-2">';
	////////////////

	echo '<p>A snippet is a block of text and our snippets system allows you to store your content on our secure server and when you\'re developing sites you can easily grab that crucial bit of info you misplaced. It doesn\'t need to be text either... you can use it for any programming language so CSS snippets, PHP, JS, license keys and the like. Go nuts!</p>';

	echo '<div style="clear: both;">';

	echo '<div class="du-gallery du-snippet-gallery">
					<div class="du" data-layout_type="snippet"></div>';

	echo '        <div class="du-tab">Snippets</div>
				</div>';

	echo '<script> jQuery(document).ready(function() { du_my_snippets(); }); </script>';

	echo '</div>';

	////////////////
	echo '</div>'; //poststuff
	echo '</div>';
	echo '</div>';
}

function du_submenu_cb() {
	global $du_remote_site;

	if ( isset( $_GET['du_use_relay'] ) && $_GET['du_use_relay'] == 1 ) {
		update_option( 'du_use_relay', 1 );
	}

	if ( isset( $_POST['du_reset_submit'] ) ) {
		delete_option( 'du_api_key' );
		delete_option( 'du_api_key_active' );
		delete_option( 'du_premium' );
		delete_option( 'du_premium_cloud' );

		wp_redirect( admin_url( 'admin.php?page=page_builder_cloud' ) );
	}

	$key           = get_option( 'du_api_key' ); //initial get
	$premium       = get_option( 'du_premium', 0 );
	$premium_cloud = get_option( 'du_premium_cloud', 0 );

	if ( isset( $_GET['du_clear_account_transient'] ) ) {
		delete_transient( 'du-account-' . $key );
		wp_redirect( remove_query_arg( 'du_clear_account_transient' ) );
	}

	if ( isset( $_GET['du_first_run'] ) ) { //located in help.php
		du_first_run_wizard();

	} else {

		//test mode
		if ( isset( $_GET['test'] ) && $_GET['test'] == 1 ) {
			$url = $du_remote_site . '?du_api_key=' . $key . '&du_domain=' . urlencode( site_url() ) . '&du_action=test';

			if ( $remote = du_call( $url ) ) {
				echo 'Method 1<br />';
				echo $url;
				echo '<pre>';
				print_r( $remote );
				echo '</pre>';
			}

			if ( $remote2 = du_call( $url, false, 2 ) ) {
				echo 'Method 2<br />';
				echo $url;
				echo '<pre>';
				print_r( $remote2 );
				echo '</pre>';
			}
		}
		//end test mode

		echo '<div class="wrap lc_wrap">
				<h2><span style="width: 30px; height: 30px; font-size: 30px;" class="dashicons dashicons-cloud"></span> ' . DU_NAME . ' - V' . DU_VERSION . '</h2>';

		///////////////////////////////////////////////////////////////
		// Action processing
		///////////////////////////////////////////////////////////////

		if ( ! defined( 'DU_API_KEY' ) && ! $key ) {
			echo '<p>Enter your details for the ' . DU_NAME . ' site. Once you have added your API key then the system will begin to function and layouts can be loaded.</p>';
		}

		if ( isset( $_POST['du_edit_wl_submit'] ) ) {
			$_POST['du_white_labelling']['saved_user'] = get_current_user_id();

			update_option( 'du_white_labelling', $_POST['du_white_labelling'] );

			echo '<div class="notice notice-success is-dismissible">
							<p>The white labelling settings have been saved. To revert back to normal please clear the white labelling fields.</p>
					</div>';
		}

		if ( isset( $_POST['du_edit_wl_delete_submit'] ) ) {
			delete_option( 'du_white_labelling' );

			echo '<div class="notice notice-success is-dismissible">
							<p>The white labelling settings have been removed.</p>
					</div>';
		}

		if ( isset( $_POST['du_edit_submit'] ) ) {
			if ( @$_POST['du_api_key'] && @$_POST['du_api_key'] != $key ) {
				delete_transient( 'du-account-' . $key );
				delete_transient( 'du-account-' . @$_POST['du_api_key'] ); //just in case there is an active transient for the new key

				update_option( 'du_api_key', @$_POST['du_api_key'] );
				$key = @$_POST['du_api_key']; //set the new key for the purposes of this page load
			}

			update_option( 'du_settings', @$_POST['du_settings'] );

			echo '<div id="message" class="updated fade">
                    <p>Settings Saved Successfully</p>
                </div>';
		}

		if ( $key ) {
			if ( $account = du_account_info( $key ) ) {
				if ( ( $premium = get_option( 'du_premium' ) ) || ( $premium_cloud = get_option( 'du_premium_cloud' ) ) ) {
					$key_active = 1;

					echo '<div class="notice notice-success is-dismissible">
								<p>Your API Key is currently Active. You can now use the ' . DU_NAME . ' interface to manage your layouts</p>
						</div>';
				} else {
					if ( $key_active = get_option( 'du_api_key_active' ) ) {
						echo '<div class="notice notice-error is-dismissible">
								<p>Your API Key is currently Active BUT you do not have a premium account and therefore the plugin will not function fully. Note tha you will still have access to the Free layouts but not Agency, Freelancer or My Cloud layouts.</p>
						</div>';
					} else if ( $account['error'] ) {
						echo '<div class="notice notice-error is-dismissible">
								<p>ERROR with your API Key: <strong>' . $account['error'] . '</strong></p>
						</div>';
					} else {
						delete_transient( 'du-account-' . $key ); //key changed, kill the transients so on the next refresh it will pull the account info from the server
					}
				}
			}
		}

		$white_label = get_option( 'du_white_labelling', array() );

		///////////////////////////////////////////////////////////////
		// END Action processing
		///////////////////////////////////////////////////////////////

		///////////////////////////////////////////////////////////////
		// Tabs Start
		///////////////////////////////////////////////////////////////

		$tabs = array(
			'home' => 'Dashboard',
		);

		if ( $premium || $premium_cloud ) {
			$tabs['settings'] = 'Settings';

			if ( du_has_permission( 'white_label' ) ) {
				$tabs['white_labelling'] = 'White Labelling';
			}

			if ( ! $white_label ) {
				if ( du_has_permission( 'edit' ) ) {
					$tabs['manage_layout_cats'] = 'Layout Categories';
				}

				if ( du_has_permission( 'snippets' ) && du_has_permission( 'edit' ) ) {
					$tabs['manage_snippet_cats'] = 'Snippet Categories';
				}

				if ( $account['is_master_key'] ) {
					$tabs['manage_keys'] = 'Manage API Keys';
				} else {
					$tabs['manage_keys'] = 'API Key';
				}
			}
		}

		$active_tab = 'home';

		if ( isset( $_GET['tab'] ) && in_array( $_GET['tab'], array_keys( $tabs ) ) && $key_active ) {
			$active_tab = $_GET['tab'];
		}

		echo '<h2 class="nav-tab-wrapper">';

		foreach ( $tabs as $tab => $label ) {
			echo '<a href="' . admin_url( 'admin.php?page=' . $_GET['page'] . '&tab=' . $tab ) . '" class="nav-tab ' . ( $active_tab == $tab ? 'nav-tab-active' : '' ) . '">' . $label . '</a>';
		}

		echo '</h2>';

		///////////////////////////////////////////////////////////////
		// Tabs END
		///////////////////////////////////////////////////////////////

		//we want to move this depending on things so keep in a variable for now
		$api_settings_form = '	<p>
									<label>
										<span style="display: inline-block; width: 100px;">API Key</span>
										<input style="padding: 6px; width: 500px;" placeholder="Enter your API Key" type="password" name="du_api_key" value="' . $key . '" />
										<br />
										<small>You can get your API Key from the ' . DU_NAME . ' website within the "my account" area.</small>	
									</label>
								</p>
								<p class="du-alt-connection-trigger">Issues connecting? ' . ( get_option( 'du_use_relay' ) ? 'Please contact support for assistance' : '<a href="' . admin_url( 'admin.php?page=' . $_GET['page'] ) . '&du_use_relay=1">Click here to use an alternate method of connecting</a>' ) . '</p>
								<p>
									<input type="submit" name="du_edit_submit" class="button-primary" value="Save Settings" />&nbsp;' . ( $key ? '<input type="submit" onclick="return confirm(\'Are you sure? This will remove your key from the site and will not function until one has been added again.\');" name="du_reset_submit" class="button-secondary" value="Delete API Key" />' : '' ) . '
								</p>';

		echo '<div id="poststuff">
					<div id="post-body" class="metabox-holder columns-2">';

		echo '<form method="POST">';
		echo '<div style="clear: both;">';

		///////////////////////////////////////////////////////////////
		// Tab Content Start
		///////////////////////////////////////////////////////////////

		if ( 1 ) { //doesn\t do anything. Just so I can easily jump to before and after the tab logic ;) #lazydev

			if ( $active_tab == 'home' ) {

				if ( ! $key || ! $key_active ) {
					echo du_box_start( $tabs[ $active_tab ] );
					echo $api_settings_form;
					echo du_box_end();
				} else {
					echo '<div class="du_settings_dashboard">';

					if ( ! $premium && ! $premium_cloud ) {
						echo '<div class="du_not_premium">Although you have entered a valid key, it is not linked to a ' . DU_NAME . ' premium account.<br />If you want access to 20 NEW layouts every month and the ability to upload your own layouts to your personal cloud<br />then visit <a href="https://pagebuildercloud.com" target="_blank">https://layoutscloud.com</a> and upgrade!</div>';
					}

					if ( 1 ) {

						echo '<div class="du_col_half">';

						if ( $summary = du_upload_summary() ) {
							$timestamp = $summary['timestamp'];

							if ( $summary = $summary['content'] ) {
								echo du_box_start( 'Your Content' );

								echo '<p>The following gives a simple summary of what content you have stored in the cloud</p>';

								echo '<div class="du_stats">';

								if ( isset( $summary['layouts']['total'] ) ) {
									$layout_total = $summary['layouts']['total'];
									echo '<div class="du_stat"><a href="' . admin_url( 'admin.php?page=du_admin_home' ) . '">' . $layout_total . '</a><br /><span>' . ( $layout_total == 1 ? 'Layout' : 'Layouts' ) . '</span><div class="du-clear">&nbsp;</div></div>';
								}

								if ( du_has_permission( 'snippets' ) && ! @$white_label['disable_snippets'] ) {
									if ( isset( $summary['snippets']['total'] ) ) {
										$snippet_total = $summary['snippets']['total'];
										echo '<div class="du_stat"><a href="' . admin_url( 'admin.php?page=du_submenu_sn' ) . '">' . $snippet_total . '</a><br /><span>' . ( $snippet_total == 1 ? 'Snippet' : 'Snippets' ) . '</span><div class="du-clear">&nbsp;</div></div>';
									}
								}

								echo '<div class="du-clear">&nbsp;</div>';
								echo '</div>';

								if ( $timestamp ) {
									echo '<p><small>Last Updated ' . $timestamp . '. Updates every 5 minutes</small></p>';
								}

								echo du_box_end();
							}
						}

						if ( du_has_permission( 'account_info' ) ) {
							echo du_box_start( 'Account Info' );

							if ( ! isset( $account['error'] ) || $account['error'] == '' ) {

								echo '<table class="form-table">';
								echo '<tr><th>Name</th><td>' . $account['name'] . '</td></tr>';

								if ( du_has_permission( 'account_info' ) ) {

									echo '<tr><th>Email</th><td>' . $account['email'] . '</td></tr>';
									echo '<tr><th>Membership</th><td>';

									if ( $account['memberships'] ) {
										foreach ( $account['memberships'] as $name => $expiry ) {
											echo '<strong>' . $name . '</strong>';

											if ( $expiry != '-' ) {
												echo '<em><small>(Expires ' . $expiry . ')</small></em>';
											}

											echo '<br />';
										}
									} else {
										echo '<p><a class="button-primary" href="https://layoutscloud.com/product/membership-upgrade/" target="_blank">View Upgrade Options</a></p>';
									}
								}

								echo '</td></tr>';
								echo '</table>';

							} else {
								echo '<p style="color: #FF9999; font-size: 20px;"><strong>It looks like there is a problem connecting to the ' . DU_NAME . ' server. Don\'t panic though!</strong></p>
									<p>If the message below mentions "SSL" then the easiest solution is to speak to your web host and pass the error below. ' . DU_NAME . ' used a very common system called cURL to communicate layouts etc. Sometimes your site will have an old version of this and it may not work.</p>
									<p>If you ask your web host to upgrade cURL to the latest stable version this will fix the issue. If it does not then please contact us to resolve things.</p>
									<p>A simple test of the system for your web host is for them to access the following URL from the server. If it is possible then ' . DU_NAME . ' will function properly: ' . $du_remote_site . '?du_api_key=' . $key . '&du_action=test</p>';
							}

							echo du_box_end();
						}

						echo '<div class="du-clear">&nbsp;</div>';
						echo '</div>';

						echo '<div class="du_col_half">';

						echo du_box_start( 'Hints &amp; Tips' );
						echo du_get_where_now();
						echo du_box_end();

						echo '<div class="du-clear">&nbsp;</div>';
						echo '</div>';

					}

					echo '<div class="du-clear">&nbsp;</div>';
					echo '</div>';
				}

				///////

			} else if ( $active_tab == 'white_labelling' ) {

				if ( du_has_permission( 'white_label' ) ) {

					/////////////////////////////////////////////////////////////////

					echo du_box_start( $tabs[ $active_tab ] );

					/////////////////////////////////////////////////////////////////


					if ( ! isset( $white_label['saved_user'] ) || ( @$white_label['saved_user'] && get_current_user_id() == $white_label['saved_user'] ) || DU_DEBUG ) {

						echo '<p>This plugin can be white labelled meaning that you can tune the name of the plugin and author information to suit your needs. Fill in the boxes below and references to the plugin throughout the site will change accordingly.</p>';

						echo '<table class="form-table">
<colgroup><col width="25%" /></colgroup>';

						echo '<tr>
                            <th>Plugin Name</th>
                            <td>';

						echo '<label>
                    <input style="padding: 6px; width: 500px;" placeholder="Divi Cloud" type="text" name="du_white_labelling[plugin_name]" value="' . @$white_label['plugin_name'] . '" />
                    </label>';

						echo '</td>
                        </tr>
                        <tr>
                            <th>Plugin URL</th>
                            <td>';

						echo '<label>
                    <input style="padding: 6px; width: 500px;" placeholder="https://www.layoutscloud.com" type="text" name="du_white_labelling[plugin_url]" value="' . @$white_label['plugin_url'] . '" />
                    </label>';

						echo '</td>
                        </tr>
                        <tr>
                            <th>Plugin Author</th>
                            <td>';

						echo '<label>
                    <input style="padding: 6px; width: 500px;" placeholder="Page Builder Cloud" type="text" name="du_white_labelling[plugin_author]" value="' . @$white_label['plugin_author'] . '" />
                    </label>';

						echo '</td>
                        </tr>
                        <tr>
                            <th>Author URL</th>
                            <td>';

						echo '<label>
                    <input style="padding: 6px; width: 500px;" placeholder="https://www.layoutscloud.com" type="text" name="du_white_labelling[plugin_author_url]" value="' . @$white_label['plugin_author_url'] . '" />
                    </label>';

						echo '</td>
                        </tr>
                        <tr>
                            <th>Plugin Description</th>
                            <td>';

						echo '<label>
                    <textarea style="padding: 6px; height: 200px; width: 500px;" name="du_white_labelling[plugin_desc]">' . @$white_label['plugin_desc'] . '</textarea>
                    </label>';

						echo '</td></tr>
                        <tr>
                            <th>Disable Divi Cloud Layouts?</th>
                            <td>';

						echo '<p><label><input type="checkbox" name="du_white_labelling[disable_dc]" ' . ( isset( $white_label['disable_dc'] ) ? 'checked="checked"' : '' ) . ' value="1" /></label></p>';

						echo '</td></tr>
                        <tr>
                            <th>"My Cloud" Subsets?</th>
                            <td>';

						if ( $layouts = du_get_my_cloud() ) {
							if ( isset( $layouts['categories'] ) ) {
								foreach ( $layouts['categories'] as $cat_name => $cat_label ) {
									echo '<p><label><input type="checkbox" name="du_white_labelling[cats][' . $cat_name . ']" ' . ( isset( $white_label['cats'][ $cat_name ] ) ? 'checked="checked"' : '' ) . ' value="' . $cat_name . '" />&nbsp;' . $cat_label . '</label></p>';
								}
							} else {
								echo '<p>When you start categorising your own cloud layouts, the categories will appear here for you to choose from.</p>';
							}
						}

						echo '<p><small>Using this feature you can make sure that the "My Cloud" section of the Divi Builder will ONLY show layouts from certain categories.</small></p>';

						echo '</td></tr>
                        <tr>
                            <th>Disable Snippets?</th>
                            <td>';

						echo '<p><label><input type="checkbox" name="du_white_labelling[disable_snippets]" ' . ( isset( $white_label['disable_snippets'] ) ? 'checked="checked"' : '' ) . ' value="1" /></label></p>';

						echo '<p><small>Using this feature will disable the snippet system entirely.</small></p>';


						echo '</td></tr>
                        <tr>
                            <th>Snippet Categories</th>
                            <td>';

						if ( $layouts = du_get_snippets() ) {
							if ( isset( $layouts['categories'] ) ) {
								foreach ( $layouts['categories'] as $cat_name => $cat_label ) {
									echo '<p><label><input type="checkbox" name="du_white_labelling[snippet_cats][' . $cat_name . ']" ' . ( isset( $white_label['snippet_cats'][ $cat_name ] ) ? 'checked="checked"' : '' ) . ' value="' . $cat_name . '" />&nbsp;' . $cat_label . '</label></p>';
								}
							} else {
								echo '<p>When you start categorising your Snippets, the categories will appear here for you to choose from. You can add categories using the Snippet Categories link above</p>';
							}
						}

						echo '<p><small>Using this feature you can make sure that this site will ONLY show snippets from certain categories. eg: license keys for specific clients etc</small></p>';

						echo '</td></tr>
                    </table>';

						echo '<p>';

						echo '<input type="submit" name="du_edit_wl_submit" class="button-primary" value="Save White labelling Settings" />';

						if ( isset( $white_label['saved_user'] ) ) {
							echo '<input type="submit" name="du_edit_wl_delete_submit" class="button-secondary" style="margin-left: 10px;" value="Delete White labelling Configuration" />';
						}

						echo '</p>';
					} else {
						if ( @$white_label['saved_user'] ) {
							if ( $saved_user = get_userdata( @$white_label['saved_user'] ) ) {
								echo '<p>This plugin has been white labelled. Only the user who set this up can edit it. Please login as ' . $saved_user->user_login . ' and revisit this page.</p>';
							} else {
								delete_option( 'du_white_labelling' ); //delete db code
								echo '<p>This plugin has been white labelled. However, it has now been reset to defaults as the user who set it up has been deleted from your site. </p>';
							}
						}
					}

					echo du_box_end();
				}
			} else if ( $active_tab == 'manage_layout_cats' ) {

				if ( du_has_permission( 'edit' ) ) {
					echo du_box_start( $tabs[ $active_tab ] );

					echo '<p>You can use the following categories to tag your layouts. Use this page to add and remove categories. Removing categories won\'t remove the layouts they are tagged to, just the category itself so there is no content lost!</p>';

					echo '<div style="clear: both;">';
					echo '<div class="du-gallery du-manage-categories du-layout-categories"><div class="du-tab"></div></div>';
					echo '<script> jQuery(document).ready(function() { du_my_categories("layout"); }); </script>';
					echo '</div>';

					echo du_box_end();
				}

			} else if ( $active_tab == 'manage_snippet_cats' ) {

				if ( du_has_permission( 'snippets' ) && du_has_permission( 'edit' ) ) {

					echo du_box_start( $tabs[ $active_tab ] );

					echo '<p>You can use the following categories to tag your layouts. Use this page to add and remove categories. Removing categories won\'t remove the layouts they are tagged to, just the category itself so there is no content lost!</p>';

					echo '<div style="clear: both;">';
					echo '<div class="du-gallery du-manage-categories du-snippet-categories"><div class="du-tab"></div></div>';
					echo '<script> jQuery(document).ready(function() { du_my_categories("snippet"); }); </script>';
					echo '</div>';

					echo du_box_end();
				}

			} else if ( $active_tab == 'manage_keys' ) {

				if ( $key ) {
					echo du_box_start( 'API Settings' );
					echo $api_settings_form;
					echo du_box_end();
				}

				if ( $account['is_master_key'] ) {
					echo du_box_start( $tabs[ $active_tab ] );

					$reset_url = admin_url( 'admin.php?page=' . $_GET['page'] . '&tab=manage_keys&du_clear_account_transient=1' );

					if ( $account['plugin_manage_keys'] ) {
						echo '<div style="clear: both;">';
						echo '<div class="du-gallery du-manage-keys"><div class="du-tab"></div></div>';
						echo '<script> jQuery(document).ready(function() { du_manage_additional_keys(); }); </script>';
						echo '</div>';
					} else {
						echo '<p>Your account can have more than one key! If you would like to be able to manage your keys from within this plugin please visit your ' . DU_NAME . ' account pages online and turn on the "In-Plugin Key Management" option. If you prefer to manage your keys online then you will find that in your account also. This is strictly an OPT IN as all sites that use the master key will show this interface which, we understand, some of you may not want!</p>';
						echo '<p>Once you have made the setting change in your account you can <a href="' . $reset_url . '">click here</a> to refresh your preferences and you should see the interface appear.</p>';
					}

					echo du_box_end();
				}

			} else if ( $active_tab == 'settings' ) {
				echo du_box_start( $tabs[ $active_tab ] );

				/////////////////////////////////

				$settings = du_get_settings();

				$post_methods = array(
					1 => 'WP Methods (Default)',
					2 => 'cURL (Alternate)'
				);

				$method_options = '<select name="du_post_method">';

				foreach ( $post_methods as $method_id => $method_label ) {
					$method_options .= '<option value="' . $method_id . '" ' . selected( $settings['post_method'], $method_id, false ) . '>' . $method_label . '</option>';
				}

				$method_options .= '</select>';

				/////////////////////////////////

				$orders = array(
					'date_desc' => 'Newest first',
					'date_asc'  => 'Oldest first',
					'az_asc'    => 'By Name (A-Z)',
					'az_desc'   => 'By Name (Z-A)',
				);

				$order_options = array();

				foreach ( $orders as $order_key => $order_val ) {
					$order_options[] = '<option value="' . $order_key . '" ' . ( @$settings['layout_order'] == $order_key ? 'selected="selected"' : '' ) . '>' . $order_val . '</option>';
				}

				/////////////////////////////////

				$views = array(
					'grid-view' => 'Grid View',
					'list-view' => 'List View',
				);

				$view_options = array();

				foreach ( $views as $view_key => $view_val ) {
					$view_options[] = '<option value="' . $view_key . '" ' . ( @$settings['cloud_default_view'] == $view_key ? 'selected="selected"' : '' ) . '>' . $view_val . '</option>';
				}

				/////////////////////////////////

				echo '<div class="du_settings_form">';
				echo '<p>
						<label>Default Layout Type</label>
		                <span>
			                <select name="du_settings[default_view]">
			                    <option value="layouts" ' . ( @$settings['default_view'] == 'layouts' ? 'selected="selected"' : '' ) . '>All Layouts</option>
			                    <option value="my-cloud" ' . ( @$settings['default_view'] == 'my-cloud' ? 'selected="selected"' : '' ) . '>My Cloud</option>
			                </select>
			            </span>
		              </p>';

				echo '<p>
						<label>My Cloud - Default View Format (List/Grid)</label>
		                <span>
			                <select name="du_settings[cloud_default_view]">
			                    ' . implode( '', $view_options ) . '
			                </select>
			                <small>The default layout for the layouts and cloud layouts. In list or grid format</small>
			            </span>
		              </p>';

				echo '<p class="du-alt-connection">
							<label>POST Method</label>
							<span>
								' . $method_options . '
								<small>Sometimes some servers have issues connecting to the PBC server. Using the "alternative" method helps to fix this. There is no downside so using it either so by all means give it a go before contacting support.</small>
							</span>
						</p>';

				echo '<p>
						<label>Layouts per page</label>
						<span>
							<input type="text" name="du_settings[per_page]" value="' . @$settings['per_page'] . '" />
							<small>The number of layouts to show per page when viewing the cloud.</small>
						</span>
						</p>';

				echo '<p>
						<label>My Cloud - Layout Order</label>
		                <span>
			                <select name="du_settings[layout_order]">
			                    ' . implode( '', $order_options ) . '
			                </select>
			                <small>The order of your cloud items. Defaults to show the newest first so you can find them more easily but those with a lot of cloud items might find it easier to sort by name for example.</small>
			            </span>
		              </p>';

				echo '<p><input type="submit" name="du_edit_submit" class="button-primary" value="Save Settings" /></p>';
				echo '</div>';

				echo du_box_end();
			} else {
				echo '<p>Unknown tab. ' . $active_tab . '</p>';
			}
		}

		///////////////////////////////////////////////////////////////
		// Tab Content END
		///////////////////////////////////////////////////////////////

		echo '</div>';
		echo '</form>';

		echo '</div>';
		echo '</div>';
		echo '</div>';
	}
}

function du_box_start( $title, $width = false, $float = 'left' ) {
	return '<div class="postbox" style="' . ( $width ? 'float: ' . $float . '; margin-bottom: 20px; width: ' . $width : 'clear: both;' ) . '">
								<h2 class="hndle">' . $title . '</h2>
								<div class="inside" style="clear: both;">';
}

function du_box_end() {
	return '    <div style="display: table; clear: both;">&nbsp;</div>
</div>
						</div>';
}

function du_admin_general_scripts() {
	$css_url = DU_STYLE_URL . 'admin-general.css';
	wp_enqueue_style( 'du_admin_general_css', $css_url, null, DU_VERSION );
}

function du_conditional_admin_scripts() {
	$pts = array(
		'et_pb_layout',
		'page',
		'project'
	);

	if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array(
			'layouts_cloud',
			'du_submenu_mc',
			'du_gallery_view',
			'du_submenu_sn',
			'du_admin_home'
		) ) || ( isset( $_GET['post_type'] ) && in_array( $_GET['post_type'], $pts ) ) ) {
		du_admin_scripts();
	}
}

function du_admin_scripts() {
	global $du_remote_site;

	$js_url        = DU_SCRIPT_URL . 'script.min.js';
	$iframe_js_url = DU_STYLE_URL . 'cbox-theme/jquery.colorbox-min.js';

	$css_url        = DU_STYLE_URL . 'admin.css';
	$iframe_css_url = DU_STYLE_URL . 'cbox-theme/colorbox.css';

	wp_enqueue_script( 'jquery' );
	wp_enqueue_script( 'du_admin_js', $js_url, null, DU_VERSION );

	$settings = du_get_settings();

	$translation_array = array(
		'plugin_name'  => DU_NAME,
		'lc_site_url'  => site_url(),
		'default_view' => DU_DEFAULT_VIEW,
		'permissions'  => get_option( 'du_permissions' ),
		'per_page'     => $settings['per_page'],
	);

	wp_localize_script( 'du_admin_js', 'du_constants', $translation_array );

	wp_enqueue_style( 'du_admin_css', $css_url, null, DU_VERSION );

	wp_enqueue_script( 'jquery' );

	wp_enqueue_script( 'du_cbox_admin_js', $iframe_js_url, null, DU_VERSION );
	wp_enqueue_style( 'du_cbox_admin_css', $iframe_css_url, null, DU_VERSION );

	//////////////////////// Syntax highlighting for the snippet system
	$hl_js_url  = DU_STYLE_URL . 'highlight-js/highlight.pack.js';
	$hl_css_url = DU_STYLE_URL . 'highlight-js/zenburn.css';

	wp_enqueue_script( 'du_hl_js', $hl_js_url, null, DU_VERSION );
	wp_enqueue_style( 'du_hl_css', $hl_css_url, null, DU_VERSION );
	////////////////////////

	$key_present = 0;
	$key         = '';

	if ( get_option( 'du_api_key' ) && get_option( 'du_api_key_active' ) ) {
		$key_present = 1;
		$key         = get_option( 'du_api_key' );
	}

	add_action( 'admin_footer', 'du_admin_footer' );

	echo '	<script>
				var du_api_key_present = ' . $key_present . ';
				var du_api_key = "' . $key . '";
				var du_site_url = "' . trailingslashit( site_url() ) . '";
				var du_ajax_spinner = "' . DU_IMAGE_URL . 'ajax-loading.gif";
				var du_remote_site_url = "' . $du_remote_site . '";
				
			</script>';
}

function du_enqueue_scripts() {
	$css_url = DU_STYLE_URL . 'style.css';

	wp_enqueue_script( 'jquery' );
	wp_enqueue_style( 'du_css', $css_url, null, DU_VERSION );
}

function du_enter_key() {
	if ( ! get_option( 'du_api_key' ) && ! isset( $_GET['du_first_run'] ) ) {
		echo '	<div class="notice notice-error">
					<p>Congratulations on activating ' . DU_NAME . '! Your development process will never be the same again. Please visit the <a href="' . admin_url( 'admin.php?page=layouts_cloud' ) . '">settings page</a> and enter your API Key to get started</p>
				</div>';
	}
}

function du_get_settings() {
	$settings = get_option( 'du_settings' );

	$defaults = array(
		'post_method'        => 1,
		'default_view'       => 'layouts',
		'per_page'           => 48,
		'layout_order'       => 'date_desc',
		'cloud_default_view' => 'grid-view'
	);

	return wp_parse_args( $settings, $defaults );
}

function du_array_span_wrap( $item ) {
	return '<span>' . $item . '</span>';
}

?>
