<?php

namespace WPUltimateSecurity\UltimateSecurity\Presentation\API\Controllers;

use WPUltimateSecurity\UltimateSecurity\Support\Helpers\Utils;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;

/**
 * Update Controller
 *
 * Handles WordPress, plugin, and theme update information
 */
class UpdateController
{
    /**
     * Get update information summary
     *
     * @return array
     */
    public static function get_update_info()
    {
        $result = [];
        $coreUpdate = self::get_latest_version();

        // Get plugin updates
        $plugin_updates = get_site_transient('update_plugins');
        $plugin_count = !empty($plugin_updates->response) ? count($plugin_updates->response) : 0;

        // Get theme updates
        $theme_updates = get_site_transient('update_themes');
        $theme_count = !empty($theme_updates->response) ? count($theme_updates->response) : 0;

        $result = [
            'wp_info' => $coreUpdate,
            'core_update_available' => (isset($coreUpdate['update_available']) && sanitize_text_field(wp_unslash($coreUpdate['update_available']))) ? 1 : 0,
            'plugin_updates' => $plugin_count,
            'theme_updates' => $theme_count
        ];
        return $result;
    }

    /**
     * Get latest WordPress version
     *
     * @return array|WP_Error
     */
    public static function get_latest_version()
    {
        $response = wp_remote_get('https://api.wordpress.org/core/version-check/1.7/', [
            'timeout' => 10,
            'sslverify' => true
        ]);

        if (is_wp_error($response)) {
            return $response;
        }

        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        if (empty($data['offers'][0]['current'])) {
            return new WP_Error('invalid_response', __('Invalid response from WordPress.org API', 'ultimate-security'));
        }

        $result = [
            'latest_version' => $data['offers'][0]['current'],
            'current_version' => get_bloginfo('version'),
            'update_available' => version_compare($data['offers'][0]['current'], get_bloginfo('version'), '>')
        ];
        return $result;
    }

