<?php
if ( ! defined( 'ABSPATH' ) ) {
	die( 'You are not allowed to call this page directly.' );
}

/**
 * Class FormShieldSettings
 */
class FormShieldSettings {

	public function __construct( $is_partner = false ) {
		$this->_hooks( $is_partner );
	}

	/**А
	 * Central nonce check for settings posts
	 */
	private static function verify_settings_nonce_or_bail() : void {
		$field  = 'formshield_settings_nonce';
		$action = 'formshield_settings';
		if (
			empty( $_POST[ $field ] ) ||
			! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST[ $field ] ) ), $action )
		) {
			wp_die( esc_html__( 'Invalid request.', 'formshield' ) );
		}
	}

	/**
	 * Add hooks and filters
	 */
	public function _hooks( $is_partner = false ) {
		// Process settings changes
		add_action( 'admin_init', array( __CLASS__, 'process_save_settings' ) );

		// Temporarily disable the premium license check. This only really checks for expired licenses
		// since license activations are handled in the license key saving function
		// add_action( 'admin_init', array( __CLASS__, 'premium_license_check' ) );

		add_action( 'admin_init', array( __CLASS__, 'display_community_upgrade_banner' ) );
		add_action( 'formshield_upgrade', array( __CLASS__, 'reenable_community_upgrade_banner') );
		add_action( 'admin_init', array( __CLASS__, 'download_debug_report' ) );

		// Add AJAX handlers
		add_action( 'wp_ajax_formshield_form_enabled_change', array( __CLASS__, 'form_enabled_change' ) );
		add_action( 'wp_ajax_formsh_scan_forms', array( __CLASS__, 'scan_forms' ) );
		// add_action( 'wp_ajax_formsh_rescan_forms', array( __CLASS__, 'rescan_forms' ) ); // Moved to formshield.php
		add_action( 'wp_ajax_formshield_check_form_status', array( __CLASS__, 'check_form_status' ) );

	}

	/**
	 * Process settings changes
	 */
	public static function process_save_settings() {
		// Process community upgrade banner form
		if ( isset( $_GET['action'] ) && 'formshield_community_join' == sanitize_text_field(wp_unslash($_GET['action'])) ) {
			$hidden_field = isset( $_POST['formshield_community_upgrade_submitted'] ) ? sanitize_text_field(wp_unslash($_POST['formshield_community_upgrade_submitted'])) : '';

			if ( ! empty( $hidden_field ) && check_admin_referer( 'formshield_community_join', 'formshield_nonce' ) ) {
				$options = array(
					'email' => isset($_REQUEST['formshield_community_upgrade_email']) ? sanitize_text_field(wp_unslash($_REQUEST['formshield_community_upgrade_email'])) : '',
				);

				// Community upgrade join disabled for free version
				$response = false;

				if ( is_wp_error( $response ) ) {
					FormShieldUtils::show_wp_admin_notice( 'Hmmm. Something went wrong when we tried to send you your upgrade discount code. Please try again.', 'notice-success is-dismissible', true );
				} else {
					FormShieldUtils::show_wp_admin_notice( 'Awesome! Check your email for your upgrade discount code.', 'notice-success is-dismissible', true );
					self::hide_community_upgrade_banner( true );
				}
			}
		}

		// License activation disabled for free version

		// Process settings form
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- reading admin navigation param only
		$action = isset( $_GET['action'] ) ? sanitize_key( wp_unslash( $_GET['action'] ) ) : '';
		if ( 'formshield_settings' == $action ) {
			$hidden_field = isset( $_POST['formshield_settings_submitted'] ) ? sanitize_text_field(wp_unslash($_POST['formshield_settings_submitted'])) : '';

			if ( ! empty( $hidden_field ) && check_admin_referer( 'formshield_settings', 'formshield_nonce' ) ) {
				// Get autoprotect change
				$autoprotect_change = isset( $_POST['autoprotect'] ) ? sanitize_text_field(wp_unslash($_POST['autoprotect'])) : '';

				// Get minimal confidence change
				$min_confidence_change = isset( $_POST['minimal_confidence'] ) ? sanitize_text_field(wp_unslash($_POST['minimal_confidence'])) : '';

				// Validate autoprotect change
				$autoprotect_validation_failed = self::autoprotect_validate( $autoprotect_change );

				// Validate minimal confidence change
				$minimal_confidence = isset( $_POST['minimal_confidence'] ) ? floatval( wp_unslash( $_POST['minimal_confidence'] ) ) : null;
				$min_confidence_validation_failed = $minimal_confidence !== null ? self::minimal_confidence_validate( $minimal_confidence ) : '';

				if ( ! $autoprotect_validation_failed && ! $min_confidence_validation_failed ) {
					// Save settings changes
					self::handle_settings_changes( $_POST );
				}
			}
		}

		// Process logout form
		if ( isset( $_GET['action'] ) && 'formshield_logout' == sanitize_text_field(wp_unslash($_GET['action'])) ) {
			$hidden_field = isset( $_POST['formshield_logout_submitted'] ) ? sanitize_text_field(wp_unslash($_POST['formshield_logout_submitted'])) : '';

			if ( ! empty( $hidden_field ) && check_admin_referer( 'formshield_logout', 'formshield_nonce' ) ) {
				self::logout();
			}
		}

		// Hide community upgrade banner
		if ( !empty( $_GET['hide_community_nag'] ) ) {
			self::hide_community_upgrade_banner();
		}
	}

	/**
	 * Logout
	 */
	public static function logout() {
		$options = form_shield()->get_options();

		// Reset options
		$options = array_merge( $options, array(
			'wp_hp_premium_license'     => 0,
			'wp_hp_premium_license_key' => '',
		) );

		form_shield()->update_options( $options );

		wp_redirect( form_shield()->admin_url );
		exit;
	}

	/**
	 * Check premium license
	 */
	public static function premium_license_check() {
		// License checking disabled for free version
		return;
	}

	/**
	 * Get displayable license message (disabled for free version)
	 */
	public static function get_displayable_license_message( $license_msg ) {
		return 'License checking disabled for free version';
	}

	/**
	 * Validate license key (disabled for free version)
	 */
	public static function license_key_validate( $license_key ) {
		return true; // Always fail validation for free version
	}

	/**
	 * Check license key with remote server
	 */
	public static function remote_license_check( $license_key, $license_id ) {
		// License checking disabled for free version
		return array(
			'success' => false,
			'license' => 'invalid'
		);
	}

	/**
	 * Activate license key with remote server
	 */
	public static function remote_license_activation( $license_key, $license_id ) {
		// License activation disabled for free version
		return array(
			'success' => false,
			'license' => 'invalid'
		);
	}

	/**
	 * Handle license key changes (disabled for free version)
	 */
	public static function handle_license_key_changes( $license_key ) {
		// License handling disabled for free version
		return;
	}

	/**
	 * Validate autoprotect
	 */
	public static function autoprotect_validate( $autoprotect ) {
		$validation_failed = false;

		// Auto-protect validation disabled for free version
		if ( false ) {
			FormShieldUtils::show_wp_admin_notice( 'Automatic protection of all forms requires a premium license.', 'notice-error is-dismissible', true );
			$validation_failed = true;
		}

		if ( ! is_numeric( $autoprotect ) ) {
			FormShieldUtils::show_wp_admin_notice( 'Auto-protect status should be either 0 or 1.', 'notice-error is-dismissible', true );
			$validation_failed = true;
		}

		if ( $autoprotect > 1 ) {
			FormShieldUtils::show_wp_admin_notice( 'Auto-protect status should not be higher than 1.', 'notice-error is-dismissible', true );
			$validation_failed = true;
		}

		return $validation_failed;
	}

	/**
	 * Validate minimal confidence
	 */
	public static function minimal_confidence_validate( $minimal_confidence ) {
		$validation_failed = false;

		if ( empty( $minimal_confidence ) ) {
			FormShieldUtils::show_wp_admin_notice( 'Minimal confidence value required.', 'notice-error is-dismissible', true );
			$validation_failed = true;
		}

		if ( ! is_numeric( $minimal_confidence ) ) {
			FormShieldUtils::show_wp_admin_notice( 'Minimal value should be a number.', 'notice-error is-dismissible', true );
			$validation_failed = true;
		}

		if ( $minimal_confidence < 0 || $minimal_confidence > 100 ) {
			FormShieldUtils::show_wp_admin_notice( 'Minimal value should be at least 0 and at most 100.', 'notice-error is-dismissible', true );
			$validation_failed = true;
		}

		return $validation_failed;
	}

	/**
	 * Handle settings changes
	 */
	public static function handle_settings_changes( $posted_data ) {
		$options                         = form_shield()->get_options();
		$options['autoprotect']         = isset( $posted_data['autoprotect'] ) ? sanitize_text_field( $posted_data['autoprotect'] ) : '';
		$options['minimal_confidence']   = isset( $posted_data['minimal_confidence'] ) ? sanitize_text_field( $posted_data['minimal_confidence'] ) : '';

		form_shield()->update_options( $options );

		FormShieldUtils::show_wp_admin_notice( 'FormShield settings changes saved successfully.', 'notice-success is-dismissible', true );

		FormShieldAutoProtect::init();
	}

	/**
	 * Community Upgrade Banner - премахнат
	 */
	public static function display_community_upgrade_banner() {
		// Рекламата за ъпгрейд е премахната
		return;
	}

	/**
	 * Hide Community Upgrade Banner
	 */
	public static function hide_community_upgrade_banner( $forever = false ) {
		$options = form_shield()->get_options();
		$options['hide_community_nag'] = $forever ? -1 : 1;
		form_shield()->update_options( $options );
	}

	/**
	 * Re-enable Community Upgrade Banner
	 */
	public static function reenable_community_upgrade_banner() {
		$options = form_shield()->get_options();
		if( $options['hide_community_nag'] == 1 ) {
			$options['hide_community_nag'] = 0;
			form_shield()->update_options( $options );
		}
	}

	/**
	 * Download debug report
	 */
	public static function download_debug_report() {
		$options = form_shield()->get_options();

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- reading admin navigation param only
		if ( isset( $_GET['action'] ) && 'formshield_debug_report' == sanitize_text_field( wp_unslash( $_GET['action'] ) ) ) {
			header( 'Content-Type: text/plain' );
			header( 'Content-Disposition: attachment; filename=formshield-debug-report.txt' );

			ob_end_clean();

			echo "FormShield Debug Report\n";
			echo "======================\n\n";

			echo "WordPress Version: " . esc_html(get_bloginfo( 'version' )) . "\n";
			echo "PHP Version: " . esc_html(phpversion()) . "\n";
			echo "FormShield Version: " . esc_html(FORMSHIELD_VERSION) . "\n\n";

			echo "FormShield Options\n";
			echo "=================\n\n";


			exit;
		}
	}

	/**
	 * Check if form is enabled (returns boolean)
	 */
	public static function is_form_enabled( $form_id ) {
		$options = form_shield()->get_options();
		
		if ( isset( $options['formshield_forms'] ) && isset( $options['formshield_forms'][ $form_id ] ) ) {
			return (int)$options['formshield_forms'][ $form_id ]['form_enabled'] === 1;
		}
		
		return false;
	}

	/**
	 * Render form enabled checkbox
	 */
	public static function render_formshield_fm_enabled_cb( $form_id ) {
		$enabled = self::is_form_enabled( $form_id );
		
		return sprintf(
			'<input type="checkbox" id="formshield-fm-enable-%s" class="formshield-fm-enable-cb" %s />',
			esc_attr( $form_id ),
			checked( $enabled, true, false )
		);
	}

	/**
	 * Handle form enabled change
	 */
	public static function form_enabled_change() {
		
		// Verify nonce
		formshield_verify_nonce_or_bail('formshield_form_enabled_change');

		$form_id = formshield_get_post_string('fid');
		$enabled = formshield_get_post_int('enabled');
		

		try {
			FormShieldForms::enable_forms( $form_id, $enabled );
			wp_send_json_success();
		} catch (Exception $e) {
			wp_send_json_error('Failed to update form: ' . $e->getMessage());
		} catch (Error $e) {
			wp_send_json_error('Fatal error updating form: ' . $e->getMessage());
		}
	}

	/**
	 * Handle scan forms AJAX request
	 */
	public static function scan_forms() {
		
		// Verify nonce
		formshield_verify_nonce_or_bail('formshield_scan_forms');
		

		try {
			// Scan for forms using FormShieldFormDetector
			$forms = FormShieldFormDetector::scan_site_for_forms();
			
			// Scan completed successfully
		} catch (Exception $e) {
			wp_send_json_error('Scan failed: ' . $e->getMessage());
			return;
		} catch (Error $e) {
			wp_send_json_error('Fatal error during scan: ' . $e->getMessage());
			return;
		}
		
		// Prepare detailed scan results
		$detailed_results = array();
		foreach ($forms as $form) {
			$form_status = self::get_form_usage_status($form);
			$detailed_results[] = array(
				'name' => $form['name'],
				'type' => $form['type'],
				'status' => $form_status['status'],
				'message' => $form_status['message'],
				'icon' => $form_status['icon']
			);
		}
		
		wp_send_json_success( array(
			'forms_found' => count( $forms ),
			'message' => 'Found ' . count( $forms ) . ' forms',
			'detailed_results' => $detailed_results
		) );
	}

	/**
	 * Handle rescan forms AJAX request
	 */
	public static function rescan_forms() {
		
		// Verify nonce
		formshield_verify_nonce_or_bail('formsh_rescan_forms');
		

		// Get previous forms for comparison
		$options = FormShield::get_options();
		$previous_forms = isset($options['detected_forms']) ? $options['detected_forms'] : array();
		$previous_form_ids = array_column($previous_forms, 'id');

		// Clear cache and rescan
		delete_transient( 'dcd_divi_scan' );
		$forms = FormShieldFormDetector::scan_site_for_forms();
		
		
		// Compare with previous results to find new and deleted forms
		$new_forms = array();
		$deleted_forms = array();
		$current_form_ids = array_column($forms, 'id');
		
		// Find new forms (in current scan but not in previous)
		foreach ($forms as $form) {
			if (!in_array($form['id'], $previous_form_ids)) {
				$new_forms[] = $form;
			}
		}
		
		// Find deleted forms (in previous scan but not in current)
		foreach ($previous_forms as $prev_form) {
			if (!in_array($prev_form['id'], $current_form_ids)) {
				$deleted_forms[] = $prev_form;
			}
		}
		
		// Prepare detailed scan results
		$detailed_results = array();
		foreach ($forms as $form) {
			$form_status = self::get_form_usage_status($form);
			$is_new = in_array($form['id'], array_column($new_forms, 'id'));
			$detailed_results[] = array(
				'name' => $form['name'],
				'type' => $form['type'],
				'status' => $form_status['status'],
				'message' => $form_status['message'],
				'icon' => $form_status['icon'],
				'is_new' => $is_new
			);
		}
		
		// Determine message based on results
		$total_forms = count($forms);
		$new_forms_count = count($new_forms);
		$deleted_forms_count = count($deleted_forms);
		
		if ($new_forms_count > 0 && $deleted_forms_count > 0) {
			$message = "Намерени {$new_forms_count} нови форми, изтрити {$deleted_forms_count} форми. Общо {$total_forms} форми";
		} elseif ($new_forms_count > 0) {
			$message = "Намерени {$new_forms_count} нови форми от общо {$total_forms} форми";
		} elseif ($deleted_forms_count > 0) {
			$message = "Изтрити {$deleted_forms_count} форми. Общо {$total_forms} форми";
		} else {
			$message = "Няма промени. Общо {$total_forms} форми";
		}
		
		wp_send_json_success( array(
			'forms_found' => $total_forms,
			'new_forms_found' => $new_forms_count,
			'deleted_forms_found' => $deleted_forms_count,
			'message' => $message,
			'detailed_results' => $detailed_results,
			'deleted_forms' => $deleted_forms
		) );
	}
	
	/**
	 * Get form usage status (whether it's used on a page or not)
	 *
	 * @param array $form
	 * @return array
	 */
	public static function get_form_usage_status($form) {
		$form_id = $form['id'];
		$form_type = $form['type'];
		
		// Check if form is used on any page
		$is_used = false;
		$page_url = '';
		
		if (strpos($form_id, 'divi_') !== false) {
			// For Divi forms, check if page exists
			$page_id = str_replace('divi_', '', $form_id);
			if (is_numeric($page_id) && get_post($page_id)) {
				$is_used = true;
				$page_url = get_permalink($page_id);
			}
		} elseif (strpos($form_id, 'cf7_') !== false) {
			// For Contact Form 7, search for shortcode usage
			$form_id_number = str_replace('cf7_', '', $form_id);
			$page_url = self::find_contact_form_7_page($form_id_number);
			$is_used = !empty($page_url);
		} elseif (strpos($form_id, 'wpforms_') !== false) {
			// For WPForms, search for shortcode usage
			$form_id_number = str_replace('wpforms_', '', $form_id);
			$page_url = self::find_wpforms_page($form_id_number);
			$is_used = !empty($page_url);
		} elseif (strpos($form_id, 'gravity_') !== false) {
			// For Gravity Forms, search for shortcode usage
			$form_id_number = str_replace('gravity_', '', $form_id);
			$page_url = self::find_gravity_forms_page($form_id_number);
			$is_used = !empty($page_url);
		} elseif (strpos($form_id, 'ninja_') !== false) {
			// For Ninja Forms, search for shortcode usage
			$form_id_number = str_replace('ninja_', '', $form_id);
			$page_url = self::find_ninja_forms_page($form_id_number);
			$is_used = !empty($page_url);
		} elseif (strpos($form_id, 'comments_') !== false) {
			// For comments, check if post exists
			$post_id = str_replace('comments_', '', $form_id);
			if (is_numeric($post_id) && get_post($post_id)) {
				$is_used = true;
				$page_url = get_permalink($post_id);
			}
		} elseif ($form_id === 'frontend_detector') {
			// Frontend detector is always active
			$is_used = true;
			$page_url = '';
		}
		
		if ($is_used) {
			return array(
				'status' => 'active',
				'message' => 'Активна на страница',
				'icon' => '✅'
			);
		} else {
			return array(
				'status' => 'unused',
				'message' => 'Не се използва никъде',
				'icon' => '⚠️'
			);
		}
	}
	

	

	

	

	

	
	/**
	 * Check form status AJAX handler
	 */
	public static function check_form_status() {
		$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'formshield_check_form_status' ) ) {
			wp_send_json_error( 'Invalid nonce' );
		}
		
		$form_id = isset( $_POST['form_id'] ) ? absint( wp_unslash( $_POST['form_id'] ) ) : 0;
		if ( ! $form_id ) {
			wp_send_json_error( 'No form ID provided' );
		}
		
		// Get form data
		$options = form_shield()->get_options();
		$forms = FormShieldForms::get_forms();
		
		$form = null;
		foreach ($forms as $f) {
			if ($f['id'] === $form_id) {
				$form = $f;
				break;
			}
		}
		
		if (!$form) {
			wp_send_json_error( 'Form not found' );
		}
		
		// Get form status
		$form_status = self::get_form_usage_status($form);
		
		wp_send_json_success( array(
			'form_id' => $form_id,
			'status' => $form_status['status'],
			'message' => $form_status['message'],
			'icon' => $form_status['icon']
		) );
	}

	
}