<?php
/**
 * Feedback Handler
 *
 * @category   WordPress_Plugin
 * @package    Standard
 * @subpackage Handlers
 * @author     miniOrange <info@miniorange.com>
 * @license    MIT/Expat
 * @link       https://plugins.miniorange.com/woocommerce-api-product-sync-with-woocommerce-rest-apis
 */

namespace MOWCPS\Standard\Handlers\Feedback;

use MOWCPS\Common\Utils\Model_Utils;
use MOWCPS\Common\Utils\Utils;
use MOWCPS\Common\Models\Supplier_Model;
use MOWCPS\Common\Models\Attribute_Mapping_Model;
use MOWCPS\Common\Models\Connection_Model;


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

/**
 * Class Feedback_Handler
 *
 * Handles feedback form display and functionality
 */
class Feedback_Handler {

	/**
	 * Display feedback form on plugins page
	 *
	 * @return void
	 */
	public static function display_feedback_form() {
		// Only show on plugins page.
		if ( ! isset( $_SERVER['PHP_SELF'] ) || 'plugins.php' !== basename( sanitize_text_field( wp_unslash( $_SERVER['PHP_SELF'] ) ) ) ) {
			return;
		}

		self::enqueue_feedback_assets();

		// Load HTML template.
		$template_path = MOWCPS_PLUGIN_DIR . 'views/assets/templates/feedback-form.html';
		if ( ! file_exists( $template_path ) ) {
			return;
		}

		$template_content = file_get_contents( $template_path );

		// Get user email.
		$user_details = Model_Utils::get_option( 'mowcps_user_display_details', array() );
		$user_email   = $user_details['user_email'] ?? get_option( 'admin_email', '' );

		// Replace placeholders.
		$template_content = str_replace( '{{PLUGIN_URL}}', MOWCPS_PLUGIN_URL, $template_content );
		$template_content = str_replace( '{{USER_EMAIL}}', esc_attr( $user_email ), $template_content );

		// Output the HTML directly (it's our own template, so it's safe).
		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Template content is controlled by us
		echo $template_content;
	}

	/**
	 * Enqueue feedback form assets
	 *
	 * @return void
	 */
	private static function enqueue_feedback_assets() {
		wp_enqueue_style( 'wp-pointer' );
		wp_enqueue_script( 'wp-pointer' );
		wp_enqueue_script( 'utils' );

		wp_enqueue_style(
			'mowcps-feedback-form',
			MOWCPS_PLUGIN_URL . 'views/public/css/feedback-form.css',
			array(),
			MOWCPS_VERSION
		);

		wp_enqueue_script(
			'mowcps-feedback-form',
			MOWCPS_PLUGIN_URL . 'views/public/js/feedback-form.js',
			array( 'jquery' ),
			MOWCPS_VERSION,
			true
		);

		wp_localize_script(
			'mowcps-feedback-form',
			'MOWCPSFeedbackData',
			array(
				'resturl'   => rest_url( 'mowcps/v1' ),
				'restNonce' => wp_create_nonce( 'wp_rest' ),
			)
		);
	}

	/**
	 * Collect detailed user configuration
	 *
	 * @return array
	 */
	public static function collect_detailed_user_config() {
		global $wpdb, $wp_version;

		$config = array();

		$config['site_info'] = array(
			'site_url'        => get_site_url(),
			'admin_email'     => get_bloginfo( 'admin_email' ),
			'wp_version'      => $wp_version,
			'active_theme'    => wp_get_theme()->get( 'Name' ),
			'php_version'     => PHP_VERSION,
			'mysql_version'   => $wpdb->db_version(),
			'server_software' => isset( $_SERVER['SERVER_SOFTWARE'] ) ? sanitize_text_field( wp_unslash( $_SERVER['SERVER_SOFTWARE'] ) ) : 'Unknown',
		);

		$config['plugin_info'] = array(
			'plugin_version'     => Utils::get_version_number(),
			'plugin_active_time' => Model_Utils::get_option( 'mowcps_plugin_active_time', 'Unknown' ),
		);

		$config['server_info'] = array(
			'memory_limit'        => ini_get( 'memory_limit' ),
			'max_execution_time'  => ini_get( 'max_execution_time' ),
			'upload_max_filesize' => ini_get( 'upload_max_filesize' ),
			'post_max_size'       => ini_get( 'post_max_size' ),
		);

		if ( class_exists( 'WooCommerce' ) ) {
			global $woocommerce;
			$config['woocommerce_info'] = array(
				'wc_version'     => $woocommerce->version ?? 'Unknown',
				'wc_active'      => 'Yes',
				'store_currency' => get_woocommerce_currency(),
				'products_count' => wp_count_posts( 'product' )->publish,
			);
		} else {
			$config['woocommerce_info'] = array(
				'wc_active' => 'No - WooCommerce not installed',
			);
		}

		$config['plugin_settings'] = array(
			'user_details' => Model_Utils::get_option( 'mowcps_user_display_details', array() ),
			'last_sync'    => Model_Utils::get_option( 'mowcps_last_sync_time', 'Never' ),
			'sync_count'   => Model_Utils::get_option( 'mowcps_total_sync_count', 0 ),
		);

		$plugin_config = self::get_plugin_configuration();

		$config['plugin_config'] = ! empty( $plugin_config ) ? $plugin_config : 'Not configured';

		return $config;
	}

