<?php
/**
 * Email Reports Module
 *
 * Sends scheduled digest emails with site health data: 404 errors,
 * login attempts, activity log, and email delivery stats.
 *
 * @package EmailReports
 * @since 1.0.0
 */

namespace EmailReports;

use WP_PowerSuite\Core\Contracts\DataLocationsInterface;
use WP_PowerSuite\Core\AbstractModule;
use WP_PowerSuite\Core\NetworkScope;
use EmailReports\Includes\ReportRegistry;
use EmailReports\Includes\ReportService;

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

require_once __DIR__ . '/includes/ReportRegistry.php';
require_once __DIR__ . '/includes/ReportService.php';

class Module extends AbstractModule implements DataLocationsInterface {

	private const MODULE_ID = 'email-reports';

	public function getId(): string {
		return self::MODULE_ID;
	}

	public function getName(): string {
		return __( 'Email Reports', 'wp-powersuite' );
	}

	public function getVersion(): string {
		return '1.0.3';
	}

	public function getDescription(): string {
		return __( 'Scheduled email summaries of 404s, logins, activity, and mail stats.', 'wp-powersuite' );
	}

	public function getContext(): string|array {
		return [ 'admin', 'ajax', 'cron' ];
	}

	public function getDependencies(): array {
		return [];
	}

	private function isLicenseActive(): bool {
		return function_exists( 'wp_powersuite_is_license_valid' ) && wp_powersuite_is_license_valid();
	}

	public function getDataLocations(): array {
		return [];
	}

	protected function registerHooks(): void {
		if ( ! $this->isLicenseActive() ) {
			return;
		}

		add_filter( 'cron_schedules', [ ReportService::class, 'addCronSchedules' ] );
		add_action( 'wpps_email_reports_daily', [ $this, 'runCronDaily' ] );
		add_action( 'wpps_email_reports_weekly', [ $this, 'runCronWeekly' ] );
		add_action( 'wpps_email_reports_monthly', [ $this, 'runCronMonthly' ] );
		add_action( 'wp_powersuite_module_settings_saved', [ $this, 'onSettingsSaved' ], 10, 2 );

		add_action( 'init', [ $this, 'maybeScheduleReports' ], 20 );

		add_action( 'wp_ajax_wpps_email_reports_send_test', [ $this, 'ajaxSendTest' ] );
		add_action( 'wp_ajax_wpps_email_reports_send_now', [ $this, 'ajaxSendNow' ] );

		if ( is_admin() ) {
			add_action( 'admin_enqueue_scripts', [ $this, 'enqueueModalAssets' ] );
		}
	}

	public function maybeScheduleReports(): void {
		$s = ReportService::getSettings();
		if ( empty( $s['enabled'] ) ) {
			return;
		}

		$schedule = $s['schedule'] ?? 'weekly';
		$hook     = match ( $schedule ) {
			'daily'   => 'wpps_email_reports_daily',
			'monthly' => 'wpps_email_reports_monthly',
			default   => 'wpps_email_reports_weekly',
		};

		if ( ! wp_next_scheduled( $hook ) ) {
			ReportService::scheduleReports();
		}
	}

	public function onSettingsSaved( string $module_id, array $settings ): void {
		unset( $settings );
		if ( $module_id !== self::MODULE_ID ) {
			return;
		}
		ReportService::scheduleReports();
	}

	public function runCronDaily(): void {
		$this->runCron( 'daily' );
	}

	public function runCronWeekly(): void {
		$this->runCron( 'weekly' );
	}

	public function runCronMonthly(): void {
		$this->runCron( 'monthly' );
	}

	private function runCron( string $schedule ): void {
		$s = ReportService::getSettings();
		if ( empty( $s['enabled'] ) || ( $s['schedule'] ?? '' ) !== $schedule ) {
			return;
		}
		ReportService::sendReport();
	}

	public function enqueueModalAssets( string $hook ): void {
		unset( $hook );
		$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
		if ( $page !== 'powersuite' ) {
			return;
		}
		wp_enqueue_media();
		wp_enqueue_style( 'wp-color-picker' );
		wp_enqueue_script( 'wp-color-picker' );
	}

	public function ajaxSendTest(): void {
		if ( ! NetworkScope::canManagePlugin() || ! check_ajax_referer( 'wpps_email_reports', 'nonce', false ) ) {
			wp_send_json_error( [ 'message' => __( 'Invalid request.', 'wp-powersuite' ) ] );
		}

		if ( ! $this->allowReportSend( 'test' ) ) {
			wp_send_json_error( [ 'message' => __( 'Please wait a minute before sending another test report.', 'wp-powersuite' ) ] );
		}

		if ( ReportService::sendTestReport( true ) ) {
			wp_send_json_success();
		}

		wp_send_json_error( [ 'message' => __( 'Failed to send email.', 'wp-powersuite' ) ] );
	}

	public function ajaxSendNow(): void {
		if ( ! NetworkScope::canManagePlugin() || ! check_ajax_referer( 'wpps_email_reports', 'nonce', false ) ) {
			wp_send_json_error( [ 'message' => __( 'Invalid request.', 'wp-powersuite' ) ] );
		}

		if ( ! $this->allowReportSend( 'now' ) ) {
			wp_send_json_error( [ 'message' => __( 'Please wait before sending another report.', 'wp-powersuite' ) ] );
		}

		if ( ReportService::sendReport( true ) ) {
			wp_send_json_success();
		}

		wp_send_json_error( [ 'message' => __( 'Failed to send report.', 'wp-powersuite' ) ] );
	}

	/**
	 * Per-user rate limit for manual report sends.
	 */
	private function allowReportSend( string $kind ): bool {
		$user_id = get_current_user_id();
		$key     = 'wpps_er_' . sanitize_key( $kind ) . '_' . $user_id;
		if ( get_transient( $key ) ) {
			return false;
		}
		$ttl = $kind === 'test' ? MINUTE_IN_SECONDS : 5 * MINUTE_IN_SECONDS;
		set_transient( $key, '1', $ttl );
		return true;
	}
}
