<?php

function rental_get_upgrade_information($slug) {
    // Trying to get from cache first
    if ( !$remote = get_transient("rental_upgrade_$slug")) {
        // FIX SSL SNI
        $filter_add = true;
        if (function_exists('curl_version')) {
            $version = curl_version();
            if (version_compare($version['version'], '7.18', '>=')) {
                $filter_add = false;
            }
        }
        if ($filter_add) {
            add_filter('https_ssl_verify', '__return_false');
        }

        
        $request = wp_remote_get('https://rentopian.com/wp-plugin/rentopian-sync.json', [
            'timeout' => 10,
            'headers' => [
                'Accept' => 'application/json'
            ]
        ]);


        // info.json is the file with the actual plugin information on your server
        // $request = wp_remote_get('https://rentprotheme.com/theme-assets/plugins/rentopian-sync.json', [
        //     'timeout' => 10,
        //     'headers' => [
        //         'Accept' => 'application/json'
        //     ]
        // ]);

        if ($filter_add) {
            remove_filter('https_ssl_verify', '__return_false');
        }

        if (is_wp_error($request) || !isset($request['response']) || !isset($request['response']['code']) || $request['response']['code'] != 200 ||
            !isset($request['body']) || empty($remote = json_decode($request['body']))) {
            return false;
        }
//        $remote = json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $remote['body']) );
        set_transient("rental_upgrade_$slug", $remote, 7200); // 2 hours cache
    }

    return $remote;
}

function rental_plugin_info($res, $action, $args) {
    // Do nothing if this is not about getting plugin information
    if ($action !== 'plugin_information') {
        return $res;
    }

    $slug = plugin_basename(RENTOPIAN_SYNC_PATH . '/rentopian-sync.php');
    // Do nothing if it is not our plugin
    if ( !isset($args->slug) || $slug !== $args->slug) {
        return $res;
    }

    if ($remote = rental_get_upgrade_information($slug)) {
        $res = new stdClass();
        $res->name = $remote->name;
        $res->slug = $slug;
        $res->version = $remote->version;
        $res->tested = $remote->tested;
        $res->requires = $remote->requires;
        $res->author = $remote->author;
        $res->author_profile = 'https://rentopian.com'; // WordPress.org profile
        $res->download_link = $remote->download_url;
        $res->trunk = $remote->download_url;
        $res->last_updated = $remote->last_updated;
        $res->sections = [
            'description' => $remote->sections->description, // description tab
            'installation' => $remote->sections->installation, // installation tab
            'changelog' => $remote->sections->changelog, // changelog tab
            // you can add your custom sections (tabs) here
        ];

        // in case you want the screenshots tab, use the following HTML format for its content:
        // <ol><li><a href="IMG_URL" target="_blank" rel="noopener noreferrer"><img src="IMG_URL" alt="CAPTION" /></a><p>CAPTION</p></li></ol>
        if ( !empty($remote->sections->screenshots)) {
            $res->sections['screenshots'] = $remote->sections->screenshots;
        }

        $image_folder = plugins_url(plugin_basename(RENTOPIAN_SYNC_PATH . '/assets/images'));
        $res->banners = array(
            'low' => $image_folder . '/banner-772x250.png',
            'high' => $image_folder . '/banner-1544x500.png'
        );
    }

    return $res;
}
add_filter('plugins_api', 'rental_plugin_info', 20, 3);


function rental_push_update($transient) {
    $slug = plugin_basename(RENTOPIAN_SYNC_PATH . '/rentopian-sync.php');

    // Extra check for 3rd plugins
    if (isset($transient->response[$slug])) {
        return $transient;
    }

    // your installed plugin version should be on the line below! You can obtain it dynamically of course
    if (($remote = rental_get_upgrade_information($slug)) && version_compare(RENTOPIAN_SYNC_VERSION, $remote->version, '<') && version_compare($remote->requires, get_bloginfo('version'), '<')) {
        $res = new stdClass();
        $res->slug = $slug;
        $res->plugin = $slug;
        $res->new_version = $remote->version;
        $res->tested = $remote->tested;
        $res->package = $remote->download_url;
        $res->url = $remote->homepage;
        $transient->response[$slug] = $res;
    }

    return $transient;
}
add_filter('pre_set_site_transient_update_plugins', 'rental_push_update');


function rental_pre_upgrade_filter($reply, $package, $updater) {
    $slug = plugin_basename(RENTOPIAN_SYNC_PATH . '/rentopian-sync.php');

    // Do nothing if it is not our plugin
    if (( !isset($updater->skin->plugin) || $slug !== $updater->skin->plugin) && ( !isset($updater->skin->plugin_info) || !$updater->skin->plugin_info['Name'] === "Rentopian Sync")) {
        return $reply;
    }

    if ( !$updater->fs_connect([WP_CONTENT_DIR])) {
        return new WP_Error('no_credentials', esc_html__("Error! Can't connect to filesystem", 'rentopian-sync'));
    }

    $updater->strings['downloading_package_url'] = esc_html__('Getting download link...', 'rentopian-sync');
    $updater->skin->feedback('downloading_package_url');

    if ( !$remote = rental_get_upgrade_information($slug)) {
        return new WP_Error('no_credentials', esc_html__('Download link could not be retrieved', 'rentopian-sync'));
    }

    $updater->strings['downloading_package'] = esc_html__('Downloading package...', 'rentopian-sync');
    $updater->skin->feedback('downloading_package');

    $downloaded_archive = download_url($remote->download_url);
    if (is_wp_error($downloaded_archive)) {
        return $downloaded_archive;
    }

    // WP will use same name for plugin directory as archive name, so we have to rename it
    $downloaded_archive_info = pathinfo($downloaded_archive);
    if ($downloaded_archive_info['filename'] !== 'rentopian-sync') {
        $new_archive_name = $downloaded_archive_info['dirname'] . '/rentopian-sync.' . $downloaded_archive_info['extension'];
        if (rename($downloaded_archive, $new_archive_name)) {
            $downloaded_archive = $new_archive_name;
        }
    }

    return $downloaded_archive;
}
//add_filter('upgrader_pre_download', 'rental_pre_upgrade_filter', 10, 3);


function rental_after_update($updater, $options) {
    if (isset($options['action'] ) && $options['action'] == 'update' && $options['type'] === 'plugin') {
        // just clean the cache when new plugin version is installed
        delete_transient('rental_upgrade_' . plugin_basename(RENTOPIAN_SYNC_PATH . '/rentopian-sync.php'));
    }
}
add_action('upgrader_process_complete', 'rental_after_update', 10, 2);



function rental_force_correct_folder( $source, $remote, $upgrader, $hook_extra ) {
    if (
        isset( $hook_extra['plugin'] )
        && $hook_extra['plugin'] === plugin_basename( RENTOPIAN_SYNC_PATH . '/rentopian-sync.php' )
    ) {
        $correct = dirname($source) . '/rentopian-sync';
        if ( basename($source) !== 'rentopian-sync' ) {
            rename($source, $correct);
            return $correct;
        }
    }
    return $source;
}
add_filter( 'upgrader_source_selection', 'rental_force_correct_folder', 10, 4 );