<?php
/**
 * Admin tools page.
 *
 * @package northmill-online-shared
 *
 * @phpcs:disable Squiz.Commenting.FunctionComment.MissingParamTag
 */

namespace Northmill_Online_Shared\Modules\Admin\Pages\Page;

use JetBrains\PhpStorm\NoReturn;
use Northmill_Online_Shared\Abstract_Plugin_Shared;
use Northmill_Online_Shared\Helpers\Hook_Helpers;
use Northmill_Online_Shared\Modules\Admin\Pages\Abstract_Tabbed_Admin_Page;
use Northmill_Online_Shared\Modules\Loggers\WooCommerce_Logger;
use WC_Admin_Status;
use ZipArchive;

defined( 'ABSPATH' ) || exit;

/**
 * Class Admin_Tools
 */
class Admin_Tools extends Abstract_Tabbed_Admin_Page {
	private const ADMIN_POST_ACTION_DOWNLOAD_LOGS       = 'nms_tools_download_logs';
	private const ADMIN_POST_ACTION_DOWNLOAD_LOGS_NONCE = 'nms_tools_download_logs_nonce';
	private const AJAX_KEY_REMOVE_DATA_ON_UNINSTALL     = 'remove_plugin_data_on_uninstall';

	/**
	 * {@inheritDoc}
	 */
	protected function get_shared_tabs(): array {
		$sections = array();

		$is_plugin = $this->shared->package_info->is_plugin();

		$sections['download_logs'] = array(
			'title'   => __( 'Download logs', 'northmill-online-shared' ),
			'content' => $this->render_tab_content(
				'download-logs',
				array(
					'is_plugin'         => $is_plugin,
					'admin_post_action' => self::ADMIN_POST_ACTION_DOWNLOAD_LOGS,
					'admin_post_nonce'  => self::ADMIN_POST_ACTION_DOWNLOAD_LOGS_NONCE,
				),
			),
		);

		$show_cleaner_section = Hook_Helpers::apply_scoped_filters(
			'northmill_online_shared_tools_show_uninstall_cleaner_section',
			$is_plugin
		);

		if ( $show_cleaner_section ) {
			$sections['uninstall_cleaner'] = array(
				'title'   => __( 'Uninstall cleaner', 'northmill-online-shared' ),
				'content' => $this->render_tab_content(
					'uninstall-cleaner',
					array(
						'delete_data_on_uninstall' => Abstract_Plugin_Shared::base_plugin_instance()->uninstaller->is_uninstall_cleaner_enabled(),
						'warning_message'          => Hook_Helpers::apply_scoped_filters(
							'northmill_online_shared_uninstall_cleaner_message',
							__( 'If you uninstall the plugin with this enabled, plugin data including, but not limited to, WooCommerce meta, log files, settings are deleted. NOTE that a lot of this CANNOT be restored on a reinstall.', 'northmill-online-shared' )
						),
					),
				),
			);
		}

		return $sections;
	}


	/**
	 * {@inheritDoc}
	 */
	public function register_ajax_actions(): void {
		parent::register_ajax_actions();
		add_action( 'admin_post_' . self::ADMIN_POST_ACTION_DOWNLOAD_LOGS, array( $this, 'handle_download_logs' ) );

		$this->shared->ajax->add_action(
			self::AJAX_KEY_REMOVE_DATA_ON_UNINSTALL,
			array( $this, 'ajax_toggle_uninstall_data_deletion' )
		);
	}

	/**
	 * {@inheritDoc}
	 */
	protected function get_page_script_dependencies(): array {
		return array( 'ajax-script-shared' );
	}

	/**
	 * {@inheritDoc}
	 */
	public function get_script_localization( bool $is_shared ): array {
		$loc = parent::get_script_localization( $is_shared );

		$loc['uninstall_data_deletion_ajax'] = $this->shared->ajax->get_action( self::AJAX_KEY_REMOVE_DATA_ON_UNINSTALL )?->get_data_for_js();

		$loc['l10n']['confirm_enable_uninstall_data_deletion']  = __( 'Are you sure you want to enable data deletion?', 'northmill-online-shared' );
		$loc['l10n']['confirm_disable_uninstall_data_deletion'] = __( 'Are you sure you want to disable data deletion?', 'northmill-online-shared' );

		return $loc;
	}

	/**
	 * Ajax action to download logs.
	 *
	 * @return void
	 */
	#[NoReturn] public function handle_download_logs(): void {
		if (
			! current_user_can( 'manage_options' ) ||
			! isset( $_POST[ self::ADMIN_POST_ACTION_DOWNLOAD_LOGS_NONCE ] ) ||
			! wp_verify_nonce( $_POST[ self::ADMIN_POST_ACTION_DOWNLOAD_LOGS_NONCE ], self::ADMIN_POST_ACTION_DOWNLOAD_LOGS )
		) {
			wp_die( esc_html__( 'Unauthorized request', 'northmill-online-shared' ), 403 );
		}
		//phpcs:disable
		ini_set( 'display_errors', '0' );
		ini_set( 'display_startup_errors', '0' );
		error_reporting( 0 );
		while ( ob_get_level() ) {
			ob_end_clean();
		}
		if ( ini_get( 'zlib.output_compression' ) ) {
			ini_set( 'zlib.output_compression', 'Off' );
		}
		//phpcs:enable

