<?php
/**
 * AnyCoin Payment Gateway Admin.
 *
 * @package AnyCoin_Payment_Gateway
 */

defined( 'ABSPATH' ) || exit;
// phpcs:disable Generic.Files.OneObjectStructurePerFile.MultipleFound -- Keeping related admin classes together for cohesion.

/**
 * Admin functionality class.
 */
class AnyCoin_Admin {

	/**
	 * Constructor.
	 */
	public function __construct() {
		$this->init_hooks();
	}

	/**
	 * Initialize hooks.
	 */
	private function init_hooks() {
		// Add admin menu.
		add_action( 'admin_menu', [ $this, 'add_admin_menu' ] );
		// Enqueue admin styles.
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_admin_assets' ] );
	}

	/**
	 * Add admin menu items.
	 */
	public function add_admin_menu() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		add_management_page(
			'AnyCoin Payment Debug',
			'AnyCoin Payment Debug',
			'manage_options',
			'anycoin-payment-debug',
			[ $this, 'render_debug_page' ]
		);

		// Add transactions page.
		add_menu_page(
			'AnyCoin Transactions',
			'AnyCoin',
			'manage_woocommerce', // phpcs:ignore WordPress.WP.Capabilities.Unknown -- WooCommerce capability for shop managers/admins.
			'anycoin-transactions',
			[ $this, 'render_transactions_page' ],
			'dashicons-money-alt',
			58
		);
	}

	/**
	 * Render the admin debug page.
	 */
	public function render_debug_page() {
		// Security check.
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( 'You do not have sufficient permissions to access this page.' );
		}

		$debug_page = new AnyCoin_Admin_Debug_Page();
		$debug_page->render();
	}

	/**
	 * Render the transactions page.
	 */
	public function render_transactions_page() {
		// Security check.
		if ( ! current_user_can( 'manage_woocommerce' ) ) { // phpcs:ignore WordPress.WP.Capabilities.Unknown -- WooCommerce capability.
			wp_die( 'You do not have sufficient permissions to access this page.' );
		}

		$transactions_page = new AnyCoin_Admin_Transactions_Page();
		$transactions_page->render();
	}

	/**
	 * Enqueue admin CSS/JS for our screens.
	 *
	 * @param string $hook_suffix Admin page hook suffix.
	 */
	public function enqueue_admin_assets( $hook_suffix ) {
		if ( $hook_suffix !== 'toplevel_page_anycoin-transactions' && $hook_suffix !== 'tools_page_anycoin-payment-debug' ) {
			return;
		}
		{
			wp_enqueue_style(
				'anycoin-admin-transactions',
				ANYCOIN_PAYMENT_PLUGIN_URL . 'assets/css/admin-transactions.css',
				[],
				ANYCOIN_PAYMENT_VERSION
			);

			$inline_js = "document.addEventListener('click',function(e){var t=e.target.closest('.anycoin-confirm');if(t){var msg=t.getAttribute('data-confirm')||'Are you sure?';if(!window.confirm(msg)){e.preventDefault();}}});document.addEventListener('submit',function(e){var f=e.target.closest('.anycoin-confirm-form');if(f){var msg=f.getAttribute('data-confirm')||'Are you sure?';if(!window.confirm(msg)){e.preventDefault();}}});";
			wp_register_script( 'anycoin-admin-inline', '', [], ANYCOIN_PAYMENT_VERSION, true );
			wp_enqueue_script( 'anycoin-admin-inline' );
			wp_add_inline_script( 'anycoin-admin-inline', $inline_js );
		}
	}
}

/**
 * Debug page class.
 */
class AnyCoin_Admin_Debug_Page {

