<?php

// Ensure the file is not accessed directly
if ( !defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Handles deletion of old plugin folder when plugin name changes
 *
 * @package BWDCV
 * @version 2.1.2
 */
class BWDCV_Delete_Old_Folder {

    private $old_folder_name;
    private $current_plugin_path;
    private $plugins_directory;
    private $success = false;
    private $errors = [];

    /**
     * Constructor
     *
     * @param  string  $old_folder_name  The old plugin folder name (e.g., 'wp-cv-builder-saas')
     */
    public function __construct( $old_folder_name = 'wp-cv-builder-saas' ) {
        $this->old_folder_name = $old_folder_name;
        $this->current_plugin_path = plugin_dir_path( BWDCV_FILE );
        $this->plugins_directory = dirname( $this->current_plugin_path );
    }

    /**
     * Main method to delete old plugin folder
     *
     * @return bool Success status
     */
    public function delete_old_folder() {
        try {
            if ( !$this->validate_environment() ) {
                return false;
            }

            $old_folder_path = $this->plugins_directory . '/' . $this->old_folder_name;

            if ( !$this->old_folder_exists( $old_folder_path ) ) {
                $this->success = true;
                return true;
            }

            if ( $this->is_current_plugin_folder( $old_folder_path ) ) {
                $this->errors[] = 'Safety check failed: Cannot delete current plugin folder';
                return false;
            }

            if ( !$this->verify_old_plugin_folder( $old_folder_path ) ) {
                $this->errors[] = 'Old folder verification failed';
                return false;
            }

            $active_old_plugin = $this->get_active_old_plugin_path();
            if ( $active_old_plugin ) {
                $this->errors[] = 'Old plugin is still active';

                add_action( 'admin_notices', function () use ( $active_old_plugin ) {
                    echo '<div class="notice notice-warning is-dismissible"><p>'
                    . sprintf(
                        /* translators: %s: plugin path */
                        esc_html__( 'CV Builder: Please deactivate the old plugin version (%s) manually before the old folder can be removed.', 'cv-builder' ),
                        '<strong>' . esc_html( $active_old_plugin ) . '</strong>'
                    )
                        . '</p></div>';
                } );

                return false;
            }

            // Old plugin is already inactive, safe to delete the folder
            if ( $this->recursive_delete( $old_folder_path ) ) {
                $this->success = true;
                return true;
            } else {
                $this->errors[] = 'Failed to delete old plugin folder';
                return false;
            }

        } catch ( Exception $e ) {
            $this->errors[] = $e->getMessage();
            return false;
        }
    }

    /**
     * Validate the environment before attempting deletion
     *
     * @return bool
     */
    private function validate_environment() {
        // Check if we have filesystem access
        if ( !function_exists( 'WP_Filesystem' ) ) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
        }

        // Check write permissions on plugins directory
        if ( !is_writable( $this->plugins_directory ) ) {
            $this->errors[] = 'Plugins directory is not writable';

            return false;
        }

        // Ensure we're running from the correct plugin
        if ( !defined( 'BWDCV_FILE' ) ) {
            $this->errors[] = 'BWDCV_FILE constant not defined';

            return false;
        }

        return true;
    }

    /**
     * Check if old folder exists
     *
     * @param  string  $old_folder_path
     *
     * @return bool
     */
    private function old_folder_exists( $old_folder_path ) {
        return is_dir( $old_folder_path );
    }

    /**
     * Safety check to ensure we're not deleting the current plugin folder
     *
     * @param  string  $old_folder_path
     *
     * @return bool
     */
    private function is_current_plugin_folder( $old_folder_path ) {
        // First, check if we're trying to delete the exact same directory
        $old_real_path = realpath( $old_folder_path );
        $current_real_path = realpath( $this->current_plugin_path );

        if ( $old_real_path && $current_real_path && $old_real_path === $current_real_path ) {
            // Same directory, but let's check if this is an upgrade scenario
            return $this->is_upgrade_scenario( $old_folder_path );
        }

        return false;
    }

    /**
     * Check if this is an upgrade scenario where we're running new code from old directory
     */
    private function is_upgrade_scenario( $old_folder_path ) {
        $main_plugin_file = $old_folder_path . '/wp-cv-builder-saas.php';

        if ( !file_exists( $main_plugin_file ) ) {
            return true; // If old plugin file doesn't exist, it's safe to proceed
        }

        $file_content = file_get_contents( $main_plugin_file );
        if ( !$file_content ) {
            return true; // Can't read file, assume safe
        }

        // Check plugin headers to determine version
        if ( preg_match( '/Plugin Name:\s*(.+)/i', $file_content, $matches ) ) {
            $plugin_name = trim( $matches[1] );
            error_log( "BWDCV Debug: Found plugin name: {$plugin_name}" );

            // If it says "WP CV Builder SaaS", it's the old version
            if ( strpos( $plugin_name, 'WP CV Builder SaaS' ) !== false ) {
                error_log( 'BWDCV Debug: Detected old plugin version, allowing deletion' );

                return false; // Allow deletion
            }

            // If it says just "WP CV Builder" (new version), don't delete
            if ( strpos( $plugin_name, 'WP CV Builder' ) !== false && strpos( $plugin_name, 'SaaS' ) === false ) {
                error_log( 'BWDCV Debug: Detected new plugin version, preventing deletion' );

                return true; // Prevent deletion
            }
        }

        // If we can't determine, err on the side of caution
        error_log( 'BWDCV Debug: Could not determine plugin version, preventing deletion' );

        return true;
    }
    /**
     * Verify that the old folder contains our plugin
     *
     * @param  string  $old_folder_path
     *
     * @return bool
     */
    private function verify_old_plugin_folder( $old_folder_path ) {
        // Look for the main plugin file with old name
        $old_plugin_files = [
            $old_folder_path . '/wp-cv-builder-saas.php', // Correct old plugin file name
            $old_folder_path . '/bwdcv-boots.php', // Alternative name
        ];

        foreach ( $old_plugin_files as $file ) {
            if ( file_exists( $file ) ) {
                // Read the file to check for plugin headers
                $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;
    }

    /**
     * Deactivate the old plugin if it's currently active
     */
    // private function deactivate_old_plugin() {
    //     $old_plugin_paths = [
    //         $this->old_folder_name . '/wp-cv-builder-saas.php', // Correct old plugin file name
    //         $this->old_folder_name . '/bwdcv-boots.php',       // Alternative name
    //     ];

    //     foreach ( $old_plugin_paths as $plugin_path ) {
    //         if ( is_plugin_active( $plugin_path ) ) {
    //             deactivate_plugins( $plugin_path, true );
    //         }
    //     }
    // }

    /**
     * Check if the old plugin is still active.
     * Returns the active plugin path if found, false otherwise.
     *
     * @return string|false
     */
    private function get_active_old_plugin_path() {
        $old_plugin_paths = [
            $this->old_folder_name . '/wp-cv-builder-saas.php',
            $this->old_folder_name . '/bwdcv-boots.php',
        ];

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

        return false;
    }

    /**
     * Recursively delete a directory and its contents
     *
     * @param  string  $dir
     *
     * @return bool
     */
    private function recursive_delete( $dir ) {
        if ( !is_dir( $dir ) ) {
            return false;
        }

        $files = array_diff( scandir( $dir ), ['.', '..'] );

        foreach ( $files as $file ) {
            $path = $dir . '/' . $file;

            if ( is_dir( $path ) ) {
                if ( !$this->recursive_delete( $path ) ) {
                    return false;
                }
            } else {
                if ( !unlink( $path ) ) {
                    error_log( "BWDCV: Failed to delete file: {$path}" );

                    return false;
                }
            }
        }

        return rmdir( $dir );
    }

    /**
     * Get success status
     *
     * @return bool
     */
    public function was_successful() {
        return $this->success;
    }

    /**
     * Get any errors that occurred
     *
     * @return array
     */
    public function get_errors() {
        return $this->errors;
    }

    /**
     * Get error messages as string
     *
     * @return string
     */
    public function get_error_message() {
        return implode( ', ', $this->errors );
    }

    /**
     * Static method for quick deletion
     *
     * @param  string  $old_folder_name
     *
     * @return bool
     */
    public static function cleanup_old_folder( $old_folder_name = 'wp-cv-builder-saas' ) {
        $deleter = new self( $old_folder_name );

        return $deleter->delete_old_folder();
    }

}
