<?php 

namespace Lcmigrator\LcMigrator\Migrator\SiteInfo;
if( !function_exists('get_plugin_data') ){
    require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
}
class SiteInfo{

    private $export_path = null;
    public function export_data(string $export_path) {
        $this->export_path = $export_path;
        $data = [
            'site_url'       => get_site_url(),
            'home_url'       => get_home_url(),
            'admin_email'    => get_option('admin_email'),
            'active_plugins' => $this->get_active_plugins(),
            'theme'          => wp_get_theme()->get('Name'),
            'theme_version'  => wp_get_theme()->get('Version'),
            'wp_version'     => get_bloginfo('version'),
            'php_version'    => phpversion(),
            'database_info'  => $this->get_database_info(),
        ];

        $this->save_to_json($data);
    }

    private function get_active_plugins() {
        return array_map(function($plugin) {
            return [
                'name'    => $plugin,
                'version' => \get_plugin_data(WP_PLUGIN_DIR . '/' . $plugin)['Version'] ?? 'Unknown'
            ];
        }, get_option('active_plugins', []));
    }

    private function get_database_info() {
        global $wpdb;
        return [
            'db_name' => DB_NAME,
            'db_user' => DB_USER,
            'db_host' => DB_HOST,
            'prefix'  => $wpdb->prefix
        ];
    }

    private function save_to_json($data) {
        if (file_put_contents($this->export_path, json_encode($data, JSON_PRETTY_PRINT))) {
            error_log("Export successful: " . $this->export_path);
        } else {
            error_log("Export failed: Unable to write file.");
        }
    }
}