<?php
/**
 * WordPress Settings Framework
 *
 * @link    https://github.com/gilbitron/WordPress-Settings-Framework
 * @author  Gilbert Pellegrom, James Kemp
 * @license MIT
 */

/**
 * Define your settings
 *
 * The first parameter of this filter should be wpsf_register_settings_[options_group],
 * in this case "my_example_settings".
 *
 * Your "options_group" is the second param you use when running new WordPressSettingsFramework()
 * from your init function. It's important as it differentiates your options from others.
 *
 * To use the tabbed example, simply change the second param in the filter below to 'wpsf_tabbed_settings'
 * and check out the tabbed settings function on line 156.
 */

use KaizenCoders\MagicLink\Helper;
use KaizenCoders\MagicLink\Option;

add_filter( 'wpsf_register_settings_kc_ml', 'kc_ml_tabbed_settings' );
add_filter( 'kc_ml_settings_validate', 'kc_ml_settings_validate' );

/**
 * Settings
 *
 * @param $wpsf_settings
 *
 * @return mixed
 *
 * @since 1.0.0
 *
 */
function kc_ml_tabbed_settings( $wpsf_settings ) {
	// Tabs
	$tabs = [
		[
			'id'    => 'general',
			'title' => __( 'General', 'magic-link' ),
		],

		[
			'id'    => 'reports',
			'title' => __( 'Reports', 'magic-link' ),
		],
	];

	$general_settings = [
		[
			'id'         => 'enable_magic_link',
			'title'      => __( 'Enable Magic Link', 'magic-link' ),
			'title_desc' => __( 'Allow user to login via Magic Link', 'magic-link' ),
			'type'       => 'switch',
			'default'    => 1,
			'order'      => 1,
		],

		[
			'id'         => 'force_magic_link_login',
			'title'      => __( 'Force Magic Link Login', 'magic-link' ),
			'title_desc' => __( 'Change default login behaviour and use magic link login as default login method.', 'magic-link' ),
			'desc'       => __( 'Use magic link login by default.', 'magic-link' ),
			'type'       => 'switch',
			'default'    => 0,
			'order'      => 2,
		],

		[
			'id'         => 'link_expiry',
			'title'      => __( 'Token Lifespan', 'magic-link' ),
			'title_desc' => __( 'The TTL (time to live) of the login link. WP-Cron removes expired tokens.', 'magic-link' ),
			'desc'       => __( 'How long magic links remain valid (1-1440 minutes)', 'magic-link' ),
			'type'       => 'custom',
			'output'     => kc_ml_render_token_lifespan_field(),
			'order'      => 3,
		],

		[
			'id'         => 'token_validity',
			'title'      => __( 'Token Validity', 'magic-link' ),
			'title_desc' => __( 'Specify how many times a token can be used.', 'magic-link' ),
			'type'       => 'number',
			'default'    => 1,
			'order'      => 4,
		],

		[
			'id'         => 'show_on_login_form',
			'title'      => __( 'Show on Login Form', 'magic-link' ),
			'title_desc' => __( 'Adds magic link button to WordPress login form.', 'magic-link' ),
			'default'    => 0,
			'type'       => 'switch',
			'order'      => 5,
		],

		[
			'id'         => 'login_redirect',
			'title'      => __( 'Login Redirect', 'magic-link' ),
			'title_desc' => __( 'Redirect users to custom URL after login.', 'magic-link' ),
			'desc'       => __( 'Enter a default redirect URL for all users', 'magic-link' ),
			'type'       => 'text',
			'default'    => home_url(),
			'order'      => 10,
		],
	];

	$email_digest_settings = [
		[
			'id'         => 'email_digest_enabled',
			'title'      => __( 'Enable Email Digest', 'magic-link' ),
			'title_desc' => __( 'Automatically send a summary of magic link activity via email.', 'magic-link' ),
			'type'       => 'switch',
			'default'    => 0,
			'order'      => 1,
		],
		[
			'id'      => 'email_digest_frequency',
			'title'   => __( 'Digest Frequency', 'magic-link' ),
			'type'    => 'radio',
			'default' => 'weekly',
			'choices' => [
				'daily'   => __( 'Daily', 'magic-link' ),
				'weekly'  => __( 'Weekly', 'magic-link' ),
				'monthly' => __( 'Monthly', 'magic-link' ),
			],
			'order'   => 2,
		],
		[
			'id'      => 'email_digest_day',
			'title'   => __( 'Digest Day', 'magic-link' ),
			'desc'    => __( 'Day of the week for weekly digests, or day of the month for monthly digests. Not used for daily digests.', 'magic-link' ),
			'type'    => 'custom',
			'output'  => kc_ml_render_email_digest_day_field(),
			'order'   => 3,
		],
		[
			'id'      => 'email_digest_time',
			'title'   => __( 'Send Time', 'magic-link' ),
			'desc'    => __( 'Time of day to send the digest in your site timezone.', 'magic-link' ),
			'type'    => 'select',
			'default' => '14:00',
			'choices' => kc_ml_get_email_digest_time_choices(),
			'order'   => 4,
		],
		[
			'id'          => 'email_digest_recipients',
			'title'       => __( 'Recipients', 'magic-link' ),
			'desc'        => sprintf( __( 'Enter one email address per line. If left blank, the digest is sent to the admin email: <b>%s</b>', 'magic-link' ), get_option( 'admin_email' ) ),
			'type'        => 'textarea',
			'default'     => '',
			'placeholder' => "user@example.com\nanother@example.com",
			'order'       => 5,
		],
		[
			'id'      => 'email_digest_status',
			'title'   => __( 'Digest Status', 'magic-link' ),
			'type'    => 'custom',
			'output'  => kc_ml_render_email_digest_status_field(),
			'order'   => 6,
		],
	];

	$wpsf_settings['tabs'] = apply_filters( 'kc_ml_filter_settings_tab', $tabs );

	$general_settings      = apply_filters( 'kc_ml_filter_general_settings', $general_settings );
	$email_digest_settings = apply_filters( 'kc_ml_filter_email_digest_settings', $email_digest_settings );

	$sections = [
		[
			'tab_id'        => 'general',
			'section_id'    => 'settings',
			'section_title' => __( 'Settings', 'url-shortify' ),
			'section_order' => 1,
			'fields'        => $general_settings,
		],
		[
			'tab_id'        => 'reports',
			'section_id'    => 'email_digest',
			'section_title' => __( 'Email Digest', 'magic-link' ),
			'section_order' => 1,
			'fields'        => $email_digest_settings,
		],
	];

	$sections = apply_filters( 'kc_ml_filter_settings_sections', $sections );

	$wpsf_settings['sections'] = $sections;

	return $wpsf_settings;
}


