<?php

if ( ! class_exists( 'SSDThemeUpdateCheck' ) ) {
    class SSDThemeUpdateCheck
    {
        protected $theme_name = 'swifty-site-designer';
        protected $theme_version = '3.0.1';
        protected $server_version_request_url = 'https://stuff.swifty.online/stuff/data/get.php?do=get_version_data&code=ssd';

        public function __construct() {
            // to debug
            //set_site_transient('update_themes',null);

            add_filter( 'pre_set_site_transient_update_themes', array( $this, 'check' ) );
        }

        public function check( $updates ) {

            if( ! isset( $updates->checked ) ) return
                $updates;

            add_filter( 'http_request_args', array( $this, 'http_timeout' ), 10, 1 );

            $installed = wp_get_themes();

            if( isset( $installed[ $this->theme_name ] ) ) {
                $theme = $installed[ $this->theme_name ];
                $update_found = $this->remote_request( $this->server_version_request_url );
                if( $update_found ) {
                    $defaults = array( 'version' => '', 'url' => '', 'package' => '' );
                    $update_found = wp_parse_args( $update_found, $defaults );

                    if( version_compare( $this->theme_version, $update_found[ 'version' ], '<' ) ) {
                        // bingo, inject the update
                        if( $url = $update_found[ 'url' ] ) {
                            $update = array(
                                'url' => $url,
                                'new_version' => $update_found[ 'version' ],
                                'package' => $update_found[ 'package' ]
                            );
                            $updates->response[ $theme->Stylesheet ] = $update;
                        }
                    }
                }
            }

            remove_filter( 'http_request_args', array( $this, 'http_timeout' ) );

            return $updates;
        }

        public function http_timeout( $req ) {
            // increase timeout for api request
            $req[ 'timeout' ] = 300;
            return $req;
        }

        protected function remote_request( $url ) {

            if ( empty( $url ) ) {
                return false;
            }

            $request = wp_remote_request( $url );

            if ( $request['response']['code'] == 200 ) {
                return json_decode( $request['body'], true );
            }

            return false;
        }
    }

    new SSDThemeUpdateCheck();
}