<?php
/**
 * Email Logs Module
 *
 * Logs all emails sent through WordPress for debugging and monitoring.
 *
 * @package EmailLogs
 * @since 1.0.0
 */

namespace EmailLogs;

use WP_PowerSuite\Core\Contracts\DataLocationsInterface;
use WP_PowerSuite\Core\AbstractModule;
use WP_PowerSuite\Core\NetworkScope;
use EmailLogs\Includes\EmailLogService;

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

require_once __DIR__ . '/includes/EmailLogService.php';

class Module extends AbstractModule implements DataLocationsInterface {

	private const MODULE_ID = 'email-logs';

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

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

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

	public function getDescription(): string {
		return __( 'History of WordPress-sent email with recipients, subjects, and timestamps for support and debugging.', 'wp-powersuite' );
	}

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

	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 [
			'options' => [ EmailLogService::get_option_key() ],
			'tables'  => [ 'wpps_email_logs' ],
		];
	}

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

		add_action( 'init', [ $this, 'maybeCreateTable' ], 999 );
		add_filter( 'wp_mail', [ $this, 'logEmail' ], 10, 1 );
		add_action( 'wp_mail_failed', [ $this, 'onMailFailed' ], 10, 1 );
		add_action( 'wp_mail_succeeded', [ $this, 'onMailSucceeded' ], 10, 1 );
		add_action( EmailLogService::CRON_PRUNE, [ EmailLogService::class, 'prune_logs' ] );
		EmailLogService::schedule_prune();
		EmailLogService::register_privacy_hooks();

		add_action( 'wp_ajax_wpps_email_logs_delete', [ $this, 'ajaxDelete' ] );
		add_action( 'wp_ajax_wpps_email_logs_delete_all', [ $this, 'ajaxDeleteAll' ] );

		if ( is_admin() ) {
			add_action( $this->adminMenuHook(), [ $this, 'addAdminMenu' ], 20 );
			add_action( 'admin_enqueue_scripts', [ $this, 'enqueueScripts' ] );
			add_action( 'admin_post_wpps_email_logs_save_settings', [ $this, 'handleSaveSettings' ] );
			add_action( 'admin_post_wpps_email_logs_export', [ $this, 'handleExport' ] );
		}
	}

	/** @param array{to?:mixed,subject?:string,message?:string,headers?:string|array} $args */
	public function logEmail( array $args ): array {
		return EmailLogService::log_email( $args );
	}

	public function onMailFailed( \WP_Error $error ): void {
		EmailLogService::mark_failed( $error );
	}

	public function onMailSucceeded( array $mail_data ): void {
		unset( $mail_data );
		EmailLogService::mark_sent();
	}

	public function maybeCreateTable(): void {
		EmailLogService::create_table();
	}

	public function addAdminMenu(): void {
		$this->registerPowerSuiteSubmenu(
			__( 'Email Logs', 'wp-powersuite' ),
			__( 'Email Logs', 'wp-powersuite' ),
			'powersuite-email-logs',
			[ $this, 'renderAdminPage' ]
		);
	}

	public function enqueueScripts( string $hook ): void {
		$suffix = NetworkScope::isNetworkActivated() ? 'toplevel_page_powersuite-email-logs' : 'wp-powersuite_page_powersuite-email-logs';
		if ( $hook !== $suffix && strpos( $hook, 'powersuite-email-logs' ) === false ) {
			return;
		}
		wp_enqueue_style( 'dashicons' );
		wp_enqueue_style( 'wp-powersuite-admin' );
		$base = defined( 'WP_POWERSUITE_PLUGIN_URL' ) ? WP_POWERSUITE_PLUGIN_URL : '';
		wp_enqueue_style( 'wpps-email-logs-admin', $base . 'modules/email-logs/assets/email-logs-admin.css', [ 'wp-powersuite-admin' ], '1.1.0' );
	}

	public function renderAdminPage(): void {
		if ( ! $this->canManagePlugin() ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'wp-powersuite' ) );
		}
		if ( ! $this->isLicenseActive() ) {
			?>
			<div class="wrap">
				<h1><?php esc_html_e( 'Email Logs', 'wp-powersuite' ); ?></h1>
				<div class="notice notice-warning inline" style="margin:0;">
					<p>
						<?php esc_html_e( 'Email Logs requires an active license. Activate your license to view outgoing mail history.', 'wp-powersuite' ); ?>
						<a href="<?php echo esc_url( admin_url( 'admin.php?page=powersuite-license' ) ); ?>"><?php esc_html_e( 'Activate license', 'wp-powersuite' ); ?></a>
					</p>
				</div>
			</div>
			<?php
			return;
		}
		$settings      = EmailLogService::get_settings();
		$search        = isset( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '';
		$status_filter = isset( $_GET['status'] ) ? sanitize_key( wp_unslash( $_GET['status'] ) ) : '';
		$paged         = max( 1, (int) ( $_GET['paged'] ?? 1 ) );
		$per_page      = 25;
		$result        = EmailLogService::get_logs(
			[
				'search' => $search,
				'status' => $status_filter,
				'limit'  => $per_page,
				'offset' => ( $paged - 1 ) * $per_page,
			]
		);
		$logs          = $result['items'];
		$total         = $result['total'];
		$total_pages   = (int) ceil( $total / $per_page );
		include __DIR__ . '/views/admin-page.php';
	}

	public function handleSaveSettings(): void {
		if ( ! $this->canManagePlugin() || ! check_admin_referer( 'wpps_email_logs_settings' ) ) {
			wp_die( esc_html__( 'Invalid request.', 'wp-powersuite' ) );
		}
		$limit       = isset( $_POST['limit'] ) ? max( 10, min( 200, (int) sanitize_text_field( wp_unslash( $_POST['limit'] ) ) ) ) : 100;
		$log_content = isset( $_POST['log_content'] ) ? 1 : 0;
		EmailLogService::save_settings( [ 'limit' => $limit, 'log_content' => $log_content ] );
		wp_safe_redirect(
			add_query_arg(
				[ 'page' => 'powersuite-email-logs', 'saved' => '1' ],
				NetworkScope::adminUrl( 'admin.php' )
			)
		);
		exit;
	}

	public function handleExport(): void {
		if ( ! $this->canManagePlugin() || ! check_admin_referer( 'wpps_email_logs_export' ) ) {
			wp_die( esc_html__( 'Invalid request.', 'wp-powersuite' ) );
		}

		$csv      = EmailLogService::export_csv();
		$filename = 'email-logs-' . gmdate( 'Y-m-d' ) . '.csv';

		nocache_headers();
		header( 'Content-Type: text/csv; charset=utf-8' );
		header( 'Content-Disposition: attachment; filename="' . sanitize_file_name( $filename ) . '"' );
		echo "\xEF\xBB\xBF" . $csv;
		exit;
	}

	public function ajaxDelete(): void {
		if ( ! $this->canManagePlugin() || ! check_ajax_referer( 'wpps_email_logs', 'nonce', false ) ) {
			wp_send_json_error( [ 'message' => __( 'Invalid request.', 'wp-powersuite' ) ] );
		}
		$id = isset( $_POST['id'] ) ? absint( wp_unslash( $_POST['id'] ) ) : 0;
		if ( $id && EmailLogService::delete_log( $id ) ) {
			wp_send_json_success();
		}
		wp_send_json_error( [ 'message' => __( 'Failed to delete.', 'wp-powersuite' ) ] );
	}

	public function ajaxDeleteAll(): void {
		if ( ! $this->canManagePlugin() || ! check_ajax_referer( 'wpps_email_logs', 'nonce', false ) ) {
			wp_send_json_error( [ 'message' => __( 'Invalid request.', 'wp-powersuite' ) ] );
		}
		EmailLogService::delete_all_logs();
		wp_send_json_success();
	}
}
