<?php

namespace Breakdance\AI;

use Breakdance\Licensing\EDD_SL_Plugin_Updater;
use Breakdance\Licensing\EddApi;
use function Breakdance\Data\get_global_option;
use function Breakdance\Data\set_global_option;
use function Breakdance\Licensing\get_option_receive_beta_updates;

add_action('init', function () {
    if (!is_admin()) return;

    if (!function_exists('get_plugin_data')) {
        require_once(ABSPATH . 'wp-admin/includes/plugin.php');
    }

    $path = path_join(dirname(__FILE__), 'breakdance-ai.php');
    $pluginData = get_plugin_data( $path );
    $version = $pluginData['Version'];
    $license_key = \Breakdance\AI\getLicenseKey();

    if (!$license_key) return;

    /** @psalm-suppress UndefinedClass */
    (new EDD_SL_Plugin_Updater(
        "https://breakdance.com",
        $path,
        [
            'version' => $version,
            'license' => $license_key,
            'item_id' => BREAKDANCE_AI_EDD_ITEM_ID,
            'author' => 'Soflyy',
            // set to true if you wish customers to receive update notifications of beta releases
            'beta' => get_option_receive_beta_updates(),
        ]
    ));
});

function getLicenseKey() {
    return get_global_option('ai_license_key');
}

function setLicenseKey($license_key) {
    set_global_option('ai_license_key', $license_key);
    setLicenseKeyStatus(null);
    activateLicenseKey($license_key);
}

function getLicenseKeyStatus() {
    return get_global_option('ai_license_key_status');
}

function setLicenseKeyStatus($license_key_status) {
    set_global_option('ai_license_key_status', $license_key_status);
}

function fetchLicenseKeyStatus() {
    $eddApi = new \Breakdance\Licensing\EddApi(get_site_url());
    $licenseKey = getLicenseKey();

    if (!$licenseKey) {
        setLicenseKeyStatus(null);
        return;
    }

    $licenseData = $eddApi->fetchLicenseInfo(
        $licenseKey,
        BREAKDANCE_AI_EDD_ITEM_ID
    );

    if (!$licenseData) {
        setLicenseKeyStatus('invalid');
    } else {
        setLicenseKeyStatus($licenseData['license']);
    }
}

function activateLicenseKey($license_key) {
    $licenseKeyStatus = getLicenseKeyStatus();
    if ($licenseKeyStatus === 'valid') return;

    $eddApi = new \Breakdance\Licensing\EddApi(get_site_url());

    $response = $eddApi->activateLicense(
        $license_key,
        BREAKDANCE_AI_EDD_ITEM_ID
    );

    if ($response['success']) {
        afterActivation();
    }

    fetchLicenseKeyStatus();
}

function afterActivation() {
    $domain = str_replace('www.', '', parse_url(get_site_url(), PHP_URL_HOST));

    \Breakdance\Licensing\Events\log(
        BREAKDANCE_AI_OWAUID,
        'AI Plugin Activated',
        [
            'domain' => $domain
        ]
    );
}