	/**
	 * Render debug page.
	 */
	public function render() {
		$nonce = isset( $_POST['anycoin_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['anycoin_nonce'] ) ) : '';
		if ( isset( $_POST['anycoin_action'] ) && $nonce && wp_verify_nonce( $nonce, 'anycoin_debug_action' ) ) {
			$action = sanitize_text_field( wp_unslash( $_POST['anycoin_action'] ) );
			$this->process_debug_action( $action );
		}

		$this->display_debug_interface();
	}

	/**
	 * Process debug actions.
	 *
	 * @param string $action Debug action key.
	 */
	private function process_debug_action( $action ) {

		switch ( $action ) {
			case 'reset_tables':
				$this->reset_tables();
				break;
			case 'manual_cleanup':
				$this->manual_cleanup();
				break;
			case 'reschedule_cron':
				$this->reschedule_cron();
				break;
			case 'test_api':
				$this->test_api();
				break;
			case 'update_order_statuses':
				$result = AnyCoin_Utilities::update_all_order_statuses();
				$this->add_admin_notice( 'Updated ' . $result . ' order statuses', 'success' );
				break;
			case 'test_monitoring':
				if ( class_exists( 'AnyCoin_Transaction_Monitor' ) ) {
					$monitor = new AnyCoin_Transaction_Monitor();
					$monitor->check_transactions();
					$this->add_admin_notice( 'Automatic monitoring test completed. Check the logs for results.', 'success' );
				} else {
					$this->add_admin_notice( 'AnyCoin_Transaction_Monitor class not found.', 'error' );
				}
				break;
		}
	}

	/**
	 * Reset database tables.
	 */
	private function reset_tables() {
		AnyCoin_Database_Migration::create_payments_table();
		AnyCoin_Database_Migration::reset_and_migrate_legacy();
		echo '<div class="notice notice-success"><p>Payment database tables have been reset and legacy data has been migrated/cleaned.</p></div>';
	}

	/**
	 * Manual cleanup of expired payments (marks as failed).
	 */
	private function manual_cleanup() {
		if ( class_exists( 'AnyCoin_Transaction_Handler' ) ) {
			$cleaned_count = AnyCoin_Transaction_Handler::cleanup_expired_payments();
			echo '<div class="notice notice-success"><p>Manual cleanup completed. Marked ' . esc_html( $cleaned_count ) . ' expired payments as failed.</p></div>';
		} else {
			echo '<div class="notice notice-error"><p>AnyCoin_Transaction_Handler class not found.</p></div>';
		}
	}

	/**
	 * Reschedule cron jobs.
	 */
	private function reschedule_cron() {
						AnyCoin_Utilities::unschedule_cron_jobs();
				AnyCoin_Utilities::schedule_cron_jobs();
		echo '<div class="notice notice-success"><p>Cron jobs have been rescheduled.</p></div>';
	}

	/**
	 * Test API connection.
	 */
	private function test_api() {
		$gateway_settings = get_option( 'woocommerce_anycoin_payment_settings', [] );
		$api              = new AnyCoin_API(
			[
				'api_url'            => $gateway_settings['api_url'] ?? '',
				'wallet_address'     => $gateway_settings['wallet_address'] ?? '',
				'view_key'           => $gateway_settings['view_key'] ?? '',
				'payment_id_api_url' => $gateway_settings['payment_id_api_url'] ?? AnyCoin_Constants::PAYMENT_VERIFICATION_API,
				'debug'              => true,
			]
		);

		$result = $api->test_connection();

		if ( is_wp_error( $result ) ) {
			echo '<div class="notice notice-error"><p>API Connection Test Failed: ' . esc_html( $result->get_error_message() ) . '</p></div>';
		} else {
			echo '<div class="notice notice-success"><p>API Connection Test Successful!</p></div>';
		}
	}

	/**
	 * Display debug interface.
	 */
	private function display_debug_interface() {
		// Count pending payments.
		$summary         = AnyCoin_Database_Manager::get_payment_status_summary();
		$pending_count   = intval( $summary['pending'] ?? 0 );
		$confirmed_count = intval( $summary['confirmed'] ?? 0 );

		// Count expired payments.
		$expired_count = AnyCoin_Database_Manager::count_expired_payments();

		?>
		<div class="wrap">
			<h1>AnyCoin Payment Gateway Debug Tools</h1>
			
			<div class="card">
				<h2>Payment Database Status</h2>
				<p>
					<strong>Pending Payments:</strong> <?php echo intval( $pending_count ); ?><br>
					<strong>Confirmed Payments:</strong> <?php echo intval( $confirmed_count ); ?><br>
					<strong>Expired Payments (>20 min):</strong> <?php echo intval( $expired_count ); ?>
				</p>
				
				<?php if ( $expired_count > 0 ) : ?>
				<form method="post">
					<?php wp_nonce_field( 'anycoin_debug_action', 'anycoin_nonce' ); ?>
					<input type="hidden" name="anycoin_action" value="manual_cleanup">
					<p class="submit">
						<input type="submit" class="button button-primary" value="Clean Up Expired Payments (<?php echo intval( $expired_count ); ?>)">
					</p>
					<p><small>This will mark all payments older than 20 minutes as "failed".</small></p>
				</form>
				<?php endif; ?>
				
				<form method="post" onsubmit="return confirm('Are you sure you want to reset the payment tables? This will delete ALL payment records!');">
					<?php wp_nonce_field( 'anycoin_debug_action', 'anycoin_nonce' ); ?>
					<input type="hidden" name="anycoin_action" value="reset_tables">
					<p class="submit">
						<input type="submit" class="button button-secondary" value="Reset Payment Database Tables">
					</p>
					<p><small>Note: This will delete all payment records and recreate the tables.</small></p>
				</form>
			</div>
			
			<div class="card">
				<h2>Cron Job Status</h2>
				<p>
					<?php
					$next_cleanup = wp_next_scheduled( 'anycoin_cleanup_expired_payments' );
					$next_check   = wp_next_scheduled( 'anycoin_monitor_payments' );

					if ( $next_cleanup ) {
						$cleanup_time = gmdate( 'Y-m-d H:i:s', $next_cleanup );
						echo '<strong>Next Cleanup:</strong> ' . esc_html( $cleanup_time ) . '<br>';
					} else {
						echo '<strong>Cleanup Cron:</strong> Not scheduled<br>';
					}

					if ( $next_check ) {
						$check_time = gmdate( 'Y-m-d H:i:s', $next_check );
						echo '<strong>Next Transaction Check:</strong> ' . esc_html( $check_time ) . '<br>';
					} else {
						echo '<strong>Transaction Check Cron:</strong> Not scheduled<br>';
					}

					// Check if WP Cron is disabled.
					if ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ) {
						echo "<strong style='color: red;'>Warning:</strong> WP Cron is disabled (DISABLE_WP_CRON = true)<br>";
					}
					?>
				</p>
				
				<form method="post">
					<?php wp_nonce_field( 'anycoin_debug_action', 'anycoin_nonce' ); ?>
					<input type="hidden" name="anycoin_action" value="reschedule_cron">
					<p class="submit">
						<input type="submit" class="button button-secondary" value="Reschedule Cron Jobs">
					</p>
				</form>
				
				<form method="post" style="margin-top: 10px;">
					<?php wp_nonce_field( 'anycoin_debug_action', 'anycoin_nonce' ); ?>
					<input type="hidden" name="anycoin_action" value="test_monitoring">
					<p class="submit">
						<input type="submit" class="button button-primary" value="Test Automatic Monitoring Now" title="Run the automatic transaction monitor manually to test if it's working">
					</p>
				</form>
			</div>
			
			<div class="card">
				<h2>API Connection Test</h2>
				<form method="post">
					<?php wp_nonce_field( 'anycoin_debug_action', 'anycoin_nonce' ); ?>
					<input type="hidden" name="anycoin_action" value="test_api">
					<p class="submit">
						<input type="submit" class="button button-primary" value="Test API Connection">
					</p>
				</form>
			</div>
			
			<div class="card">
				<h2>Debug Logs</h2>
				<p>
					<?php
					$log_files = [
						'zano-api.log'          => 'API Logs',
						'zano-transactions.log' => 'Transaction Logs',
						'zano-gateway.log'      => 'Gateway Logs',
					];

					foreach ( $log_files as $file => $title ) {
						$log_path = ANYCOIN_PAYMENT_PLUGIN_DIR . 'logs/' . $file;
						if ( file_exists( $log_path ) ) {
							$size     = size_format( filesize( $log_path ) );
							$view_url = add_query_arg(
								[
									'page'     => 'anycoin-payment-debug',
									'view_log' => $file,
									'_wpnonce' => wp_create_nonce( 'anycoin_view_log' ),
								],
								admin_url( 'tools.php' )
							);
							echo '<strong>' . esc_html( $title ) . ':</strong> ' . esc_html( $size );
							echo ' [<a href="' . esc_url( $view_url ) . '">View</a>]<br>';
						} else {
							echo '<strong>' . esc_html( $title ) . ':</strong> No log file<br>';
						}
					}
					?>
				</p>
				
				<?php
				// Display log content if requested.
				$nonce_view = isset( $_GET['_wpnonce'] ) ? sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ) : '';
				$view_param = isset( $_GET['view_log'] ) ? sanitize_file_name( wp_unslash( $_GET['view_log'] ) ) : '';
				if ( $view_param && wp_verify_nonce( $nonce_view, 'anycoin_view_log' ) && array_key_exists( $view_param, $log_files ) ) {
					$log_file = $view_param;
					$log_path = ANYCOIN_PAYMENT_PLUGIN_DIR . 'logs/' . $log_file;

					if ( file_exists( $log_path ) ) {
						global $wp_filesystem;
						if ( ! $wp_filesystem ) {
							require_once ABSPATH . 'wp-admin/includes/file.php';
							WP_Filesystem();
						}
						$log_content = ( $wp_filesystem ) ? $wp_filesystem->get_contents( $log_path ) : '';
						if ( $log_content ) {
							echo '<h3>' . esc_html( $log_files[ $log_file ] ) . '</h3>';
							echo '<div style="background:#f0f0f1; padding:10px; overflow:auto; max-height:400px; font-family:monospace;">';
							echo nl2br( esc_html( $log_content ) );
							echo '</div>';
						}
					}
				}
				?>
			</div>
		</div>
		<?php
	}
}

