<?php

namespace Clonable\Objects;

use Clonable\Models\Site;

defined('ABSPATH') || exit;

/**
 * Class with constants and function that are used throughout
 * the entire plugin.
 */
class ClonableConfig
{
    const WOOCOMMERCE_QUERY_ID = "clonable-excluded-%s";
    const WOOCOMMERCE_TAXONOMY = 'clonable_excluded_products';
    const UT_API_ENDPOINT = 'ut.api.clonable.net';
    const TRANSLATIONS_API_ENDPOINT = 'translations.api.clonable.net';
    const SERVER_IP = '89.41.171.180';
    const SERVER_IPV6 = '2a01:7c8:e001:d9:0:0:0:e778';
    const CP_API_ENDPOINT = 'api.clonable.net';
    const MODULES_ENDPOINT = 'modules.clonable.net';
    const ORIGINAL_SHOP = 'original';

    /**
     * Return the Clonable clones from the WordPress option.
     * @return array
     */
    public static function get_clones()
    {
        $site = self::get_site();
        if (empty($site)) {
            return [];
        }
        return $site->get_clones();
    }

    /**
     * Retrieves the Clonable site from the WordPress option.
     * @return Site|null
     */
    public static function get_site()
    {
        $response = get_option("clonable_site");
        if (empty($response)) {
            return null;
        }
        return new Site($response);
    }

    /**
     * Gets the current clone domain including subfolder.
     * This value is unique per clone.
     * @return string returns the value of ClonableConfig::ORIGINAL_SHOP for the original site,
     * or return the domain + subfolder for the clone.
     */
    public static function current_clonable_domain()
    {
        // phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        $server_data = $_SERVER;
        // phpcs:enable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized

        $domain = ($server_data['HTTP_CLONABLE_CLONE_DOMAIN'] ?? null);
        if (empty($domain)) {
            // return a static string when it's the original shop.
            // allows for easier checks in different places.
            return self::ORIGINAL_SHOP;
        }
        $subfolder = ($server_data['HTTP_CLONABLE_CLONE_SUBFOLDER'] ?? '');
        // each clone is uniquely identified by their domain in combination with subfolder.
        return $domain . $subfolder;
    }

    /**
     * Get the clone ID based on the current URL or refererrer URL.
     * @return string|null
     */
    public static function get_clone_id_by_current_url(): ?string
    {
        $clones = self::get_clones();
        if (empty($clones)) {
            return null;
        }

        $host_header = $_SERVER['HTTP_X_FORWARDED_HOST'] ?? ($_SERVER['HTTP_HOST'] ?? ($_SERVER['SERVER_NAME'] ?? ''));
        $sanitized_host = str_replace('www.', '', $host_header);

        // Get all clones for this domain.
        $domain_matches = [];
        foreach ($clones as $clone) {
            if ($clone['domain'] === $sanitized_host) {
                $domain_matches[] = $clone;
            }
        }

        if (empty($domain_matches)) {
            return null;
        }

        if (count($domain_matches) === 1 && empty($domain_matches[0]['subfolder_clone'])) {
            return $domain_matches[0]['id'];
        }

        // More than 1 domain match basically means that there are multiple subfolder clones.
        foreach ($domain_matches as $clone) {
            if ($clone['is_subfolder_clone']) {
                $subfolder = trim($clone['subfolder_clone'], '/');
                $request_uri = $_SERVER['HTTP_REFERER'] ?? '/';
                $request_path = parse_url($request_uri, PHP_URL_PATH);
                if (strpos($request_path, $subfolder) !== false) {
                    return $clone['id'];
                }
            }
        }

        return null;
    }
}
