<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

$credentials                   = SftcyWordformConnectGooglesheet::get_google_credentials();
$google_client_id              = isset( $credentials['clientID'] ) ? $credentials['clientID'] : '';
$google_client_secret          = isset( $credentials['clientSecret'] ) ? $credentials['clientSecret'] : '';
$google_auth_managed_available = SftcyWordformConnectGooglesheet::is_google_managed_oauth_available();
$google_calendar_auth_uri      = SftcyWordformConnectGooglecalendar::get_googlecalendar_authorization_uri();
$google_calendar_info          = SftcyWordformConnectGooglecalendar::get_googlecalendar_configured_info();
$google_calendar_id            = isset( $google_calendar_info['calendarId'] ) ? $google_calendar_info['calendarId'] : '';
$google_calendar_label         = isset( $google_calendar_info['calendarLabel'] ) ? $google_calendar_info['calendarLabel'] : '';
$google_calendar_is_authorized = ! SftcyWordformConnectGooglecalendar::is_googlecalendar_authentication_required() && ! empty( SftcyWordformConnectGooglecalendar::get_googlecalendar_token_info() );
$google_auth_redirect_url      = SftcyWordformConnectBase::get_wordform_connect_oauth_redirect_url();
$wordform_connect_is_local_env = SftcyWordformConnectBase::is_wordform_connect_local_environment();
?>
<div id="GoogleCalendarAPIModal" title="Google Calendar Configure" class="" style="display: none;">
	<div class="wordform-connect-modal-quickstart">
		<strong>Quick setup:</strong>
		<?php if ( $google_calendar_is_authorized ) : ?>
			Load calendars, select one, then save. WordForm will create events from connected form submissions.
		<?php elseif ( $google_auth_managed_available ) : ?>
			Use <strong>Connect with Google Calendar</strong>. WordForm will try to use the primary calendar automatically after authorization, and you can change it here any time.
		<?php else : ?>
			Save the shared Google OAuth credentials, authorize Google Calendar, and WordForm will try to use the primary calendar automatically. You can change the target calendar here any time.
		<?php endif; ?>
	</div>

	<h5>How to configure Google Calendar connection</h5>
	<p>
		<a href="https://developers.google.com/workspace/calendar/api/guides/create-events" target="_blank" rel="noopener">Google Calendar Event Guide</a> |
		<a href="https://developers.google.com/workspace/calendar/api/v3/reference/calendarList/list" target="_blank" rel="noopener">Google Calendar List API Docs</a> |
		<a href="https://developers.google.com/identity/protocols/oauth2/web-server" target="_blank" rel="noopener">Google OAuth Web Server Docs</a>
	</p>

	<div id="google-calendar-help" class="accordion">
		<h3>1. Connect Google Calendar</h3>
		<div>
			<p>Authorize the Google account that should own the target calendar connection for this site.</p>
			<p><strong>Important:</strong> The redirect URL saved in Google Cloud must stay exactly the same as the redirect URL shown in this WordForm modal. If you change the redirect URL in one place, update the other place before authorize or re-authorize.</p>
		</div>
		<h3>2. Load available calendars</h3>
		<div>
			<p>After Google authorization, use <strong>Verify &amp; Load Calendars</strong> to fetch the calendars available to the connected account.</p>
		</div>
		<h3>3. Save the target calendar</h3>
		<div>
			<p>Select the calendar you want WordForm to use, then click <strong>Save / Update</strong>.</p>
		</div>
		<h3>4. Connect forms</h3>
		<div>
			<p>After saving, connect only the forms you want. Google Calendar works best with forms that include a <strong>Date</strong> or <strong>Datetime</strong> field.</p>
		</div>
	</div>

	<div class="googlecalendar-connection-input-elements-wrapper" style="display: flex; flex-direction:column;">
		<div class="wordform-googlecalendar-app-feedback-msg"></div>

		<?php if ( $google_auth_managed_available ) : ?>
		<div class="wordform-managed-oauth-connect-action">
			<p>
				<strong><?php echo $google_calendar_is_authorized ? 'Google Calendar is already authorized for this site.' : 'Quick Connect is enabled for this site.'; ?></strong>
				<?php echo $google_calendar_is_authorized ? 'Reconnect only if you want to change the Google account or refresh authorization.' : 'Click the button below, sign in to Google, and approve calendar access.'; ?>
			</p>
			<p class="wordform-connect-oauth-verification-note"><i class="fa-solid fa-shield-check"></i> Google verifies the connection during sign-in and consent approval.</p>
			<button
				type="button"
				class="button button-primary wordform-start-managed-oauth-authentication-btn"
				data-auth-url="<?php echo esc_url( $google_calendar_auth_uri ); ?>"
			><i class="fa-brands fa-google"></i> <?php echo $google_calendar_is_authorized ? esc_html__( 'Reconnect Google Calendar', 'wordform-pro' ) : esc_html__( 'Connect with Google Calendar', 'wordform-pro' ); ?></button>
		</div>
		<?php else : ?>
		<div>
			<label for="googleCalendarClientId"><i class="fa-solid fa-id-badge"></i> Google Authentication Client ID<a class="wordform-field-help-link" href="https://developers.google.com/identity/protocols/oauth2/web-server" target="_blank" rel="noopener" aria-label="How to get your Google OAuth Client ID"><span class="dashicons dashicons-editor-help" aria-hidden="true"></span></a></label><br/>
			<input type="text" id="googleCalendarClientId" name="google-calendar-client-id" class="google-calendar-client-id" placeholder="Google Client ID" value="<?php echo esc_attr( $google_client_id ); ?>">
		</div>

		<div>
			<label for="googleCalendarClientSecret"><i class="fa-solid fa-key"></i> Google Authentication Client Secret<a class="wordform-field-help-link" href="https://developers.google.com/identity/protocols/oauth2/web-server" target="_blank" rel="noopener" aria-label="How to get your Google OAuth Client Secret"><span class="dashicons dashicons-editor-help" aria-hidden="true"></span></a></label><br/>
			<input type="text" id="googleCalendarClientSecret" name="google-calendar-client-secret" class="google-calendar-client-secret" placeholder="Google Client Secret" value="<?php echo esc_attr( $google_client_secret ); ?>">
		</div>

		<div>
			<label for="googleCalendarRedirectUrl"><i class="fa-solid fa-link"></i> Google Authentication Redirect URL</label><br/>
			<input type="text" id="googleCalendarRedirectUrl" name="google-calendar-redirect-url" class="google-calendar-redirect-url" value="<?php echo esc_attr( $google_auth_redirect_url ); ?>">
			<p class="wordform-connect-oauth-verification-note"><i class="fa-solid fa-circle-info"></i><span>Keep this redirect URL exactly the same in both WordForm and your Google OAuth client settings. If they do not match exactly, authorize or re-authorize will fail.</span></p>
			<?php if ( $wordform_connect_is_local_env ) : ?>
			<div class="wordform-connect-oauth-verification-note wordform-connect-oauth-verification-note-stack">
				<i class="fa-solid fa-flask"></i>
				<span class="wordform-connect-oauth-note-lines">
					<span>Localhost testing can use this exact callback.</span>
					<span>If you want a public HTTPS tunnel instead, set the constant below in your WordPress config.</span>
					<code>WORDFORM_CONNECT_OAUTH_REDIRECT_URL</code>
					<code>wp-config.php</code>
				</span>
			</div>
			<?php else : ?>
			<p class="wordform-connect-oauth-verification-note"><i class="fa-solid fa-shield-check"></i><span>WordForm uses your own site callback directly. No third-party redirect service is required.</span></p>
			<?php endif; ?>
		</div>

		<div class="wordform-connect-save-update-googlecalendar-credentials-button-div-wrapper">
			<p class="wordform-connect-oauth-verification-note"><i class="fa-solid fa-shield-check"></i><span>WordForm saves these shared Google credentials first. Google verifies them during the next authorization step.</span></p>
			<button
				class="button button-primary wordform-connect-save-update-app-fields-button"
				data-save-action="wordform_connect_save_googlecalendar_credentials_with_authentication"
				data-feedback-selector=".wordform-googlecalendar-app-feedback-msg"
				data-fields-config='[{"selector":".google-calendar-client-id","paramKey":"googleClientId","validation":"text","invalidMessage":"Please enter Google Client ID."},{"selector":".google-calendar-client-secret","paramKey":"googleClientSecret","validation":"text","invalidMessage":"Please enter Google Client Secret."},{"selector":".google-calendar-redirect-url","paramKey":"googleRedirectUrl","validation":"text","invalidMessage":"Please enter Google Redirect URL."}]'
			><i class="fa-solid fa-gear"></i> Save / Update and Continue</button>
		</div>
		<?php endif; ?>

		<div>
			<label for="GoogleCalendarId"><span class="dashicons dashicons-calendar-alt" aria-hidden="true"></span> Calendar ID<a class="wordform-field-help-link" href="https://developers.google.com/workspace/calendar/api/v3/reference/calendarList/list" target="_blank" rel="noopener" aria-label="How to find or verify your Google Calendar ID"><span class="dashicons dashicons-editor-help" aria-hidden="true"></span></a></label><br/>
			<input type="text" id="GoogleCalendarId" name="google-calendar-id" class="google-calendar-id" value="<?php echo esc_attr( $google_calendar_id ); ?>" placeholder="primary">
			<input type="hidden" id="GoogleCalendarLabel" class="google-calendar-label" value="<?php echo esc_attr( $google_calendar_label ); ?>">
		</div>

		<div class="wordform-connect-resource-actions">
			<button
				type="button"
				class="button button-secondary wordform-connect-fetch-app-resource-button"
				data-fetch-action="wordform_connect_fetch_googlecalendar_calendars"
				data-feedback-selector=".wordform-googlecalendar-app-feedback-msg"
				data-fields-config='[]'
				data-target-select="#GoogleCalendarSelect"
				data-target-input="#GoogleCalendarId"
				data-target-label-input="#GoogleCalendarLabel"
				data-empty-label="Select Calendar"
			><i class="fa-solid fa-rotate"></i> Verify & Load Calendars</button>
		</div>

		<div class="wordform-connect-resource-select-wrap">
			<label for="GoogleCalendarSelect"><span class="dashicons dashicons-calendar-alt" aria-hidden="true"></span> Loaded Calendars<a class="wordform-field-help-link" href="https://developers.google.com/workspace/calendar/api/v3/reference/calendarList/list" target="_blank" rel="noopener" aria-label="Google Calendar list documentation"><span class="dashicons dashicons-editor-help" aria-hidden="true"></span></a></label><br/>
			<select id="GoogleCalendarSelect" class="wordform-connect-resource-select">
				<option value=""><?php esc_html_e( 'Select Calendar', 'wordform-pro' ); ?></option>
				<?php if ( ! empty( $google_calendar_id ) ) : ?>
					<option value="<?php echo esc_attr( $google_calendar_id ); ?>" selected><?php echo esc_html( ! empty( $google_calendar_label ) ? $google_calendar_label : $google_calendar_id ); ?></option>
				<?php endif; ?>
			</select>
		</div>

		<div class="wordform-connect-save-update-googlecalendar-info-button-div-wrapper">
			<button
				class="button button-primary wordform-connect-save-update-app-fields-button"
				data-save-action="wordform_connect_save_googlecalendar_data_as_wp_option_data"
				data-feedback-selector=".wordform-googlecalendar-app-feedback-msg"
				data-fields-config='[{"selector":".google-calendar-id","paramKey":"googleCalendarId","validation":"text","invalidMessage":"Please enter or select Google Calendar ID."},{"selector":".google-calendar-label","paramKey":"googleCalendarLabel","validation":"optional"}]'
			><i class="fa-solid fa-gear"></i> Save / Update</button>
		</div>
	</div>
</div>
