<?php
/**
 * Video providers settings page display.
 *
 * @package BricksExtras
 */

namespace BricksExtras;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Video providers page class.
 */
class VideoProvidersPage {

	/**
	 * Prefix for settings.
	 *
	 * @var string
	 */
	public static $prefix = '';

	/**
	 * Page title.
	 *
	 * @var string
	 */
	public static $title = '';

	/**
	 * Plugin version.
	 *
	 * @var string
	 */
	public static $version = '';

	/**
	 * Register settings
	 */
	public static function register_settings() {
		// Register Bunny Stream settings.
		register_setting(
			self::$prefix . 'video_providers',
			self::$prefix . 'bunny_library_id',
			array(
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_text_field',
				'default'           => '',
			)
		);

		register_setting(
			self::$prefix . 'video_providers',
			self::$prefix . 'bunny_api_key',
			array(
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_text_field',
				'default'           => '',
			)
		);

		register_setting(
			self::$prefix . 'video_providers',
			self::$prefix . 'bunny_token',
			array(
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_text_field',
				'default'           => '',
			)
		);
	}

	/**
	 * Save settings
	 */
	private static function save_settings() {

		// Save Bunny Stream settings.
		$library_id = Helpers::get_post_value( self::$prefix . 'bunny_library_id' );

		if ( ' ' === $library_id ) {
			// Single space means clear the setting.
			delete_option( self::$prefix . 'bunny_library_id' );
		} elseif ( ! empty( $library_id ) ) {
			// Validate library ID format - allow numbers, letters, dashes, and underscores.
			if ( ! preg_match( '/^[\w\-]+$/', $library_id ) ) {
				add_action(
					'admin_notices',
					function () {
						?>
					<div class="notice notice-error is-dismissible">
						<p><?php echo esc_html__( 'Library ID can only contain letters, numbers, dashes, and underscores.', 'bricksextras' ); ?></p>
					</div>
						<?php
					}
				);
				return;
			}

			update_option( self::$prefix . 'bunny_library_id', $library_id );
		}

		// Handle API key - update if not empty, delete if space, otherwise keep existing value.
		$api_key = Helpers::get_post_value( self::$prefix . 'bunny_api_key' );

		if ( ' ' === $api_key ) {
			delete_option( self::$prefix . 'bunny_api_key' );
		} elseif ( ! empty( $api_key ) ) {
			update_option( self::$prefix . 'bunny_api_key', $api_key );
		}

		// Handle token - update if not empty, delete if space, otherwise keep existing value.
		$token = Helpers::get_post_value( self::$prefix . 'bunny_token' );

		if ( ' ' === $token ) {
			delete_option( self::$prefix . 'bunny_token' );
		} elseif ( ! empty( $token ) ) {
			update_option( self::$prefix . 'bunny_token', $token );
		}

		// Add a success message.
		add_action(
			'admin_notices',
			function () {
				?>
			<div class="notice notice-success is-dismissible">
				<p><?php echo esc_html__( 'Settings saved successfully!', 'bricksextras' ); ?></p>
			</div>
				<?php
			}
		);
	}

	/**
	 * Mask an API key for display, showing only first and last parts
	 * and masking approximately 60% of the middle characters
	 *
	 * @param string $key The API key to mask.
	 * @return string The masked API key.
	 */
	private static function mask_api_key( $key ) {
		if ( empty( $key ) ) {
			return '';
		}

		$length = strlen( $key );

		// For very short keys (less than 6 chars), show the same number of bullets as characters.
		if ( $length < 6 ) {
			return str_repeat( '•', $length );
		}

		// For short keys (less than 8 chars), show first 2 and last 2.
		if ( $length < 8 ) {
			$first_part = substr( $key, 0, 2 );
			$last_part  = substr( $key, -2 );
			$masked     = $first_part . str_repeat( '•', $length - 4 ) . $last_part;
			return $masked;
		}

		// For longer keys, mask approximately 60% of the middle.
		$visible_percent = 0.3; // 40% visible, 60% masked.
		$visible_chars   = (int) ( $length * $visible_percent );

		// Ensure even distribution between first and last part.
		$first_chars = (int) ( $visible_chars / 2 );
		$last_chars  = $visible_chars - $first_chars;

		$first_part    = substr( $key, 0, $first_chars );
		$last_part     = substr( $key, -$last_chars );
		$masked_length = $length - $first_chars - $last_chars;

		$masked = $first_part . str_repeat( '•', $masked_length ) . $last_part;

		return $masked;
	}

