<?php
if ( ! defined( 'ABSPATH' ) ) { exit; }

class Falcify_Updater {
    const METADATA_PATH = '/api/wordpress/plugin-update';
    const TRANSIENT_KEY = 'falcify_remote_plugin_meta';
    const TRANSIENT_TTL = 900;

    public static function init() {
        add_filter( 'pre_set_site_transient_update_plugins', array( __CLASS__, 'inject_update' ) );
        add_filter( 'plugins_api', array( __CLASS__, 'plugins_api' ), 20, 3 );
        add_filter( 'http_request_args', array( __CLASS__, 'tag_requests' ), 10, 2 );
    }

    protected static function plugin_basename() {
        return plugin_basename( FALCIFY_FILE );
    }

    protected static function metadata_url() {
        $base = untrailingslashit( (string) Falcify_Settings::get_value( 'saas_url' ) );
        if ( $base === '' ) {
            $base = 'https://falcify.fr';
        }
        return $base . self::METADATA_PATH;
    }

    protected static function get_remote_metadata( $force = false ) {
        if ( ! $force ) {
            $cached = get_site_transient( self::TRANSIENT_KEY );
            if ( is_array( $cached ) && ! empty( $cached['version'] ) ) {
                return $cached;
            }
        }

        $response = wp_remote_get( self::metadata_url(), array(
            'timeout' => 20,
            'headers' => array(
                'Accept' => 'application/json',
                'x-wp-site' => home_url(),
                'x-wp-plugin-version' => FALCIFY_VERSION,
            ),
        ) );

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

        $status = wp_remote_retrieve_response_code( $response );
        if ( $status < 200 || $status >= 300 ) {
            return null;
        }

        $body = json_decode( wp_remote_retrieve_body( $response ), true );
        if ( ! is_array( $body ) || empty( $body['version'] ) || empty( $body['download_url'] ) ) {
            return null;
        }

        set_site_transient( self::TRANSIENT_KEY, $body, self::TRANSIENT_TTL );
        return $body;
    }

    public static function inject_update( $transient ) {
        if ( ! is_object( $transient ) ) {
            $transient = new stdClass();
        }

        $meta = self::get_remote_metadata();
        if ( ! $meta ) {
            return $transient;
        }

        if ( version_compare( (string) $meta['version'], FALCIFY_VERSION, '<=' ) ) {
            return $transient;
        }

        $plugin = self::plugin_basename();
        if ( ! isset( $transient->response ) || ! is_array( $transient->response ) ) {
            $transient->response = array();
        }

        $transient->response[ $plugin ] = (object) array(
            'slug' => dirname( $plugin ),
            'plugin' => $plugin,
            'new_version' => (string) $meta['version'],
            'tested' => (string) ( $meta['tested'] ?? '' ),
            'requires' => (string) ( $meta['requires'] ?? '' ),
            'requires_php' => (string) ( $meta['requires_php'] ?? '' ),
            'package' => esc_url_raw( (string) $meta['download_url'] ),
            'url' => esc_url_raw( (string) ( $meta['homepage'] ?? 'https://falcify.fr' ) ),
        );

        return $transient;
    }

    public static function plugins_api( $result, $action, $args ) {
        if ( $action !== 'plugin_information' || empty( $args->slug ) || $args->slug !== 'falcify-connector' ) {
            return $result;
        }

        $meta = self::get_remote_metadata( true );
        if ( ! $meta ) {
            return $result;
        }

        return (object) array(
            'name' => 'Falcify Connector',
            'slug' => 'falcify-connector',
            'version' => (string) $meta['version'],
            'author' => '<a href="https://www.techniweb-agence.fr/">Techniweb</a>',
            'homepage' => (string) ( $meta['homepage'] ?? 'https://falcify.fr' ),
            'requires' => (string) ( $meta['requires'] ?? '' ),
            'tested' => (string) ( $meta['tested'] ?? '' ),
            'requires_php' => (string) ( $meta['requires_php'] ?? '' ),
            'download_link' => esc_url_raw( (string) $meta['download_url'] ),
            'sections' => array(
                'description' => 'Connecte WordPress à Falcify et propose un bouton « Lire en FALC » sur le site public.',
                'changelog' => (string) ( $meta['changelog'] ?? '' ),
            ),
        );
    }

    public static function tag_requests( $args, $url ) {
        $watched = array(
            self::metadata_url(),
            untrailingslashit( (string) Falcify_Settings::get_value( 'saas_url' ) ) . '/api/wordpress/plugin-download',
        );

        $should_tag = false;
        foreach ( $watched as $w ) {
            if ( $w !== '' && strpos( $url, $w ) === 0 ) {
                $should_tag = true;
                break;
            }
        }
        if ( $should_tag ) {
            if ( empty( $args['headers'] ) || ! is_array( $args['headers'] ) ) {
                $args['headers'] = array();
            }
            $args['headers']['x-wp-site'] = home_url();
            $args['headers']['x-wp-plugin-version'] = FALCIFY_VERSION;
            $args['headers']['Accept'] = 'application/json, */*';
        }

        return $args;
    }
}