		$limit_30_days = ! empty( $_POST['limit_30_days'] );
		$only_package  = ! empty( $_POST['only_package'] );

		if ( $only_package ) {
			$log_source_prefix = WooCommerce_Logger::get_source_prefix();
		} else {
			$log_source_prefix = 'northmill-';
		}

		$log_file_name_pattern = $log_source_prefix . '*.log';

		$upload  = wp_upload_dir();
		$log_dir = trailingslashit( $upload['basedir'] ) . 'wc-logs/';
		$files   = glob( $log_dir . $log_file_name_pattern );

		if ( $limit_30_days ) {
			$threshold = strtotime( '-30 days' );
			$files     = array_filter(
				$files,
				function ( $file ) use ( $threshold ) {
					return filemtime( $file ) >= $threshold;
				}
			);
		}

		if ( empty( $files ) ) {
			wp_die( esc_html__( 'No log files found for your criteria.', 'northmill-online-shared' ) );
		}

		$zip     = new ZipArchive();
		$tmp_zip = wp_tempnam();
		if ( $zip->open( $tmp_zip, ZipArchive::OVERWRITE ) !== true ) {
			wp_die( esc_html__( 'Could not create ZIP file.', 'northmill-online-shared' ) );
		}
		foreach ( $files as $file ) {
			$zip->addFile( $file, basename( $file ) );
		}

		$debug_log        = '';
		$debug_log_status = 'Not found';
		if ( defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
			if ( is_string( WP_DEBUG_LOG ) ) {
				$debug_log = WP_DEBUG_LOG;
			} else {
				$debug_log = trailingslashit( WP_CONTENT_DIR ) . 'debug.log';
			}
		}

		if ( $debug_log && file_exists( $debug_log ) ) {
			$size = filesize( $debug_log );
			if ( $size > 0 && $size < 1024 * 1024 * 1024 ) { // 1 GB
				$debug_log_status = 'Included';
				$zip->addFile( $debug_log, 'debug.log' );
			} else {
				$debug_log_status = 'Too big';
			}
		}

		// Dump system-status data into a small HTML report.
		if ( class_exists( 'WC_Admin_Status' ) ) {
			ob_start();
			WC_Admin_Status::status_report();
			$status_html = ob_get_clean();

			$status_file = sys_get_temp_dir() . '/my-plugin-system-status.html';
			file_put_contents( $status_file, $status_html ); // phpcs:ignore
			$zip->addFile( $status_file, 'system-status.html' );
		}

		// Also include a quick JSON summary of key versions and env.
		global $wpdb;
		$summary   = array(
			'WordPress Version'   => get_bloginfo( 'version' ),
			'WooCommerce Version' => defined( 'WC_VERSION' ) ? WC()->version : 'n/a',
			'PHP Version'         => phpversion(),
			'MySQL Version'       => $wpdb->db_version(),
			'Server Software'     => $_SERVER['SERVER_SOFTWARE'] ?? 'n/a',
			'Debug Log'           => $debug_log_status,
		);
		$json_file = sys_get_temp_dir() . '/my-plugin-env.json';
		file_put_contents( $json_file, wp_json_encode( $summary, JSON_PRETTY_PRINT ) ); // phpcs:ignore
		$zip->addFile( $json_file, 'environment-summary.json' );

		$zip->close();

		$zip_filename = sanitize_file_name( $log_source_prefix . 'logs-' . gmdate( 'Y-m-d' ) . '.zip' );
		header( 'Content-Type: application/zip' );
		header( 'Content-Disposition: attachment; filename="' . $zip_filename . '"' );
		header( 'Content-Length: ' . filesize( $tmp_zip ) );
		readfile( $tmp_zip ); // phpcs:ignore
		unlink( $tmp_zip ); // phpcs:ignore
		exit;
	}

	/**
	 * Ajax action to toggle uninstall data deletion.
	 */
	public function ajax_toggle_uninstall_data_deletion(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Unauthorized', 403 );
		}

		if ( ! $this->shared->package_info->is_plugin() ) {
			wp_send_json_error( 'Not a plugin', 400 );
		}

		$enabled = filter_input( INPUT_POST, 'enabled', FILTER_VALIDATE_BOOLEAN );

		if ( $enabled ) {
			$success = Abstract_Plugin_Shared::base_plugin_instance()->uninstaller->enable_uninstall_cleaner();
		} else {
			$success = Abstract_Plugin_Shared::base_plugin_instance()->uninstaller->disable_uninstall_cleaner();
		}

		if ( $success ) {
			wp_send_json_success( 'Success' );
		} else {
			wp_send_json_error( 'Failed to update option' );
		}
	}
}
