<?php
/**
 * Notification e-mail après switch core.
 *
 * @package CVS
 * @license GPL-2.0-or-later
 */

defined( 'ABSPATH' ) || exit;

class CVS_Email {

	/**
	 * @param string $from
	 * @param string $to
	 * @param int    $user_id
	 */
	public static function notify_switch( $from, $to, $user_id = 0 ) {
		$settings = CVS_Plugin::instance()->settings->all();
		if ( empty( $settings['email_on_switch'] ) ) {
			return;
		}

		$admin_email = get_option( 'admin_email' );
		if ( ! $admin_email || ! is_email( $admin_email ) ) {
			return;
		}

		$user_label = '';
		if ( $user_id ) {
			$user = get_userdata( $user_id );
			if ( $user ) {
				$user_label = $user->user_login;
			}
		}

		$site = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES );
		/* translators: %s: site name */
		$subject = sprintf( __( '[%s] WordPress core version changed', 'core-version-switcher-by-volade' ), $site );

		$lines = array(
			sprintf(
				/* translators: 1: old version, 2: new version */
				__( 'WordPress core was switched from %1$s to %2$s.', 'core-version-switcher-by-volade' ),
				$from ?: '?',
				$to
			),
			sprintf( __( 'Site: %s', 'core-version-switcher-by-volade' ), home_url() ),
		);

		if ( $user_label ) {
			$lines[] = sprintf( __( 'Triggered by user: %s', 'core-version-switcher-by-volade' ), $user_label );
		}

		$checksum = CVS_Checksums::get_last_result();
		if ( ! empty( $checksum['ok'] ) ) {
			$lines[] = __( 'Checksum spot-check: OK', 'core-version-switcher-by-volade' );
		} elseif ( ! empty( $checksum['missing'] ) ) {
			$lines[] = __( 'Checksum spot-check: mismatches detected — verify files manually.', 'core-version-switcher-by-volade' );
		}

		wp_mail( $admin_email, $subject, implode( "\n", $lines ) );
	}
}
