<?php

namespace fluXtore\Core\Settings;

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

if ( ! class_exists( 'fluXtore_Default_Editor' ) ) {
    class fluXtore_Default_Editor {
        /**
         * @var self|null
         */
        private static $instance = null;

        private function __construct() {}

        public static function init() {
            if ( null !== self::$instance ) {
                return;
            }

            self::$instance = new self();

            add_action( 'wp_ajax_my_ajax_action', [ self::$instance, 'update_default_editor' ] );
            add_action( 'wp_ajax_nopriv_my_ajax_action', [ self::$instance, 'update_default_editor' ] );

            add_action( 'wp_ajax_get_default_editior', [ self::$instance, 'get_default_editor' ] );
            add_action( 'wp_ajax_nopriv_get_default_editior', [ self::$instance, 'get_default_editor' ] );

            add_action( 'wp_ajax_check_elementor_plugin', [ self::$instance, 'check_builders' ] );
            add_action( 'wp_ajax_nopriv_check_elementor_plugin', [ self::$instance, 'check_builders' ] );

            add_action( 'deactivated_plugin', [ self::$instance, 'handle_builder_deactivation' ], 10, 2 );
        }

        public function update_default_editor() {
            $nonce = isset( $_POST['security'] ) ? sanitize_text_field( wp_unslash( $_POST['security'] ) ) : '';

            if ( ! wp_verify_nonce( $nonce, 'fluxtore_ajax_nonce' ) ) {
                wp_send_json_error( 'Invalid nonce' );
            }

            $requested_editor = isset( $_POST['option'] ) ? sanitize_text_field( wp_unslash( $_POST['option'] ) ) : '';

            if ( empty( $requested_editor ) ) {
                wp_send_json_error( 'Missing option' );
            }

            $parent_theme = $this->get_parent_theme_name();

            switch ( $requested_editor ) {
                case 'Elementor':
                    if ( ! class_exists( '\\Elementor\\Plugin' ) && ! is_plugin_active( 'elementor/elementor.php' ) ) {
                        $requested_editor = 'Gutenberg';
                    }
                    break;
                case 'Bricks':
                    if ( 'Bricks' !== $parent_theme ) {
                        $requested_editor = 'Gutenberg';
                    }
                    break;
                case 'Divi':
                    if ( 'Divi' !== $parent_theme ) {
                        $requested_editor = 'Gutenberg';
                    }
                    break;
            }

            $result          = update_option( '__fluxtore_default_editior', $requested_editor );
            $current_editor  = get_option( '__fluxtore_default_editior', '' );

            if ( $result || $current_editor === $requested_editor ) {
                error_log( 'Fluxtore: Editor option updated to: ' . $current_editor );

                wp_send_json_success(
                    [
                        'message'        => 'Received option: ' . $requested_editor,
                        'current_editor' => $current_editor,
                        'theme_name'     => $parent_theme,
                    ]
                );
            }

            error_log( 'Fluxtore: Failed to update editor option. Requested: ' . $requested_editor );

            wp_send_json_error( 'Failed to update option' );
        }

        public function get_default_editor() {
            $nonce = isset( $_POST['security'] ) ? sanitize_text_field( wp_unslash( $_POST['security'] ) ) : '';

            if ( ! wp_verify_nonce( $nonce, 'fluxtore_ajax_nonce' ) ) {
                wp_send_json_error( 'Invalid nonce' );
            }

            $editor_value = get_option( '__fluxtore_default_editior', '' );

            if ( false === $editor_value ) {
                wp_send_json_error( 'Failed to get editor value' );
            }

            wp_send_json_success(
                [
                    'success'     => true,
                    'editorValue' => $editor_value,
                ]
            );
        }

        public function check_builders() {
            $response = [];
            $parent_theme = $this->get_parent_theme_name();

            $response['elementor'] = class_exists( '\\Elementor\\Plugin' );
            $response['bricks']    = ( 'Bricks' === $parent_theme );
            $response['divi']      = ( 'Divi' === $parent_theme );

            wp_send_json( $response );
        }

        public function handle_builder_deactivation( $plugin, $network_deactivating ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
            if ( false !== strpos( $plugin, 'elementor' ) && defined( 'FLUXTORE_DEFAULT_EDITIOR' ) && 'Elementor' === FLUXTORE_DEFAULT_EDITIOR ) {
                update_option( '__fluxtore_default_editior', 'Gutenberg' );
            }
        }

        private function get_parent_theme_name() {
            $current_theme = wp_get_theme();

            if ( is_child_theme() ) {
                $parent = $current_theme->parent();

                return $parent ? $parent->get( 'Name' ) : $current_theme->get( 'Name' );
            }

            return $current_theme->get( 'Name' );
        }
    }
}

fluXtore_Default_Editor::init();
