<?php

namespace KaizenCoders\MagicLink\EmailDigest;

use KaizenCoders\MagicLink\Option;

class Init {
	const EMAIL_DIGEST_HOOK = 'kc_ml_email_digest';
	const ACTION_GROUP      = 'kc_magic_link';

	public function init() {
		add_action( self::EMAIL_DIGEST_HOOK, [ $this, 'process_digest' ] );
		add_action( 'init', [ $this, 'schedule_tasks' ] );
		add_action( 'admin_post_kc_ml_email_digest_preview', [ $this, 'handle_preview' ] );
		add_action( 'wp_ajax_kc_ml_email_digest_test', [ $this, 'handle_test_email_ajax' ] );
	}

	public function schedule_tasks() {
		if ( ! function_exists( 'as_next_scheduled_action' ) ) {
			return;
		}

		if ( false === as_next_scheduled_action( self::EMAIL_DIGEST_HOOK, [], self::ACTION_GROUP ) ) {
			as_schedule_recurring_action( time(), HOUR_IN_SECONDS, self::EMAIL_DIGEST_HOOK, [], self::ACTION_GROUP );
		}
	}

	public function process_digest() {
		if ( $this->can_send_now() ) {
			$this->send_digest();
		}
	}

	public function send_digest( $is_preview = false, $override_email = null ) {
		$settings  = $this->get_settings();
		$frequency = ! empty( $settings['frequency'] ) ? $settings['frequency'] : 'weekly';

		$report_generator = new ReportGenerator();
		$email_sender     = new EmailSender();

		$data = $report_generator->generate( $frequency, $is_preview );
		$email_sender->send( $data, $override_email );

		if ( ! $is_preview ) {
			Option::set( 'email_digest_last_sent', current_time( 'timestamp' ) );
		}
	}

	public function can_send_now() {
		$settings = $this->get_settings();

		if ( empty( $settings['enabled'] ) ) {
			return false;
		}

		$now       = current_time( 'timestamp' );
		$frequency = ! empty( $settings['frequency'] ) ? $settings['frequency'] : 'weekly';
		$day       = isset( $settings['day'] ) ? (int) $settings['day'] : 1;
		$time      = ! empty( $settings['time'] ) ? (string) $settings['time'] : '14:00';
		$last_sent = (int) Option::get( 'email_digest_last_sent', 0 );

		$hour   = 14;
		$minute = 0;
		if ( preg_match( '/^(\d{1,2}):(\d{2})$/', $time, $matches ) ) {
			$hour   = min( 23, max( 0, (int) $matches[1] ) );
			$minute = min( 59, max( 0, (int) $matches[2] ) );
		}

		if ( 'daily' === $frequency ) {
			$scheduled_send = mktime(
				$hour,
				$minute,
				0,
				(int) date( 'n', $now ),
				(int) date( 'j', $now ),
				(int) date( 'Y', $now )
			);

			if ( $now < $scheduled_send ) {
				return false;
			}

			return ! ( $last_sent > 0 && date( 'Ymd', $last_sent ) === date( 'Ymd', $now ) );
		}

		if ( 'monthly' === $frequency ) {
			$scheduled_day  = max( 1, min( 28, $day ) );
			$scheduled_send = mktime(
				$hour,
				$minute,
				0,
				(int) date( 'n', $now ),
				$scheduled_day,
				(int) date( 'Y', $now )
			);

			if ( $now < $scheduled_send ) {
				return false;
			}

			return ! ( $last_sent > 0 && date( 'Ym', $last_sent ) === date( 'Ym', $now ) );
		}

		$scheduled_day   = max( 1, min( 7, $day ) );
		$today_dow       = (int) date( 'N', $now );
		$monday_midnight = mktime(
			0,
			0,
			0,
			(int) date( 'n', $now ),
			(int) date( 'j', $now ) - ( $today_dow - 1 ),
			(int) date( 'Y', $now )
		);
		$scheduled_send  = $monday_midnight
			+ ( $scheduled_day - 1 ) * DAY_IN_SECONDS
			+ $hour * HOUR_IN_SECONDS
			+ $minute * MINUTE_IN_SECONDS;

		if ( $now < $scheduled_send ) {
			return false;
		}

		return ! ( $last_sent > 0 && date( 'oW', $last_sent ) === date( 'oW', $now ) );
	}

	public function handle_preview() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have permission to view this page.', 'magic-link' ) );
		}

		$nonce = isset( $_GET['_wpnonce'] ) ? sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'kc_ml_email_digest_preview' ) ) {
			wp_die( esc_html__( 'Invalid nonce.', 'magic-link' ) );
		}

		$settings  = $this->get_settings();
		$frequency = ! empty( $settings['frequency'] ) ? $settings['frequency'] : 'weekly';

		$report_generator = new ReportGenerator();
		$email_sender     = new EmailSender();

		$data = $report_generator->generate( $frequency, true );
		echo $email_sender->generate_email_html( $data ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		exit;
	}

	public function handle_test_email_ajax() {
		check_ajax_referer( 'kc_ml_email_digest_test', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => __( 'Permission denied.', 'magic-link' ) ] );
		}

		$email = sanitize_email( isset( $_POST['email'] ) ? wp_unslash( $_POST['email'] ) : '' );
		if ( empty( $email ) || ! is_email( $email ) ) {
			wp_send_json_error( [ 'message' => __( 'Please provide a valid email address.', 'magic-link' ) ] );
		}

		$this->send_digest( true, $email );

		wp_send_json_success(
			[
				/* translators: %s: email address */
				'message' => sprintf( __( 'Test email sent to %s', 'magic-link' ), $email ),
			]
		);
	}

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

		return [
			'enabled'    => (int) \KaizenCoders\MagicLink\Helper::get_data( $settings, 'reports|email_digest|email_digest_enabled', 0 ),
			'frequency'  => \KaizenCoders\MagicLink\Helper::get_data( $settings, 'reports|email_digest|email_digest_frequency', 'weekly' ),
			'day'        => (int) \KaizenCoders\MagicLink\Helper::get_data( $settings, 'reports|email_digest|email_digest_day', 1 ),
			'time'       => \KaizenCoders\MagicLink\Helper::get_data( $settings, 'reports|email_digest|email_digest_time', '14:00' ),
			'recipients' => \KaizenCoders\MagicLink\Helper::get_data( $settings, 'reports|email_digest|email_digest_recipients', '' ),
		];
	}
}
