<?php
/**
 * WordPress-style auto-update checker for Buy With Digikala plugin
 * 
 * This updater expects:
 * - Plugin folder name: buy-with-digikala/ (NO version in folder name)
 * - ZIP filename on server: buy-with-digikala-{version}.zip (WITH version)
 * - Plugin slug: buy-with-digikala/buy-with-digikala.php
 * - Metadata URL: https://plugins.digifyprime.net/bwdk/metadata.json
 */
namespace BWDK\Support;

use stdClass;

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

class UpdateChecker {

    /**
     * Plugin file path (e.g., buy-with-digikala/buy-with-digikala.php)
     *
     * @var string
     */
    private static $plugin_file;

    /**
     * Initialize the update checker
     */
    public static function init() {
        if (!defined('BWDK_PLUGIN_FILE') || !defined('BWDK_VERSION') || !defined('BWDK_UPDATE_METADATA_URL')) {
            error_log('BWDK update: Required constants not defined');
            return;
        }

        self::$plugin_file = plugin_basename(BWDK_PLUGIN_FILE);

        // Hook into WordPress update system
        add_filter('pre_set_site_transient_update_plugins', [__CLASS__, 'check_for_update'], 10, 1);
        add_filter('plugins_api', [__CLASS__, 'plugins_api'], 10, 3);
    }

    /**
     * Check for plugin updates
     *
     * @param object $transient The update_plugins transient object
     * @return object Modified transient object
     */
    public static function check_for_update($transient) {
        // Early return if checked array is empty (WordPress hasn't checked plugins yet)
        if (empty($transient->checked)) {
            return $transient;
        }

        // Ensure response array exists
        if (!isset($transient->response)) {
            $transient->response = [];
        }

        // Fetch remote metadata
        $remote = self::fetch_metadata();
        if (!$remote) {
            return $transient;
        }

        // Compare versions
        if (version_compare($remote->version, BWDK_VERSION, '>')) {
            // Build update object
            $update_object = (object) [
                'slug'        => $remote->slug ?? self::$plugin_file,
                'plugin'      => self::$plugin_file,
                'new_version' => $remote->version,
                'url'         => $remote->homepage ?? '',
                'package'     => $remote->download_url ?? '',
                'tested'      => $remote->tested ?? '',
                'requires'    => $remote->requires ?? '',
            ];

            // Add optional fields
            if (!empty($remote->requires_php)) {
                $update_object->requires_php = $remote->requires_php;
            }

            // Add to response array
            $transient->response[self::$plugin_file] = $update_object;
        }

        return $transient;
    }

    /**
     * Handle plugins_api filter for "View version X details" popup
     *
     * @param false|object|array $result The result object or array
     * @param string $action The type of information being requested
     * @param object $args Plugin API arguments
     * @return false|object Result object or false
     */
    public static function plugins_api($result, $action, $args) {
        // Only handle plugin_information action
        if ($action !== 'plugin_information') {
            return $result;
        }

        // Check if this is our plugin
        // WordPress may pass slug as:
        // 1. Full plugin file: "buy-with-digikala/buy-with-digikala.php"
        // 2. Folder name: "buy-with-digikala"
        // 3. Metadata slug from metadata.json: "buy-with-digikala/buy-with-digikala.php"
        if (empty($args->slug)) {
            return $result;
        }

        $plugin_file = self::$plugin_file; // e.g., "buy-with-digikala/buy-with-digikala.php"
        $plugin_slug = dirname($plugin_file); // e.g., "buy-with-digikala"
        
        // Check if the requested slug matches our plugin
        $is_our_plugin = (
            $args->slug === $plugin_file ||
            $args->slug === $plugin_slug
        );

        // Fetch metadata once (we'll use it for both slug check and response)
        $remote = self::fetch_metadata();
        if (!$remote) {
            return $result;
        }

        // Also check against metadata slug if available
        if (!$is_our_plugin && !empty($remote->slug)) {
            $is_our_plugin = (
                $args->slug === $remote->slug ||
                $args->slug === dirname($remote->slug)
            );
        }

        if (!$is_our_plugin) {
            return $result;
        }

        // Build response object
        $response = new stdClass();
        $response->name = $remote->name ?? 'خرید با دیجی‌کالا (BWDK)';
        $response->slug = dirname(self::$plugin_file); // e.g., "buy-with-digikala"
        $response->version = $remote->version ?? '';
        $response->author = $remote->author ?? '';
        $response->homepage = $remote->homepage ?? '';
        $response->requires = $remote->requires ?? '';
        $response->tested = $remote->tested ?? '';
        $response->last_updated = $remote->last_updated ?? '';
        $response->download_link = $remote->download_url ?? '';

        // Sections: description and changelog
        // Handle both object and array formats for sections
        $response->sections = [];
        if (isset($remote->sections)) {
            if (is_object($remote->sections)) {
                if (!empty($remote->sections->description)) {
                    $response->sections['description'] = $remote->sections->description;
                }
                if (!empty($remote->sections->changelog)) {
                    $response->sections['changelog'] = $remote->sections->changelog;
                }
            } elseif (is_array($remote->sections)) {
                if (!empty($remote->sections['description'])) {
                    $response->sections['description'] = $remote->sections['description'];
                }
                if (!empty($remote->sections['changelog'])) {
                    $response->sections['changelog'] = $remote->sections['changelog'];
                }
            }
        }

        return $response;
    }

    /**
     * Fetch and parse remote metadata.json
     *
     * @return false|object Parsed metadata object or false on failure
     */
    private static function fetch_metadata() {
        if (!defined('BWDK_UPDATE_METADATA_URL')) {
            error_log('BWDK update: BWDK_UPDATE_METADATA_URL constant not defined');
            return false;
        }

        $response = wp_remote_get(BWDK_UPDATE_METADATA_URL, [
            'timeout' => 10,
        ]);

        // Handle errors
        if (is_wp_error($response)) {
            error_log('BWDK update: HTTP error - ' . $response->get_error_message());
            return false;
        }

        $code = wp_remote_retrieve_response_code($response);
        if ($code !== 200) {
            error_log('BWDK update: HTTP status code ' . $code);
            return false;
        }

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

        // Validate JSON
        if (json_last_error() !== JSON_ERROR_NONE) {
            error_log('BWDK update: Invalid JSON - ' . json_last_error_msg());
            return false;
        }

        // Ensure we have an object
        if (!is_object($data)) {
            error_log('BWDK update: Metadata is not an object');
            return false;
        }

        // Validate required fields
        if (empty($data->version) || empty($data->download_url)) {
            error_log('BWDK update: Missing required fields (version or download_url)');
            return false;
        }

        return $data;
    }
}