    /**
     * Get plugin update information
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public static function get_update_plugin_info(WP_REST_Request $request)
    {
        // Check if transient exists
        $cached_data = get_transient('ultimate_security_plugin_updates');

        // Force refresh parameter
        $force_refresh = isset($request['force_refresh']) ? (bool) $request['force_refresh'] : false;

        // Return cached data if available and not forcing refresh
        if ($cached_data !== false && !$force_refresh) {
            return new WP_REST_Response($cached_data, 200);
        }

        // If we need to refresh, continue with original logic
        if (!function_exists('get_plugin_updates')) {
            require_once ABSPATH . 'wp-admin/includes/update.php';
        }

        wp_update_plugins();

        $update_plugins = get_site_transient('update_plugins');
        $all_plugins = Utils::get_plugins_cached();
        $updates = [];

        foreach ($all_plugins as $plugin_file => $plugin_data) {
            if (isset($update_plugins->response[$plugin_file])) {
                $update_info = $update_plugins->response[$plugin_file];

                // Make sure Version is included in plugin_data
                $current_version = isset($plugin_data['Version']) ? $plugin_data['Version'] : 'Unknown';

                $updates[] = [
                    'name' => $plugin_data['Name'],
                    'current_version' => $current_version,
                    'new_version' => $update_info->new_version,
                ];
            }
        }

        $response_data = [
            'plugins_with_updates' => $updates,
            'count' => count($updates),
        ];

        // Cache the data for 5 minutes
        set_transient('ultimate_security_plugin_updates', $response_data, 5 * MINUTE_IN_SECONDS);

        return new WP_REST_Response($response_data, 200);
    }

    /**
     * Get plugins information
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public static function get_plugins_info(WP_REST_Request $request)
    {
        $all_plugins = Utils::get_plugins_cached();
        $active_plugins = get_option('active_plugins', []);
        $update_plugins = get_site_transient('update_plugins');
        $auto_updates = get_option('auto_update_plugins', []);

        $ultimate_security_options = Utils::ultimate_security_get_option();
        $last_updated_times = get_option('ultimate_security_last_update_times', []);
        $plugins_list = [];

        foreach ($all_plugins as $plugin_file => $plugin_data) {
            $plugin_name = $plugin_data['Name'];
            $plugin_slug = dirname($plugin_file);
            $plugin_dir = WP_PLUGIN_DIR . '/' . $plugin_slug;

            // Get current and new version
            $current_version = isset($plugin_data['Version']) ? $plugin_data['Version'] : '';
            $new_version = '';
            $has_update = false;

            if (!empty($update_plugins->response[$plugin_file])) {
                $has_update = true;
                $new_version = isset($update_plugins->response[$plugin_file]->new_version)
                    ? $update_plugins->response[$plugin_file]->new_version
                    : '';
            }

            // Determine filters
            $filters = [];

            if (in_array($plugin_file, $active_plugins)) {
                $filters[] = 'Active';
                $filters[] = 'type-1';
            } else {
                $filters[] = 'Inactive';
                $filters[] = 'type-2';
            }

            if ($has_update) {
                $filters[] = 'Update Available';
                $filters[] = 'type-3';
            }

            if (!in_array($plugin_file, $auto_updates)) {
                $filters[] = 'Auto-updates Disabled';
            } else {
                $filters[] = 'Auto-updates Enabled';
            }

            // Get last update timestamp
            $last_updated = isset($last_updated_times['plugins'][$plugin_file])
                ? $last_updated_times['plugins'][$plugin_file]
                : null;

            // Get PHP/WP requirements
            $requires_php = isset($plugin_data['RequiresPHP']) ? $plugin_data['RequiresPHP'] : '';
            $requires_wp = isset($plugin_data['RequiresWP']) ? $plugin_data['RequiresWP'] : '';

            // Check compatibility
            $php_compatible = true;
            $wp_compatible = true;
            if ($requires_php && version_compare(PHP_VERSION, $requires_php, '<')) {
                $php_compatible = false;
            }
            if ($requires_wp && version_compare(get_bloginfo('version'), $requires_wp, '<')) {
                $wp_compatible = false;
            }

            // Check if plugin is abandoned (Pro feature - not updated in 2+ years)
            $wporg_info = self::get_plugin_wporg_info($plugin_slug);
            $is_abandoned = false;
            $wporg_last_updated = null;
            $tested_wp_version = null;

            if ($wporg_info) {
                $wporg_last_updated = isset($wporg_info['last_updated']) ? $wporg_info['last_updated'] : null;
                $tested_wp_version = isset($wporg_info['tested']) ? $wporg_info['tested'] : null;

                // Check if not updated in 2+ years
                if ($wporg_last_updated) {
                    $last_update_time = strtotime($wporg_last_updated);
                    $two_years_ago = strtotime('-2 years');
                    if ($last_update_time && $last_update_time < $two_years_ago) {
                        $is_abandoned = true;
                        $filters[] = 'Abandoned';
                    }
                }
            }

            $plugins_list[] = [
                'plugin_name' => $plugin_name,
                'plugin_slug' => $plugin_slug,
                'plugin_dir' => $plugin_dir,
                'plugin_file' => $plugin_file,
                'plugin_filters' => implode(', ', $filters),
                'current_version' => $current_version,
                'new_version' => $new_version,
                'has_update' => $has_update,
                'last_updated' => $last_updated,
                'requires_php' => $requires_php,
                'requires_wp' => $requires_wp,
                'php_compatible' => $php_compatible,
                'wp_compatible' => $wp_compatible,
                'is_abandoned' => $is_abandoned,
                'wporg_last_updated' => $wporg_last_updated,
                'tested_wp_version' => $tested_wp_version,
                'disable_updates' => isset($ultimate_security_options['security']['updates']['plugins_functionalities']['disable_updates']) ? sanitize_text_field(wp_unslash($ultimate_security_options['security']['updates']['plugins_functionalities']['disable_updates'])) : 0,
                'auto_updates' => isset($ultimate_security_options['security']['updates']['plugins_functionalities']['auto_updates']) ? sanitize_text_field(wp_unslash($ultimate_security_options['security']['updates']['plugins_functionalities']['auto_updates'])) : 0,
                'translation_updates' => isset($ultimate_security_options['security']['updates']['plugins_functionalities']['translation_updates']) ? sanitize_text_field(wp_unslash($ultimate_security_options['security']['updates']['plugins_functionalities']['translation_updates'])) : 0,
                'hide' => isset($ultimate_security_options['security']['updates']['plugins_functionalities']['hide']) ? sanitize_text_field(wp_unslash($ultimate_security_options['security']['updates']['plugins_functionalities']['hide'])) : 0,
            ];
        }

        return new WP_REST_Response($plugins_list, 200);
    }

    /**
     * Get plugin info from WordPress.org API
     *
     * @param string $plugin_slug Plugin slug
     * @return array|null Plugin info or null if not found
     */
    private static function get_plugin_wporg_info($plugin_slug)
    {
        // Skip if slug is just a file (single-file plugin)
        if ($plugin_slug === '.' || empty($plugin_slug)) {
            return null;
        }

        // Check cache first
        $cache_key = 'ultimate_security_wporg_' . md5($plugin_slug);
        $cached = get_transient($cache_key);
        if ($cached !== false) {
            return $cached === 'not_found' ? null : $cached;
        }

        // Fetch from WordPress.org API
        $url = 'https://api.wordpress.org/plugins/info/1.2/?action=plugin_information&request[slug]=' . urlencode($plugin_slug);

        $response = wp_remote_get($url, [
            'timeout' => 5,
            'sslverify' => true,
        ]);

        if (is_wp_error($response)) {
            // Cache the failure for 1 hour
            set_transient($cache_key, 'not_found', HOUR_IN_SECONDS);
            return null;
        }

        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        if (empty($data) || isset($data['error'])) {
            // Cache the not found for 1 hour
            set_transient($cache_key, 'not_found', HOUR_IN_SECONDS);
            return null;
        }

        $info = [
            'last_updated' => isset($data['last_updated']) ? $data['last_updated'] : null,
            'tested' => isset($data['tested']) ? $data['tested'] : null,
            'requires' => isset($data['requires']) ? $data['requires'] : null,
            'requires_php' => isset($data['requires_php']) ? $data['requires_php'] : null,
        ];

        // Cache for 24 hours
        set_transient($cache_key, $info, DAY_IN_SECONDS);

        return $info;
    }

