<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Sifency_Addons_Admin_Options_Ajax {

	private static $_instance = null;
	private $option_name      = 'sifency_addons_settings';

	/**
	 * Singleton Instance
	 */
	public static function instance() {
		if ( is_null( self::$_instance ) ) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	/**
	 * Constructor
	 */
	public function __construct() {
		add_action( 'wp_ajax_sifency_save_admin_data', array( $this, 'ajax_save_setting' ) );
	}

	/**
	 * Main AJAX Handler
	 */
	public function ajax_save_setting() {
		// Verify nonce properly
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'sifency_admin_options_nonce' ) ) {
			wp_send_json_error( array( 'message' => __( 'Security verification failed.', 'sifency-addons' ) ), 403 );
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'sifency-addons' ) ), 403 );
		}

		$p_key    = isset( $_POST['param1'] ) ? sanitize_key( wp_unslash( $_POST['param1'] ) ) : '';
		$p_subkey = isset( $_POST['param2'] ) ? sanitize_key( wp_unslash( $_POST['param2'] ) ) : '';
		$p_value  = isset( $_POST['param3'] ) ? wp_unslash( $_POST['param3'] ) : '';

		if ( empty( $p_key ) ) {
			wp_send_json_error( array( 'message' => __( 'Invalid parameters.', 'sifency-addons' ) ) );
		}

		if ( 'cpt_reset_defaults' === $p_key ) {
			if ( ! class_exists( 'Sifency_Addons_CPT_Module_Manager' ) ) {
				wp_send_json_error( array( 'message' => __( 'CPT Manager class not found.', 'sifency-addons' ) ) );
			}

			try {
				Sifency_Addons_CPT_Module_Manager::reset_to_defaults();
				wp_send_json_success( array( 'message' => __( 'Reset successful.', 'sifency-addons' ) ) );
			} catch ( Exception $e ) {
				wp_send_json_error( array( 'message' => $e->getMessage() ) );
			}
		}

		if ( 'cpt_enabled' === $p_key ) {

			if ( ! class_exists( 'Sifency_Addons_CPT_Module_Manager' ) ) {
				wp_send_json_error( array( 'message' => __( 'CPT Manager class not found.', 'sifency-addons' ) ) );
			}

			if ( ! $this->is_premium_active() ) {
				wp_send_json_error( array( 'message' => __( 'Pro version required to manage modules.', 'sifency-addons' ) ), 403 );
			}

			if ( empty( $p_subkey ) ) {
				wp_send_json_error( array( 'message' => __( 'Module key missing.', 'sifency-addons' ) ) );
			}

			$is_active = ( 'on' === $p_value || 'true' === $p_value || '1' === $p_value );

			try {
				if ( $is_active ) {
					Sifency_Addons_CPT_Module_Manager::enable_module( $p_subkey );
					/* translators: CPT enabled */
					$message = sprintf( __( '%s enabled.', 'sifency-addons' ), $p_subkey );
				} else {
					Sifency_Addons_CPT_Module_Manager::disable_module( $p_subkey );
					/* translators: CPT Disabled */
					$message = sprintf( __( '%s disabled.', 'sifency-addons' ), $p_subkey );
				}

				wp_send_json_success(
					array(
						'message' => $message,
						'enabled' => $is_active,
					)
				);

			} catch ( Exception $e ) {
				wp_send_json_error( array( 'message' => $e->getMessage() ) );
			}
		}

		$options = get_option( $this->option_name, array() );
		if ( ! is_array( $options ) ) {
			$options = array();
		}

		if ( ! empty( $p_subkey ) ) {
			if ( ! isset( $options[ $p_key ] ) || ! is_array( $options[ $p_key ] ) ) {
				$options[ $p_key ] = array();
			}
			$options[ $p_key ][ $p_subkey ] = sanitize_text_field( $p_value );
		} else {
			$options[ $p_key ] = sanitize_text_field( $p_value );
		}

		if ( update_option( $this->option_name, $options ) ) {
			wp_send_json_success( array( 'message' => __( 'Settings saved.', 'sifency-addons' ) ) );
		} else {
			wp_send_json_success( array( 'message' => __( 'Settings saved (no changes).', 'sifency-addons' ) ) );
		}
	}

	private function is_premium_active() {
		if ( class_exists( 'Sifency_Addons_Theme_Builder_Master' ) && method_exists( 'Sifency_Addons_Theme_Builder_Master', 'sync_environment_state' ) ) {
			try {
				if ( Sifency_Addons_Theme_Builder_Master::sync_environment_state() ) {
					return true;
				}
			} catch ( Exception $e ) {
			}
		}

		if ( class_exists( 'Sifency_Addons_CPT_Module_Manager' ) && method_exists( 'Sifency_Addons_CPT_Module_Manager', 'is_pro_active' ) ) {
			try {
				if ( Sifency_Addons_CPT_Module_Manager::is_pro_active() ) {
					return true;
				}
			} catch ( Exception $e ) {
			}
		}

		return false;
	}
}