	/**
	 * Display the video providers settings page.
	 *
	 * @param string $prefix Plugin prefix.
	 * @param string $title Page title.
	 * @param string $version Plugin version.
	 * @return void
	 */
	public static function init( $prefix, $title, $version ) {
		self::$prefix  = $prefix;
		self::$title   = $title;
		self::$version = $version;

		// Register settings.
		self::register_settings();

		// Handle form submission.
		if ( isset( $_POST['submit'] ) ) {
			$nonce = Helpers::get_post_value( self::$prefix . 'bunny_settings_nonce' );
			if ( wp_verify_nonce( $nonce, self::$prefix . 'save_bunny_settings' ) ) {
				self::save_settings();
			}
		}

		// Get saved values.
		$bunny_token      = get_option( self::$prefix . 'bunny_token', '' );
		$bunny_library_id = get_option( self::$prefix . 'bunny_library_id', '' );
		$bunny_api_key    = get_option( self::$prefix . 'bunny_api_key', '' );

		// Mask the sensitive values for display.
		$bunny_token_display      = self::mask_api_key( $bunny_token );
		$bunny_api_key_display    = self::mask_api_key( $bunny_api_key );
		$bunny_library_id_display = self::mask_api_key( $bunny_library_id );
		?>
		
		<h2>Bunny Stream</h2>

			<div class="form-plugin-links" style="display: flex;">
				<form method="post" action="" style="width: 100%;">
					<?php wp_nonce_field( self::$prefix . 'save_bunny_settings', self::$prefix . 'bunny_settings_nonce' ); ?>
					
					
					<table id="bricks-settings">
						<tbody>
							<tr>
								<th scope="row">
									<label><?php echo esc_html__( 'Caption Settings', 'bricksextras' ); ?></label>
									<p class="description">
										<?php
										/* translators: %s: Video provider name */
										printf( esc_html__( 'Populate captions from %s', 'bricksextras' ), 'Bunny Stream' );
										?>
									</p>
								</th>
								<td>
									<label for="<?php echo esc_attr( self::$prefix ); ?>bunny_library_id"><?php echo esc_html__( 'Video Library ID', 'bricksextras' ); ?></label>
									<div class="api-key-wrapper" style="position: relative;">
										<input type="text" id="<?php echo esc_attr( self::$prefix ); ?>bunny_library_id" 
										name="<?php echo esc_attr( self::$prefix ); ?>bunny_library_id" 
										value="" 
										placeholder="<?php echo ! empty( $bunny_library_id ) ? esc_attr( $bunny_library_id_display ) : esc_attr__( 'Enter your library ID', 'bricksextras' ); ?>" 
										class="regular-text">
									</div>
									<p class="description"><?php echo esc_html__( 'Find this in your Bunny Stream dashboard under API.', 'bricksextras' ); ?></p>
									<br>
									<p class="description"></p>
									<label for="<?php echo esc_attr( self::$prefix ); ?>bunny_api_key"><?php echo esc_html__( 'API key', 'bricks' ); ?></label>
									<div class="api-key-wrapper" style="position: relative;">
										<input type="text" id="<?php echo esc_attr( self::$prefix ); ?>bunny_api_key" 
										name="<?php echo esc_attr( self::$prefix ); ?>bunny_api_key" 
										value="" 
										placeholder="<?php echo ! empty( $bunny_api_key ) ? esc_attr( $bunny_api_key_display ) : esc_attr__( 'Enter your API key', 'bricksextras' ); ?>" 
										class="regular-text">
										<?php if ( ! empty( $bunny_api_key ) ) : ?>
										<div class="api-key-notice" style="font-size: 12px; color: #666; margin-top: 5px;">
										</div>
										<?php endif; ?>
									</div>
									<p class="description"><?php echo esc_html__( 'Find this in your Bunny Stream dashboard under API.', 'bricksextras' ); ?></p>
								</td>
							</tr>
							
							<tr>
								<th scope="row">
									<label><?php echo esc_html__( 'Security Settings', 'bricksextras' ); ?></label>
									<p class="description"><?php echo esc_html__( 'For token protected videos', 'bricksextras' ); ?></p>
								</th>
								<td>
									<label for="<?php echo esc_attr( self::$prefix ); ?>bunny_token"><?php echo esc_html__( 'CDN Token Key', 'bricksextras' ); ?></label>
									<input type="text" id="<?php echo esc_attr( self::$prefix ); ?>bunny_token" 
									name="<?php echo esc_attr( self::$prefix ); ?>bunny_token" 
									value="" 
									placeholder="<?php echo ! empty( $bunny_token ) ? esc_attr( $bunny_token_display ) : esc_attr__( 'Enter your CDN token key', 'bricksextras' ); ?>" 
									class="regular-text">
									<p class="description"><?php echo esc_html__( 'Find this in your Bunny Stream dashboard under Security settings.', 'bricksextras' ); ?></p>
								</td>
							</tr>
						</tbody>
					</table>
					
					<?php submit_button( '', $type = 'primary large' ); ?>
				</form>
			</div>
		<?php
	}
}
