<?php
// Stop Direct Access
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
/**
 * Fixed Old Folder Checker - Prevents double notices
 */

class BWDCV_Old_Folder_Checker {

    private static $instance = null;
    private static $notice_shown = false;

    private $old_folder_name = 'wp-cv-builder-saas';
    private $old_folder_path;

    public function __construct() {
        // Prevent multiple instances
        if (self::$instance !== null) {
            return self::$instance;
        }

        self::$instance = $this;

        $this->old_folder_path = dirname( plugin_dir_path( BWDCV_FILE ) ) . '/' . $this->old_folder_name;

        // Only run checks in admin and if notice hasn't been shown
        if ( is_admin() && !self::$notice_shown ) {
            add_action( 'admin_notices', [ $this, 'show_old_folder_notice' ], 5 );
            add_action( 'wp_ajax_bwdcv_delete_old_folder', [ $this, 'handle_delete_old_folder' ] );
            add_action( 'admin_footer', [ $this, 'enqueue_admin_scripts' ] );
        }
    }

    /**
     * Singleton pattern to ensure only one instance
     */
    public static function get_instance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Check if old folder exists and contains our plugin
     */
    public function old_folder_exists() {
        if ( ! is_dir( $this->old_folder_path ) ) {
            return false;
        }

        // Verify it's actually our old plugin
        $old_plugin_files = [
            $this->old_folder_path . '/wp-cv-builder-saas.php',
            $this->old_folder_path . '/bwdcv-blocks.php',
        ];

        foreach ( $old_plugin_files as $file ) {
            if ( file_exists( $file ) ) {
                $file_content = file_get_contents( $file );
                if ( $file_content && (
                        strpos( $file_content, 'WP CV Builder' ) !== false ||
                        strpos( $file_content, 'wp-cv-builder-saas' ) !== false ||
                        strpos( $file_content, 'BWDCV_VERSION' ) !== false
                    ) ) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * Check if there are active conflicts
     */
    public function has_active_conflicts() {
        $old_plugin_paths = [
            $this->old_folder_name . '/wp-cv-builder-saas.php',
            $this->old_folder_name . '/bwdcv-blocks.php',
        ];

        foreach ( $old_plugin_paths as $plugin_path ) {
            if ( is_plugin_active( $plugin_path ) ) {
                return true;
            }
        }

        return false;
    }

    /**
     * Show admin notice about old folder - with duplicate prevention
     */
    public function show_old_folder_notice() {
        // Prevent multiple notices from showing
        if (self::$notice_shown) {
            return;
        }

        // Only show to administrators
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        // Check if old folder exists
        if ( ! $this->old_folder_exists() ) {
            return;
        }

        // Check for dismissal
        $has_conflicts = $this->has_active_conflicts();
        if ( ! $has_conflicts && get_transient( 'bwdcv_old_folder_dismissed' ) ) {
            return;
        }

        // Mark notice as shown to prevent duplicates
        self::$notice_shown = true;

        $notice_class = $has_conflicts ? 'notice-error' : 'notice-warning';
        $urgency_text = $has_conflicts ?
            esc_html__( 'URGENT: Both plugins are active and causing conflicts!', 'cv-builder' ) :
            esc_html__( 'Old plugin folder detected', 'cv-builder' );

        ?>
        <div class="notice <?php echo esc_attr( $notice_class ); ?> bwdcv-old-folder-notice"
             style="position: relative;"
             data-notice-id="bwdcv-old-folder-<?php echo esc_attr( uniqid() ); ?>">

            <h3><?php esc_html_e( 'WP CV Builder - ', 'cv-builder' ); ?><?php echo esc_html( $urgency_text ); ?></h3>

            <?php if ( $has_conflicts ): ?>
                <p style="color: #d63638; font-weight: bold;">
                    <?php esc_html_e( 'Both old and new versions of WP CV Builder are currently active. This will cause PHP errors and conflicts.', 'cv-builder' ); ?>
                </p>
            <?php endif; ?>

            <p>
                <?php esc_html_e( 'We detected an old version of the WP CV Builder plugin in your plugins directory.', 'cv-builder' ); ?>
                <br>
                <strong><?php esc_html_e( 'Old folder:', 'cv-builder' ); ?></strong> <code><?php echo esc_html( $this->old_folder_name ); ?></code>
                <br>
                <strong><?php esc_html_e( 'Current folder:', 'cv-builder' ); ?></strong> <code><?php echo esc_html( BWDCV_PLUGIN_NAME ); ?></code>
            </p>

            <p>
                <strong><?php esc_html_e( 'Recommended action:', 'cv-builder' ); ?></strong>
                <?php if ( $has_conflicts ): ?>
                    <?php esc_html_e( 'Immediately deactivate and delete the old plugin to resolve conflicts.', 'cv-builder' ); ?>
                <?php else: ?>
                    <?php esc_html_e( 'Delete the old plugin folder to avoid future conflicts and free up disk space.', 'cv-builder' ); ?>
                <?php endif; ?>
            </p>

            <p>
                <button type="button" class="button <?php echo $has_conflicts ? 'button-primary' : 'button-secondary'; ?>"
                        id="bwdcv-delete-old-folder"
                        data-nonce="<?php echo esc_attr( wp_create_nonce( 'bwdcv_delete_old_folder' ) ); ?>"
                        data-has-conflicts="<?php echo $has_conflicts ? '1' : '0'; ?>">
                    <?php if ( $has_conflicts ): ?>
                        <?php esc_html_e( 'Fix Conflicts - Deactivate & Delete Old Folder', 'cv-builder' ); ?>
                    <?php else: ?>
                        <?php esc_html_e( 'Delete Old Folder', 'cv-builder' ); ?>
                    <?php endif; ?>
                </button>

                <?php if ( ! $has_conflicts ): ?>
                    <button type="button" class="button" id="bwdcv-dismiss-notice">
                        <?php esc_html_e( 'Dismiss for 7 days', 'cv-builder' ); ?>
                    </button>
                <?php endif; ?>

                <span class="bwdcv-loading" style="display: none; margin-left: 10px;">
                    <span class="spinner is-active" style="float: none; margin: 0;"></span>
                    <?php esc_html_e( 'Processing...', 'cv-builder' ); ?>
                </span>
            </p>

            <div class="bwdcv-result-message" style="margin-top: 10px;"></div>
        </div>
        <?php
    }

    /**
     * Enqueue admin scripts - with duplicate prevention
     */
    public function enqueue_admin_scripts() {
        // Prevent multiple script enqueues
        static $scripts_enqueued = false;
        if ($scripts_enqueued) {
            return;
        }

        if ( ! $this->old_folder_exists() ) {
            return;
        }

        $has_conflicts = $this->has_active_conflicts();
        if ( ! $has_conflicts && get_transient( 'bwdcv_old_folder_dismissed' ) ) {
            return;
        }

        $scripts_enqueued = true;

        ?>
        <script type="text/javascript">
            jQuery(document).ready(function($) {
                // Prevent multiple event handlers
                if (window.bwdcvOldFolderHandlersAttached) {
                    return;
                }
                window.bwdcvOldFolderHandlersAttached = true;

                // Handle delete old folder button
                $(document).on('click', '#bwdcv-delete-old-folder', function(e) {
                    e.preventDefault();
                    var $button = $(this);

                    // Prevent multiple clicks
                    if ($button.prop('disabled')) {
                        return;
                    }

                    var hasConflicts = $button.data('has-conflicts') === '1';
                    var nonce = $button.data('nonce');

                    var confirmMessage = hasConflicts
                        ? '<?php echo esc_js( __( 'This will deactivate the old plugin and delete its folder to resolve conflicts. Continue?', 'cv-builder' ) ); ?>'
                        : '<?php echo esc_js( __( 'Are you sure you want to delete the old plugin folder? This action cannot be undone.', 'cv-builder' ) ); ?>';

                    if (!confirm(confirmMessage)) {
                        return;
                    }

                    var $loading = $('.bwdcv-loading');
                    var $result = $('.bwdcv-result-message');

                    $button.prop('disabled', true);
                    $loading.show();
                    $result.empty();

                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'bwdcv_delete_old_folder',
                            nonce: nonce
                        },
                        success: function(response) {
                            $loading.hide();

                            if (response.success) {
                                $result.html('<div class="notice notice-success inline"><p>' + response.data.message + '</p></div>');

                                // Hide all notices with the same class to prevent duplicates
                                $('.bwdcv-old-folder-notice').fadeOut(function() {
                                    $(this).remove();
                                });

                                setTimeout(function() {
                                    window.location.reload();
                                }, 2000);
                            } else {
                                $result.html('<div class="notice notice-error inline"><p>' + (response.data ? response.data.message : 'Unknown error') + '</p></div>');
                                $button.prop('disabled', false);
                            }
                        },
                        error: function(xhr, status, error) {
                            $loading.hide();
                            $result.html('<div class="notice notice-error inline"><p><?php echo esc_js( __( 'An error occurred. Please try again.', 'cv-builder' ) ); ?></p></div>');
                            $button.prop('disabled', false);
                        }
                    });
                });

                // Handle dismiss button
                $(document).on('click', '#bwdcv-dismiss-notice', function(e) {
                    e.preventDefault();

                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'bwdcv_dismiss_old_folder_notice'
                        },
                        success: function() {
                            $('.bwdcv-old-folder-notice').fadeOut(function() {
                                $(this).remove();
                            });
                        },
                        error: function() {
                        }
                    });
                });
            });
        </script>
        <?php
    }

    /**
     * Handle AJAX request to delete old folder
     */
    public function handle_delete_old_folder() {
        // Verify nonce
        if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'bwdcv_delete_old_folder' ) ) {
            wp_send_json_error( [
                'message' => esc_html__( 'Security check failed', 'cv-builder' )
            ] );
        }

        // Check permissions
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( [
                'message' => esc_html__( 'You do not have permission to perform this action.', 'cv-builder' )
            ] );
        }

        try {
            $deleter_file = dirname( __FILE__ ) . '/delete_old_folder.php';

            if ( ! file_exists( $deleter_file ) ) {
                $deleter_file = plugin_dir_path( BWDCV_FILE ) . 'includes/updater/delete_old_folder.php';
            }

            if ( ! file_exists( $deleter_file ) ) {
                $deleter_file = plugin_dir_path( __FILE__ ) . 'delete_old_folder.php';
            }

            if ( ! file_exists( $deleter_file ) ) {
                wp_send_json_error( [
                    'message' => esc_html__( 'BWDCV_Delete_Old_Folder class file not found.', 'cv-builder' )
                ] );
            }

            require_once $deleter_file;

            if ( ! class_exists( 'BWDCV_Delete_Old_Folder' ) ) {
                wp_send_json_error( [
                    'message' => esc_html__( 'BWDCV_Delete_Old_Folder class not found after including file.', 'cv-builder' )
                ] );
            }

            $folder_deleter = new BWDCV_Delete_Old_Folder( $this->old_folder_name );
            $success = $folder_deleter->delete_old_folder();

            if ( $success ) {
                // Clear the notice shown flag on success
                self::$notice_shown = false;

                wp_send_json_success( [
                    'message' => esc_html__( 'Old plugin folder deleted successfully! Conflicts resolved.', 'cv-builder' )
                ] );
            } else {
                $errors = $folder_deleter->get_error_message();
                wp_send_json_error( [
                    'message' => sprintf(
                        esc_html__( 'Failed to delete old folder: %s', 'cv-builder' ),
                        $errors ?: esc_html__( 'Unknown error', 'cv-builder' )
                    )
                ] );
            }

        } catch ( Exception $e ) {
            wp_send_json_error( [
                'message' => sprintf(
                    esc_html__( 'Error: %s', 'cv-builder' ),
                    $e->getMessage()
                )
            ] );
        }
    }
}

/**
 * Handle dismiss notice AJAX - with singleton check
 */
if ( ! function_exists( 'bwdcv_handle_dismiss_old_folder_notice' ) ) {
    function bwdcv_handle_dismiss_old_folder_notice() {
        if ( current_user_can( 'manage_options' ) ) {
            set_transient( 'bwdcv_old_folder_dismissed', true, 7 * DAY_IN_SECONDS );
        }
        wp_send_json_success();
    }
    add_action( 'wp_ajax_bwdcv_dismiss_old_folder_notice', 'bwdcv_handle_dismiss_old_folder_notice' );
}
