<?php
/**
 * Settings screen: hub connection, site key, sync status and actions.
 */

defined( 'ABSPATH' ) || exit;

$bw_hub_url    = BW_Guides_Settings::hub_url();
$bw_url_locked = defined( 'BW_GUIDES_HUB_URL' ) && BW_GUIDES_HUB_URL;
$bw_key_hint   = (string) BW_Guides_Settings::get( 'site_key_hint' );
$bw_has_key    = '' !== BW_Guides_Settings::site_key();

$bw_last_sync   = (int) BW_Guides_Settings::get( 'last_sync_at', 0 );
$bw_sync_status = (string) BW_Guides_Settings::get( 'last_sync_status' );
$bw_last_error  = (string) BW_Guides_Settings::get( 'last_error' );
$bw_counts      = BW_Guides_Settings::get( 'last_sync_counts', array() );

$bw_notices = array(
	'saved'                 => array( 'success', __( 'Settings saved.', 'bw-guides' ) ),
	'bad_url'               => array( 'error', __( 'Hub URL not saved — it must be a valid https:// URL.', 'bw-guides' ) ),
	'bad_key'               => array( 'error', __( 'That does not look like a BW Guides site key (expected bwg_…). Nothing was saved.', 'bw-guides' ) ),
	'key_saved_synced'      => array( 'success', __( 'Site key saved and guides synced successfully.', 'bw-guides' ) ),
	'key_saved_sync_failed' => array( 'error', __( 'Site key saved, but the first sync failed — see the sync status below.', 'bw-guides' ) ),
	'synced'                => array( 'success', __( 'Sync complete.', 'bw-guides' ) ),
	'sync_failed'           => array( 'error', __( 'Sync failed — see the sync status below.', 'bw-guides' ) ),
	'connection_ok'         => array( 'success', __( 'Connection OK: the hub is reachable and your site key is valid.', 'bw-guides' ) ),
	'hub_unreachable'       => array( 'error', __( 'The guides hub is not reachable from this site.', 'bw-guides' ) ),
	'hub_ok_no_key'         => array( 'warning', __( 'The hub is reachable, but no site key is configured yet.', 'bw-guides' ) ),
	'key_invalid'           => array( 'error', __( 'The hub is reachable, but your site key was rejected. Check it, or ask Bowden Works to regenerate it.', 'bw-guides' ) ),
	'key_revoked'           => array( 'error', __( 'Your site key has been revoked. Contact Bowden Works.', 'bw-guides' ) ),
);
$bw_notice  = isset( $_GET['bw_notice'] ) ? sanitize_key( wp_unslash( $_GET['bw_notice'] ) ) : '';
?>
<div class="wrap bw-guides-wrap">
	<h1><?php esc_html_e( 'Guides — Settings', 'bw-guides' ); ?></h1>

	<?php if ( isset( $bw_notices[ $bw_notice ] ) ) : ?>
		<div class="notice notice-<?php echo esc_attr( $bw_notices[ $bw_notice ][0] ); ?>"><p><?php echo esc_html( $bw_notices[ $bw_notice ][1] ); ?></p></div>
	<?php endif; ?>

	<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
		<input type="hidden" name="action" value="bw_guides_save_settings">
		<?php wp_nonce_field( 'bw_guides_save_settings' ); ?>
		<table class="form-table" role="presentation"><tbody>
			<tr>
				<th scope="row"><label for="bw-guides-hub-url"><?php esc_html_e( 'Hub URL', 'bw-guides' ); ?></label></th>
				<td>
					<?php if ( $bw_url_locked ) : ?>
						<code><?php echo esc_html( $bw_hub_url ); ?></code>
						<p class="description"><?php esc_html_e( 'Locked by the BW_GUIDES_HUB_URL constant.', 'bw-guides' ); ?></p>
					<?php else : ?>
						<input type="url" id="bw-guides-hub-url" name="hub_url" class="regular-text" value="<?php echo esc_attr( $bw_hub_url ); ?>">
						<p class="description"><?php esc_html_e( 'Leave as-is unless Bowden Works tells you otherwise.', 'bw-guides' ); ?></p>
					<?php endif; ?>
				</td>
			</tr>
			<tr>
				<th scope="row"><label for="bw-guides-site-key"><?php esc_html_e( 'Site key', 'bw-guides' ); ?></label></th>
				<td>
					<input type="password" id="bw-guides-site-key" name="site_key" class="regular-text" value="" autocomplete="off"
						placeholder="<?php echo $bw_has_key ? esc_attr( sprintf( /* translators: %s: last characters of the stored key */ __( 'Key set (ends in …%s) — enter a new key to replace', 'bw-guides' ), $bw_key_hint ) ) : esc_attr__( 'bwg_…', 'bw-guides' ); ?>">
					<p class="description"><?php esc_html_e( 'Provided by Bowden Works. Saving a key syncs your guides immediately.', 'bw-guides' ); ?></p>
					<?php if ( $bw_has_key ) : ?>
						<label><input type="checkbox" name="clear_site_key" value="1"> <?php esc_html_e( 'Disconnect this site (clear the stored key)', 'bw-guides' ); ?></label>
					<?php endif; ?>
				</td>
			</tr>
		</tbody></table>
		<?php submit_button( __( 'Save Settings', 'bw-guides' ) ); ?>
	</form>

	<hr>

	<h2><?php esc_html_e( 'Sync status', 'bw-guides' ); ?></h2>
	<table class="form-table" role="presentation"><tbody>
		<tr>
			<th scope="row"><?php esc_html_e( 'Last sync', 'bw-guides' ); ?></th>
			<td>
				<?php
				if ( $bw_last_sync ) {
					echo esc_html( date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $bw_last_sync + (int) ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ) ) );
					echo ' — ';
					if ( 'ok' === $bw_sync_status ) {
						echo '<span class="bw-guides-status-ok">' . esc_html__( 'success', 'bw-guides' ) . '</span>';
						if ( is_array( $bw_counts ) && isset( $bw_counts['remote'] ) ) {
							echo ' ' . esc_html(
								sprintf(
									/* translators: 1: total guides, 2: created, 3: updated, 4: trashed */
									__( '(%1$d guides from the hub: %2$d new, %3$d updated, %4$d removed)', 'bw-guides' ),
									(int) $bw_counts['remote'],
									(int) $bw_counts['created'],
									(int) $bw_counts['updated'],
									(int) $bw_counts['trashed']
								)
							);
						}
					} else {
						echo '<span class="bw-guides-status-error">' . esc_html__( 'failed', 'bw-guides' ) . '</span>';
						if ( $bw_last_error ) {
							echo ' — ' . esc_html( $bw_last_error );
						}
					}
				} else {
					esc_html_e( 'Never synced.', 'bw-guides' );
				}
				?>
			</td>
		</tr>
		<tr>
			<th scope="row"><?php esc_html_e( 'Automatic sync', 'bw-guides' ); ?></th>
			<td>
				<?php
				$bw_next = wp_next_scheduled( BW_Guides_Sync::CRON_HOOK );
				if ( $bw_next ) {
					/* translators: %s: human-readable time difference */
					echo esc_html( sprintf( __( 'Checked whenever the Guides section is opened (at most every 10 minutes), plus a daily backstop — next backstop in %s.', 'bw-guides' ), human_time_diff( $bw_next ) ) );
				} else {
					esc_html_e( 'Backstop not scheduled — deactivate and reactivate the plugin. Guides still update when the Guides section is opened.', 'bw-guides' );
				}
				?>
			</td>
		</tr>
	</tbody></table>

	<div class="bw-guides-actions">
		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="bw-guides-inline-form">
			<input type="hidden" name="action" value="bw_guides_sync_now">
			<?php wp_nonce_field( 'bw_guides_sync_now' ); ?>
			<?php submit_button( __( 'Sync Now', 'bw-guides' ), 'primary', 'submit', false ); ?>
		</form>
		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="bw-guides-inline-form">
			<input type="hidden" name="action" value="bw_guides_test_connection">
			<?php wp_nonce_field( 'bw_guides_test_connection' ); ?>
			<?php submit_button( __( 'Test Connection', 'bw-guides' ), 'secondary', 'submit', false ); ?>
		</form>
	</div>
</div>