    /**
     * Get themes information
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public static function get_themes_info(WP_REST_Request $request)
    {
        $all_themes = Utils::get_themes_cached();
        $active_theme = wp_get_theme();
        $update_themes = get_site_transient('update_themes');
        $auto_updates = get_option('auto_update_themes', []);
        $last_updated_times = get_option('ultimate_security_last_update_times', []);
        $themes_list = [];

        // Loop through each theme
        foreach ($all_themes as $theme_slug => $theme_data) {
            $theme_name = $theme_data->get('Name');
            $theme_dir = get_theme_root() . '/' . $theme_slug;

            // Get current and new version
            $current_version = $theme_data->get('Version');
            $new_version = '';
            $has_update = false;

            if (!empty($update_themes->response[$theme_slug])) {
                $has_update = true;
                $new_version = isset($update_themes->response[$theme_slug]['new_version'])
                    ? $update_themes->response[$theme_slug]['new_version']
                    : '';
            }

            // Determine filters
            $filters = [];

            if ($active_theme->get_stylesheet() === $theme_slug) {
                $filters[] = 'Active';
                $filters[] = 'type-1';
            } else {
                $filters[] = 'Inactive';
                $filters[] = 'type-2';
            }

            if ($has_update) {
                $filters[] = 'Update Available';
                $filters[] = 'type-3';
            }

            if (!in_array($theme_slug, $auto_updates)) {
                $filters[] = 'Auto-updates Disabled';
            } else {
                $filters[] = 'Auto-updates Enabled';
            }

            // Get last update timestamp
            $last_updated = isset($last_updated_times['themes'][$theme_slug])
                ? $last_updated_times['themes'][$theme_slug]
                : null;

            // Get PHP/WP requirements
            $requires_php = $theme_data->get('RequiresPHP');
            $requires_wp = $theme_data->get('RequiresWP');

            // Check compatibility
            $php_compatible = true;
            $wp_compatible = true;
            if ($requires_php && version_compare(PHP_VERSION, $requires_php, '<')) {
                $php_compatible = false;
            }
            if ($requires_wp && version_compare(get_bloginfo('version'), $requires_wp, '<')) {
                $wp_compatible = false;
            }

            $themes_list[] = [
                'theme_name' => $theme_name,
                'theme_slug' => $theme_slug,
                'theme_dir' => $theme_dir,
                'theme_filters' => implode(', ', $filters),
                'current_version' => $current_version,
                'new_version' => $new_version,
                'has_update' => $has_update,
                'last_updated' => $last_updated,
                'requires_php' => $requires_php,
                'requires_wp' => $requires_wp,
                'php_compatible' => $php_compatible,
                'wp_compatible' => $wp_compatible,
            ];
        }

        return new WP_REST_Response($themes_list, 200);
    }
}
