<?php
	/**
	 * Plugin Name: Theme Subscribers
	 * Description: Native subscribers system via wp_options + AJAX + admin page.
	 * Version: 1.0
	 */

	if ( ! defined( 'ABSPATH' ) ) {
		exit;
	}

	/**
	 * Option key.
	 */
	define( 'THEME_SUBSCRIBERS_OPTION', 'theme_subscribers_list' );

	/**
	 * Get subscribers list.
	 *
	 * @return array
	 */
	function theme_get_subscribers() {

		$list = get_option( THEME_SUBSCRIBERS_OPTION, [] );

		return is_array( $list ) ? $list : [];
	}

	/**
	 * Save subscribers list.
	 *
	 * @param array $list Emails.
	 *
	 * @return void
	 */
	function theme_save_subscribers( $list ) {

		update_option(
			THEME_SUBSCRIBERS_OPTION,
			array_values( array_unique( $list ) ),
			false
		);
	}

	/**
	 * Add subscriber.
	 *
	 * @param string $email Email.
	 *
	 * @return array
	 */
	function theme_add_subscriber( $email ) {

		$email = sanitize_email( $email );

		if ( ! is_email( $email ) ) {
			return [
				'success' => false,
				'message' => 'Invalid email address.',
			];
		}

		$list = theme_get_subscribers();

		if ( in_array( $email, $list, true ) ) {
			return [
				'success' => false,
				'message' => 'You are already subscribed.',
			];
		}

		$list[] = $email;

		theme_save_subscribers( $list );

		return [
			'success' => true,
			'message' => 'Subscription successful.',
		];
	}

	/**
	 * AJAX subscribe.
	 */
	add_action( 'wp_ajax_nopriv_subscribe', 'theme_ajax_subscribe' );
	add_action( 'wp_ajax_subscribe', 'theme_ajax_subscribe' );

	function theme_ajax_subscribe() {

		check_ajax_referer( 'subscribe_nonce', 'nonce' );

		$email = isset( $_POST['email'] )
			? sanitize_email( wp_unslash( $_POST['email'] ) )
			: '';

		$result = theme_add_subscriber( $email );

		if ( $result['success'] ) {
			wp_send_json_success(
				[
					'message' => $result['message'],
				]
			);
		}

		wp_send_json_error(
			[
				'message' => $result['message'],
			],
			400
		);
	}

	/**
	 * Localize AJAX data.
	 */
	add_action(
		'wp_enqueue_scripts',
		function () {

			wp_register_script(
				'subscribe',
				false,
				[],
				null,
				true
			);

			wp_enqueue_script( 'subscribe' );

			wp_localize_script(
				'subscribe',
				'subscribeData',
				[
					'ajaxUrl' => admin_url( 'admin-ajax.php' ),
					'nonce'   => wp_create_nonce( 'subscribe_nonce' ),
				]
			);
		}
	);

	/**
	 * Admin menu.
	 */
	add_action(
		'admin_menu',
		function () {

			add_menu_page(
				'Subscribers',
				'Subscribers',
				'manage_options',
				'subscribers',
				'theme_render_admin_page',
				'dashicons-email',
				30
			);
		}
	);

	/**
	 * Delete subscriber.
	 */
	add_action(
		'admin_init',
		function () {

			if (
				! is_admin() ||
				! current_user_can( 'manage_options' )
			) {
				return;
			}

			if (
				! isset( $_GET['page'], $_GET['delete'], $_GET['_wpnonce'] ) ||
				'subscribers' !== $_GET['page']
			) {
				return;
			}

			if (
				! wp_verify_nonce(
					sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ),
					'delete_subscriber'
				)
			) {
				return;
			}

			$email = sanitize_email( wp_unslash( $_GET['delete'] ) );

			$list = array_filter(
				theme_get_subscribers(),
				function ( $item ) use ( $email ) {
					return $item !== $email;
				}
			);

			theme_save_subscribers( $list );

			wp_safe_redirect(
				admin_url( 'admin.php?page=subscribers' )
			);

			exit;
		}
	);

	/**
	 * Admin page.
	 */
	function theme_render_admin_page() {

		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$list = theme_get_subscribers();
		?>
		<div class="wrap">
			<h1>Subscribers</h1>
			<p>
				Total:
				<strong><?php echo esc_html( count( $list ) ); ?></strong>
			</p>
			<table class="widefat striped">
				<thead>
				<tr>
					<th style="width:60px;">#</th>
					<th>Email</th>
					<th style="width:120px;">Action</th>
				</tr>
				</thead>
				<tbody>
				<?php if ( $list ) : ?>
					<?php foreach ( $list as $key => $email ) : ?>
						<tr>
							<td>
								<?php echo esc_html( $key + 1 ); ?>
							</td>
							<td>
								<?php echo esc_html( $email ); ?>
							</td>
							<td>
								<a
									href="<?php echo esc_url(
										wp_nonce_url(
											admin_url(
												'admin.php?page=subscribers&delete=' . rawurlencode( $email )
											),
											'delete_subscriber'
										)
									); ?>"
									onclick="return confirm('Delete subscriber?');"
								>
									Delete
								</a>
							</td>
						</tr>
					<?php endforeach; ?>
				<?php else : ?>
					<tr>
						<td colspan="3">
							No subscribers found.
						</td>
					</tr>
				<?php endif; ?>
				</tbody>
			</table>
		</div>
		<?php
	}