/**
 * Transactions page class.
 */
class AnyCoin_Admin_Transactions_Page {

	/**
	 * Render transactions page.
	 */
	public function render() {
		// Process actions.
		$this->process_actions();

		// Display transactions.
		$this->display_transactions();
	}

	/**
	 * Process page actions.
	 */
	private function process_actions() {
		// Handle order status changes.
		$nonce_tx = isset( $_GET['_wpnonce'] ) ? sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ) : '';
		if (
			isset( $_GET['action'] ) && isset( $_GET['payment_id'] ) && isset( $_GET['_wpnonce'] ) &&
			wp_verify_nonce( $nonce_tx, 'anycoin_transaction_action' )
		) {
			$payment_id = isset( $_GET['payment_id'] ) ? sanitize_text_field( wp_unslash( $_GET['payment_id'] ) ) : '';
			$action     = isset( $_GET['action'] ) ? sanitize_text_field( wp_unslash( $_GET['action'] ) ) : '';
			$this->handle_transaction_action( $payment_id, $action );
		}

		// Handle bulk update order statuses.
		$nonce_bulk = isset( $_GET['_wpnonce'] ) ? sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ) : '';
		if (
			isset( $_GET['action'] ) && $_GET['action'] === 'update-order-statuses' && isset( $_GET['_wpnonce'] ) &&
			wp_verify_nonce( $nonce_bulk, 'anycoin_update_statuses' )
		) {
			$this->handle_bulk_status_update();
		}
	}

	/**
	 * Handle individual transaction actions.
	 *
	 * @param string $payment_id Payment ID.
	 * @param string $action     Action key.
	 */
	private function handle_transaction_action( $payment_id, $action ) {

		$payment = AnyCoin_Database_Manager::get_payment_by_payment_id( $payment_id );

		if ( $payment ) {
			$order = wc_get_order( $payment['order_id'] );

			if ( $order ) {
				switch ( $action ) {
					case 'mark-paid':
						$this->mark_order_paid( $order, $payment );
						break;
					case 'cancel':
						$this->cancel_order( $order, $payment );
						break;
					case 'clear-tx-hash':
						$this->clear_transaction_hash( $order, $payment );
						break;
				}
			}
		}
	}

	/**
	 * Mark order as paid.
	 *
	 * @param WC_Order $order   Order.
	 * @param array    $payment Payment row.
	 */
	private function mark_order_paid( $order, $payment ) {
		$order->update_status( 'processing', 'Manually marked as paid by admin' );
		AnyCoin_Database_Manager::update_payment( (int) $payment['id'], [ 'status' => AnyCoin_Constants::STATUS_CONFIRMED ] );
		/* translators: %s: Order ID */
		echo '<div class="notice notice-success"><p>' . sprintf( 'Order #%s has been marked as paid.', esc_html( $payment['order_id'] ) ) . '</p></div>';
	}

	/**
	 * Cancel order.
	 *
	 * @param WC_Order $order   Order.
	 * @param array    $payment Payment row.
	 */
	private function cancel_order( $order, $payment ) {
		$order->update_status( 'cancelled', 'Manually cancelled by admin' );
		/* translators: %s: Order ID */
		echo '<div class="notice notice-info"><p>' . sprintf( 'Order #%s has been cancelled.', esc_html( $payment['order_id'] ) ) . '</p></div>';
	}

	/**
	 * Clear transaction hash.
	 *
	 * @param WC_Order $order   Order.
	 * @param array    $payment Payment row.
	 */
	private function clear_transaction_hash( $order, $payment ) {
		AnyCoin_Database_Manager::update_payment(
			(int) $payment['id'],
			[
				'tx_hash'         => null,
				'status'          => AnyCoin_Constants::STATUS_PENDING,
				'confirmations'   => 0,
				'received_amount' => null,
			]
		);
		$order->add_order_note( 'Transaction hash cleared by admin - payment marked as pending' );
		/* translators: %s: Order ID */
		echo '<div class="notice notice-warning"><p>' . sprintf( 'Transaction hash cleared for order #%s.', esc_html( $payment['order_id'] ) ) . '</p></div>';
	}

	/**
	 * Handle bulk status update.
	 */
	private function handle_bulk_status_update() {
		$last_update = get_transient( 'anycoin_last_status_update' );
		if ( $last_update && ( time() - $last_update ) < 60 ) {
			echo '<div class="notice notice-warning"><p>Please wait at least 1 minute between status updates to avoid overloading the API.</p></div>';
		} else {
			set_transient( 'anycoin_last_status_update', time(), 120 ); // 2 minutes.

			try {
				$updated_count = AnyCoin_Utilities::update_all_order_statuses();
				if ( $updated_count > 0 ) {
					/* translators: %d: Number of updated order statuses */
					echo '<div class="notice notice-success zano-update-notice"><p>' . sprintf( 'Successfully updated %d order statuses. Check the order notes for details.', esc_html( $updated_count ) ) . '</p></div>';
				} else {
					echo '<div class="notice notice-info zano-update-notice"><p>No order statuses needed updating. All payments are current.</p></div>';
				}
			} catch ( Exception $e ) {
				if ( function_exists( 'wc_get_logger' ) ) {
					wc_get_logger()->error( 'Zano status update error: ' . $e->getMessage(), [ 'source' => 'anycoin-payment-gateway' ] );
				}
				echo '<div class="notice notice-error zano-update-notice"><p>An error occurred while updating order statuses. Please check the error logs.</p></div>';
			}
		}
	}

	/**
	 * Display transactions table.
	 */
	private function display_transactions() {
		$per_page    = 20;
		$paged_param = get_query_var( 'paged' );
		if ( empty( $paged_param ) ) {
			$paged_param = filter_input( INPUT_GET, 'paged', FILTER_SANITIZE_NUMBER_INT );
		}
		$current_page = $paged_param ? max( 1, intval( $paged_param ) ) : 1;
		$base_url     = add_query_arg( [ 'page' => 'anycoin-transactions' ], admin_url( 'admin.php' ) );
		$offset       = ( $current_page - 1 ) * $per_page;

		$total_items = AnyCoin_Database_Manager::count_transactions();
		$total_pages = ceil( $total_items / $per_page );

		$transactions = AnyCoin_Database_Manager::get_transactions_paginated( $per_page, $offset );

		$duplicate_hashes = AnyCoin_Database_Manager::get_duplicate_tx_hashes();

		include ANYCOIN_PAYMENT_PLUGIN_DIR . 'includes/admin/views/transactions-table.php';
	}
}
