<?php

/**
 * Process Form data.
 */
if ( ! empty( $_POST['ems-form-crm-connect'] ) ) {
	if ( ! wp_verify_nonce( $_POST['_wpnonce'], 'ems_jetpack_crm_dashboard_form' ) ) exit;

	$crm_main_url    = isset( $_POST['ems-jetpack-crm-api-url'] )    ? sanitize_text_field( $_POST['ems-jetpack-crm-api-url'] )    : '';
	$crm_main_key    = isset( $_POST['ems-jetpack-crm-api-key'] )    ? sanitize_text_field( $_POST['ems-jetpack-crm-api-key'] )    : '';
	$crm_main_secret = isset( $_POST['ems-jetpack-crm-api-secret'] ) ? sanitize_text_field( $_POST['ems-jetpack-crm-api-secret'] ) : '';

	update_option( 'ems_jetpack_crm_main_url', $crm_main_url );
	update_option( 'ems_jetpack_crm_main_key', $crm_main_key );
	update_option( 'ems_jetpack_crm_main_secret', $crm_main_secret );
}

/**
 * Get all services.
 */
function ems_get_services() {
	$services = [];

	return apply_filters( 'ems_jetpack_crm_services', $services );
}

/**
 * Dashboard section content.
 */
add_action( 'ems_jetpack_crm_content_dashboard', function() { ?>
	<h2>Dashboard</h2>

	<?php
		$crm_main_url    = get_option( 'ems_jetpack_crm_main_url' );
		$crm_main_key    = get_option( 'ems_jetpack_crm_main_key' );
		$crm_main_secret = get_option( 'ems_jetpack_crm_main_secret' );
	?>

	<div class="content">
		<form class="ems-form" action="" method="POST">
			<div class="ems-input-group">
				<label for="ems-jetpack-crm-api-url">Jetpack CRM API Endpoint</label>
				<input
					type="text"
					name="ems-jetpack-crm-api-url"
					id="ems-jetpack-crm-api-url"
					value="<?= esc_url( $crm_main_url ) ?>"
					placeholder="https://crm-example.org/zbs_api/"
					required>
			</div>

			<div class="ems-input-group">
				<label for="ems-jetpack-crm-api-key">Jetpack CRM API Key</label>
				<input type="text"
					name="ems-jetpack-crm-api-key"
					id="ems-jetpack-crm-api-key"
					value="<?= esc_attr( $crm_main_key ) ?>"
					required>
			</div>

			<div class="ems-input-group no-margin-bottom">
				<label for="ems-jetpack-crm-api-secret">Jetpack CRM API Secret</label>
				<input
					type="text"
					name="ems-jetpack-crm-api-secret"
					id="ems-jetpack-crm-api-secret"
					value="<?= esc_attr( $crm_main_secret ) ?>"
					required>
			</div>

			<?php wp_nonce_field( 'ems_jetpack_crm_dashboard_form' ); ?>

			<input type="submit" name="ems-form-crm-connect" value="Save API Info">
		</form>

		<div class="ems-help">
			<h3>Help links:</h3>
			<p>How to access Jetpack CRM <a href="https://kb.jetpackcrm.com/knowledge-base/jetpack-crm-api-key-and-api-secrets/" target="_blank">API key and secret</a></p>
			<p>* Please make sure your website is ssl enabled.</p>
		</div>
	</div>
<?php
} );