function kc_ml_render_token_lifespan_field() {
	$settings = KC_ML()->get_settings();

	$token_lifespan      = isset( $settings['general']['settings']['token_lifespan'] ) ? $settings['general']['settings']['token_lifespan'] : 5;
	$token_lifespan_unit = isset( $settings['general']['settings']['token_lifespan_unit'] ) ? $settings['general']['settings']['token_lifespan_unit'] :
		'minutes';

	$output = '<div style="display: flex; gap: 10px; align-items: center;">';
	$output .= '<input type="number" name="kc_ml_settings[general][settings][token_lifespan]" value="' . esc_attr( $token_lifespan ) . '" min="1" style="width: 100px;" />';
	$output .= '<select name="kc_ml_settings[general][settings][token_lifespan_unit]" style="width: 150px;">';
	$output .= '<option value="minutes" ' . selected( $token_lifespan_unit, 'minutes', false ) . '>Minutes</option>';
	$output .= '<option value="hours" ' . selected( $token_lifespan_unit, 'hours', false ) . '>Hours</option>';
	$output .= '<option value="days" ' . selected( $token_lifespan_unit, 'days', false ) . '>Days</option>';
	$output .= '</select>';
	$output .= '</div>';

	return $output;
}

function kc_ml_get_email_digest_time_choices() {
	$choices = [];

	for ( $hour = 0; $hour < 24; $hour++ ) {
		foreach ( [ 0, 30 ] as $minute ) {
			$key             = sprintf( '%02d:%02d', $hour, $minute );
			$choices[ $key ] = $key;
		}
	}

	return $choices;
}

function kc_ml_render_email_digest_day_field() {
	$settings  = KC_ML()->get_settings();
	$frequency = Helper::get_data( $settings, 'reports|email_digest|email_digest_frequency', 'weekly' );
	$day       = (int) Helper::get_data( $settings, 'reports|email_digest|email_digest_day', 1 );

	$weekly_options = [
		1 => __( 'Monday', 'magic-link' ),
		2 => __( 'Tuesday', 'magic-link' ),
		3 => __( 'Wednesday', 'magic-link' ),
		4 => __( 'Thursday', 'magic-link' ),
		5 => __( 'Friday', 'magic-link' ),
		6 => __( 'Saturday', 'magic-link' ),
		7 => __( 'Sunday', 'magic-link' ),
	];

	$output = '<div id="kc-ml-digest-day-wrapper"' . ( 'daily' === $frequency ? ' style="display:none;"' : '' ) . '>';
	$output .= '<select id="kc-ml-digest-day-select" name="kc_ml_settings[reports][email_digest][email_digest_day]">';

	if ( 'monthly' === $frequency ) {
		for ( $i = 1; $i <= 28; $i++ ) {
			$output .= '<option value="' . esc_attr( $i ) . '"' . selected( $day, $i, false ) . '>' . esc_html( $i ) . '</option>';
		}
	} else {
		foreach ( $weekly_options as $value => $label ) {
			$output .= '<option value="' . esc_attr( $value ) . '"' . selected( $day, $value, false ) . '>' . esc_html( $label ) . '</option>';
		}
	}

	$output .= '</select>';
	$output .= '</div>';

	return $output;
}

