<?php
/**
 * Plugin Update Checker
 *
 * Checks for plugin updates from the WordChat backend and enables automatic updates
 *
 * @package WordChat
 */

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

class WordChat_Updater {
    private $plugin_slug;
    private $plugin_file;
    private $version;
    private $api_url;

    public function __construct($plugin_file, $version) {
        $this->plugin_file = $plugin_file;
        $this->plugin_slug = plugin_basename($plugin_file);
        $this->version = $version;
        $this->api_url = WORDCHAT_API_URL . '/updates/check';

        // Hook into WordPress update system
        add_filter('pre_set_site_transient_update_plugins', array($this, 'check_for_updates'));
        add_filter('plugins_api', array($this, 'plugin_info'), 10, 3);
        add_filter('upgrader_process_complete', array($this, 'after_update'), 10, 2);

        // Report version to backend periodically
        add_action('admin_init', array($this, 'report_version_to_backend'));
    }

    /**
     * Check for plugin updates from our backend
     */
    public function check_for_updates($transient) {
        if (empty($transient->checked)) {
            return $transient;
        }

        $site_id = get_option('wordchat_site_id');
        $api_key = get_option('wordchat_api_key');

        $payload = array(
            'current_version' => $this->version,
            'plugin_slug' => WORDCHAT_PLUGIN_SLUG,
        );

        if ($site_id && $api_key) {
            $payload['site_id'] = $site_id;
            $payload['api_key'] = $api_key;
            $payload['domain'] = get_site_url();
            $payload['plugin_version'] = $this->version;
            $payload['wp_version'] = get_bloginfo('version');
            $payload['php_version'] = PHP_VERSION;
        }

        // Query backend for update info
        $response = wp_remote_post($this->api_url, array(
            'headers' => array('Content-Type' => 'application/json'),
            'body' => wp_json_encode($payload),
            'timeout' => 10
        ));

        if (is_wp_error($response)) {
            error_log('WordChat update check failed: ' . $response->get_error_message());
            return $transient;
        }

        $update_info = json_decode(wp_remote_retrieve_body($response), true);

        if (isset($update_info['authorized']) && $update_info['authorized'] === false) {
            return $transient;
        }

        if (!empty($update_info['update_available']) && $update_info['update_available'] === true) {
            $package_url = $update_info['download_url'] ?? ($update_info['package_url'] ?? null);
            if (!$package_url) {
                return $transient;
            }

            $plugin_obj = (object) array(
                'slug' => 'wordchat-pro',
                'new_version' => $update_info['latest_version'],
                'url' => $update_info['info_url'],
                'package' => $package_url,
                'tested' => $update_info['requires_wp_version'] ?? ($update_info['tested_wp_version'] ?? ''),
                'requires_php' => $update_info['requires_php_version'] ?? ($update_info['requires_php'] ?? ''),
            );

            $transient->response[$this->plugin_slug] = $plugin_obj;
        }

        return $transient;
    }

    /**
     * Provide plugin information for the "View details" link
     */
    public function plugin_info($result, $action, $args) {
        if ($action !== 'plugin_information') {
            return $result;
        }

        if ($args->slug !== 'wordchat-pro') {
            return $result;
        }

        $site_id = get_option('wordchat_site_id');
        $api_key = get_option('wordchat_api_key');

        $payload = array(
            'current_version' => $this->version,
            'plugin_slug' => WORDCHAT_PLUGIN_SLUG,
        );

        if ($site_id && $api_key) {
            $payload['site_id'] = $site_id;
            $payload['api_key'] = $api_key;
            $payload['domain'] = get_site_url();
            $payload['plugin_version'] = $this->version;
            $payload['wp_version'] = get_bloginfo('version');
            $payload['php_version'] = PHP_VERSION;
        }

        // Query backend for detailed plugin info
        $response = wp_remote_post($this->api_url, array(
            'headers' => array('Content-Type' => 'application/json'),
            'body' => wp_json_encode($payload),
            'timeout' => 10
        ));

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

        $update_info = json_decode(wp_remote_retrieve_body($response), true);

        if (!empty($update_info['latest_version'])) {
            $package_url = $update_info['download_url'] ?? ($update_info['package_url'] ?? null);

            $result = (object) array(
                'name' => 'Word.Chat Pro',
                'slug' => 'wordchat-pro',
                'version' => $update_info['latest_version'],
                'author' => '<a href="https://www.word.chat">Word.Chat</a>',
                'homepage' => 'https://www.word.chat',
                'download_link' => $package_url,
                'requires' => '5.5',
                'tested' => $update_info['requires_wp_version'] ?? ($update_info['tested_wp_version'] ?? ''),
                'requires_php' => $update_info['requires_php_version'] ?? ($update_info['requires_php'] ?? ''),
                'sections' => array(
                    'description' => 'AI-powered chatbot for WordPress that answers questions about your content using GPT-4.',
                    'changelog' => $this->get_changelog($update_info)
                ),
            );
        }

        return $result;
    }

    /**
     * Get changelog HTML
     */
    private function get_changelog($update_info) {
        $changelog_html = '<h4>Version ' . esc_html($update_info['latest_version']) . '</h4>';
        $changelog_html .= '<p>See full changelog at <a href="' . esc_url($update_info['changelog']) . '" target="_blank">word.chat/changelog</a></p>';
        return $changelog_html;
    }

    /**
     * After update completes, report new version to backend
     */
    public function after_update($upgrader_object, $options) {
        if ($options['action'] == 'update' && $options['type'] == 'plugin') {
            if (isset($options['plugins'])) {
                foreach ($options['plugins'] as $plugin) {
                    if ($plugin == $this->plugin_slug) {
                        // Plugin was updated, report new version
                        $this->report_version_to_backend(true);
                    }
                }
            }
        }
    }

    /**
     * Report plugin version to backend for tracking
     * Runs once per day or after updates
     */
    public function report_version_to_backend($force = false) {
        // Only report once per day unless forced
        $last_reported = get_option('wordchat_version_last_reported', 0);
        if (!$force && (time() - $last_reported) < DAY_IN_SECONDS) {
            return;
        }

        $site_id = get_option('wordchat_site_id');
        $api_key = get_option('wordchat_api_key');

        if (!$site_id || !$api_key) {
            return; // Not registered yet
        }

        global $wp_version;

        $data = array(
            'site_id' => $site_id,
            'api_key' => $api_key,
            'domain' => get_site_url(),
            'plugin_version' => $this->version,
            'php_version' => PHP_VERSION,
            'wp_version' => $wp_version
        );

        $response = wp_remote_post(WORDCHAT_API_URL . '/report-plugin-version', array(
            'headers' => array('Content-Type' => 'application/json'),
            'body' => json_encode($data),
            'timeout' => 10
        ));

        if (!is_wp_error($response)) {
            update_option('wordchat_version_last_reported', time());
        }
    }
}