	/**
	 * Get plugin configuration
	 *
	 * @return array
	 */
	public static function get_plugin_configuration() {
		$config = array();

		try {
			// Call static methods directly on the class.
			$supplier_config = Supplier_Model::get_all();

			if ( empty( $supplier_config ) || ! isset( $supplier_config[0]['id'] ) ) {
				return $config;
			}

			$supplier_id = $supplier_config[0]['id'];

			$attribute_mappings = Attribute_Mapping_Model::get_all( array( 'supplier_id' => $supplier_id ) );
			$connection_details = Connection_Model::get_by_supplier_id( $supplier_id );

			$config['supplier']           = $supplier_config;
			$config['attribute_mappings'] = $attribute_mappings;
			$config['connections']        = $connection_details;

		} catch ( \Exception $e ) {
			// Silently fail and return empty config if there's an error.
			error_log( 'MOWCPS Feedback: Error getting plugin configuration - ' . $e->getMessage() );
		}

		return $config;
	}

	/**
	 * Prepare the professional query for the submit_contact_us API.
	 *
	 * @param array $user_config User configuration data.
	 * @return string Prepared query string.
	 */
	public static function prepare_professional_query( $user_config ) {

		global $wp_version;

		$plugin_version = Utils::get_version_number();

		$query  = '<strong>--- SYSTEM INFORMATION ---</strong><br>';
		$query .= 'WordPress Version: ' . esc_html( $wp_version ) . '<br>';
		$query .= 'Plugin Version: ' . esc_html( $plugin_version ) . '<br><br>';

		if ( ! empty( $user_config ) ) {
			if ( isset( $user_config['plugin_config'] ) ) {

				// External API Configuration.
				if ( isset( $user_config['plugin_config'] ) &&
					'Not configured' !== $user_config['plugin_config'] ) {

					$api_config        = $user_config['plugin_config'];
					$api_config_string = '';
					if ( is_array( $api_config ) ) {
						foreach ( $api_config as $key => $value ) {
							$api_config_string .= "\n{$key}:\n";
							if ( is_array( $value ) ) {
								foreach ( $value as $prop => $prop_value ) {
									if ( is_array( $prop_value ) || is_object( $prop_value ) ) {
										$api_config_string .= '  ' . $prop . ': ' . wp_json_encode( $prop_value ) . "\n";
									} else {
										$api_config_string .= '  ' . $prop . ': ' . $prop_value . "\n";
									}
								}
							} else {
								$api_config_string .= '  ' . $value . "\n";
							}
							$api_config_string .= "\n";
						}
					} else {
						$api_config_string = $api_config;
					}

					$query .= '<br><br><strong>--- PLUGIN CONFIGURATION ---</strong><br>';
					$query .= '<pre style="border:1px solid #007cba;padding:15px;background:#f8fafc;border-radius:8px;overflow-x:auto;"><code>' . htmlspecialchars( $api_config_string ) . '</code></pre>';
				}

				if ( isset( $user_config['plugin_configuration'] ) &&
					'Not configured' !== $user_config['plugin_configuration'] ) {

					$general_config       = $user_config['plugin_configuration'];
					$plugin_config_string = '';
					if ( is_array( $general_config ) ) {
						foreach ( $general_config as $key => $value ) {
							$plugin_config_string .= "\n{$key}:\n";
							if ( is_array( $value ) ) {
								foreach ( $value as $prop => $prop_value ) {
									if ( is_array( $prop_value ) || is_object( $prop_value ) ) {
										$plugin_config_string .= '  ' . $prop . ': ' . wp_json_encode( $prop_value ) . "\n";
									} else {
										$plugin_config_string .= '  ' . $prop . ': ' . $prop_value . "\n";
									}
								}
							} else {
								$plugin_config_string .= '  ' . $value . "\n";
							}
							$plugin_config_string .= "\n";
						}
					} else {
						$plugin_config_string = $general_config;
					}

					$query .= '<br><br><strong>--- PLUGIN SYNC CONFIGURATION ---</strong><br>';
					$query .= '<pre style="border:1px solid #28a745;padding:15px;background:#f8fff8;border-radius:8px;overflow-x:auto;"><code>' . htmlspecialchars( $plugin_config_string ) . '</code></pre>';
				}
			}
		}

		return $query;
	}

	/**
	 * Prepare email query
	 *
	 * @param array $form_data Form data from API request.
	 * @param array $user_config User configuration data.
	 * @return string Prepared query string.
	 */
	public static function prepare_query( $form_data, $user_config ) {
		$reason          = $form_data['reason'] ?? '';
		$comments        = $form_data['comments'] ?? '';
		$custom_feedback = $form_data['custom_feedback'] ?? '';

		$query = '';

		if ( ! empty( $custom_feedback ) ) {
			$query .= nl2br( esc_html( $custom_feedback ) ) . '<br><br>';
		}
		if ( ! empty( $comments ) ) {
			$query .= nl2br( esc_html( $comments ) ) . '<br><br>';
		}
		if ( empty( $comments ) && empty( $custom_feedback ) && ! empty( $reason ) ) {
			$query .= 'Feedback for reason: ' . esc_html( str_replace( array( '[', ']' ), '', $reason ) ) . '<br><br>';
		}

		if ( $form_data['request_contact'] ) {
			$query .= self::prepare_professional_query( $user_config );
		}

		$query .= '</div>';

		return $query;
	}
}