function kc_ml_render_email_digest_status_field() {
	$settings       = KC_ML()->get_settings();
	$enabled        = (int) Helper::get_data( $settings, 'reports|email_digest|email_digest_enabled', 0 );
	$frequency      = Helper::get_data( $settings, 'reports|email_digest|email_digest_frequency', 'weekly' );
	$last_sent      = (int) Option::get( 'email_digest_last_sent', 0 );
	$timezone       = wp_timezone_string();
	$preview_url    = add_query_arg(
		'_wpnonce', wp_create_nonce( 'kc_ml_email_digest_preview' ),
		admin_url( 'admin-post.php?action=kc_ml_email_digest_preview' )
	);
	$test_nonce     = wp_create_nonce( 'kc_ml_email_digest_test' );
	$status_markup  = $enabled
		? '<span style="color:#047857;font-weight:600;">&#10003; ' . esc_html__( 'Active', 'magic-link' ) . '</span>'
		: '<span style="color:#6b7280;">' . esc_html__( 'Inactive', 'magic-link' ) . '</span>';
	$last_sent_text = $last_sent > 0
		? date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $last_sent )
		: __( 'Never', 'magic-link' );
	$admin_email    = get_option( 'admin_email' );
	$weekly_options = [
		1 => __( 'Monday', 'magic-link' ),
		2 => __( 'Tuesday', 'magic-link' ),
		3 => __( 'Wednesday', 'magic-link' ),
		4 => __( 'Thursday', 'magic-link' ),
		5 => __( 'Friday', 'magic-link' ),
		6 => __( 'Saturday', 'magic-link' ),
		7 => __( 'Sunday', 'magic-link' ),
	];

	ob_start();
	?>
	<div class="kc-ml-email-digest-panel">
		<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px;margin-bottom:16px;">
			<div style="padding:12px;border:1px solid #e5e7eb;border-radius:8px;background:#fafafa;">
				<div style="font-size:12px;color:#6b7280;margin-bottom:4px;"><?php esc_html_e( 'Status', 'magic-link' ); ?></div>
				<div><?php echo wp_kses( $status_markup, [ 'span' => [ 'style' => true ] ] ); ?></div>
			</div>
			<div style="padding:12px;border:1px solid #e5e7eb;border-radius:8px;background:#fafafa;">
				<div style="font-size:12px;color:#6b7280;margin-bottom:4px;"><?php esc_html_e( 'Frequency', 'magic-link' ); ?></div>
				<div><?php echo esc_html( ucfirst( $frequency ) ); ?></div>
			</div>
			<div style="padding:12px;border:1px solid #e5e7eb;border-radius:8px;background:#fafafa;">
				<div style="font-size:12px;color:#6b7280;margin-bottom:4px;"><?php esc_html_e( 'Last Sent', 'magic-link' ); ?></div>
				<div><?php echo esc_html( $last_sent_text ); ?></div>
			</div>
			<div style="padding:12px;border:1px solid #e5e7eb;border-radius:8px;background:#fafafa;">
				<div style="font-size:12px;color:#6b7280;margin-bottom:4px;"><?php esc_html_e( 'Timezone', 'magic-link' ); ?></div>
				<div><?php echo esc_html( $timezone ); ?></div>
			</div>
		</div>

		<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:12px;">
			<div style="padding:14px;border:1px solid #e5e7eb;border-radius:8px;background:#fff;">
				<strong><?php esc_html_e( 'Preview Email', 'magic-link' ); ?></strong>
				<p style="margin:8px 0 12px;color:#6b7280;font-size:13px;"><?php esc_html_e( 'Open a preview of the digest in a new tab using sample data from the last 7 days.', 'magic-link' ); ?></p>
				<button type="button" class="button button-secondary" id="kc-ml-digest-preview-btn"><?php esc_html_e( 'Preview Email', 'magic-link' ); ?></button>
			</div>
			<div style="padding:14px;border:1px solid #e5e7eb;border-radius:8px;background:#fff;">
				<strong><?php esc_html_e( 'Send Test Email', 'magic-link' ); ?></strong>
				<p style="margin:8px 0 12px;color:#6b7280;font-size:13px;"><?php esc_html_e( 'Send a test digest to verify formatting and delivery.', 'magic-link' ); ?></p>
				<div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
					<input type="email" id="kc-ml-digest-test-email" class="regular-text" value="<?php echo esc_attr( $admin_email ); ?>">
					<button type="button" class="button button-secondary" id="kc-ml-digest-test-btn"><?php esc_html_e( 'Send Test', 'magic-link' ); ?></button>
				</div>
				<div id="kc-ml-digest-test-status" style="display:none;margin-top:10px;font-size:13px;"></div>
			</div>
		</div>
	</div>
	<script>
		document.addEventListener('DOMContentLoaded', function () {
			var previewUrl = <?php echo wp_json_encode( $preview_url ); ?>;
			var ajaxUrl = <?php echo wp_json_encode( admin_url( 'admin-ajax.php' ) ); ?>;
			var ajaxNonce = <?php echo wp_json_encode( $test_nonce ); ?>;
			var weeklyOptions = <?php echo wp_json_encode( $weekly_options ); ?>;

			function renderMonthlyOptions(select) {
				var html = '';
				for (var i = 1; i <= 28; i++) {
					html += '<option value="' + i + '">' + i + '</option>';
				}
				select.innerHTML = html;
			}

			function renderWeeklyOptions(select) {
				var html = '';
				Object.keys(weeklyOptions).forEach(function (key) {
					html += '<option value="' + key + '">' + weeklyOptions[key] + '</option>';
				});
				select.innerHTML = html;
			}

			function syncDigestDayField() {
				var selectedFrequency = document.querySelector('input[name="kc_ml_settings[reports][email_digest][email_digest_frequency]"]:checked');
				var wrapper = document.getElementById('kc-ml-digest-day-wrapper');
				var select = document.getElementById('kc-ml-digest-day-select');

				if (!selectedFrequency || !wrapper || !select) {
					return;
				}

				var previousValue = select.value;
				if (selectedFrequency.value === 'daily') {
					wrapper.style.display = 'none';
					return;
				}

				wrapper.style.display = '';

				if (selectedFrequency.value === 'monthly') {
					renderMonthlyOptions(select);
					if (parseInt(previousValue, 10) >= 1 && parseInt(previousValue, 10) <= 28) {
						select.value = previousValue;
					}
				} else {
					renderWeeklyOptions(select);
					if (weeklyOptions[previousValue]) {
						select.value = previousValue;
					}
				}
			}

			document.querySelectorAll('input[name="kc_ml_settings[reports][email_digest][email_digest_frequency]"]').forEach(function (input) {
				input.addEventListener('change', syncDigestDayField);
			});
			syncDigestDayField();

			var previewBtn = document.getElementById('kc-ml-digest-preview-btn');
			if (previewBtn) {
				previewBtn.addEventListener('click', function () {
					window.open(previewUrl, '_blank');
				});
			}

			var testBtn = document.getElementById('kc-ml-digest-test-btn');
			var testEmail = document.getElementById('kc-ml-digest-test-email');
			var status = document.getElementById('kc-ml-digest-test-status');

			if (testBtn && testEmail && status) {
				testBtn.addEventListener('click', function () {
					var email = testEmail.value.trim();
					status.style.display = 'none';
					testBtn.disabled = true;

					var formData = new window.FormData();
					formData.append('action', 'kc_ml_email_digest_test');
					formData.append('nonce', ajaxNonce);
					formData.append('email', email);

					window.fetch(ajaxUrl, {
						method: 'POST',
						credentials: 'same-origin',
						body: formData
					}).then(function (response) {
						return response.json();
					}).then(function (payload) {
						status.style.display = 'block';
						status.style.color = payload.success ? '#047857' : '#b91c1c';
						status.textContent = payload.data && payload.data.message ? payload.data.message : 'Request failed.';
					}).catch(function () {
						status.style.display = 'block';
						status.style.color = '#b91c1c';
						status.textContent = 'Request failed.';
					}).finally(function () {
						testBtn.disabled = false;
					});
				});
			}
		});
	</script>
	<?php

	return ob_get_clean();
}

/**
 * Validate/ Sanitize settings.
 *
 * @param $settings
 *
 * @return void
 *
 * @since 1.7.0
 *
 */
function kc_ml_settings_validate( $settings ) {
	return $settings;
}
