<?php
/**
 * License management class
 */
class Nietos_AI_License {

    /**
     * Get license server URL
     * Can be overridden in wp-config.php with:
     * define('NIETOS_LICENSE_SERVER_URL', 'https://your-shop.com');
     */
    private function get_license_server_url() {
        if (defined('NIETOS_LICENSE_SERVER_URL')) {
            return NIETOS_LICENSE_SERVER_URL;
        }
        // Default to nietos-ai.com
        return 'https://nietos-ai.com';
    }

    /**
     * Cache duration for license verification (24 hours)
     */
    const CACHE_DURATION = DAY_IN_SECONDS;

    /**
     * Check if premium license is active
     */
    public function is_premium_active() {
        $license_key = $this->get_license_key();

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

        // Check cache first
        $cache_key = 'nietos_license_valid_' . md5($license_key);
        $cached_status = get_transient($cache_key);

        if ($cached_status !== false) {
            return $cached_status === 'valid';
        }

        // Verify with server
        $is_valid = $this->verify_license_with_server($license_key);

        // Cache the result
        set_transient($cache_key, $is_valid ? 'valid' : 'invalid', self::CACHE_DURATION);

        return $is_valid;
    }

    /**
     * Get stored license key
     */
    public function get_license_key() {
        return get_option('nietos_ai_license_key', '');
    }

    /**
     * Save license key
     */
    public function save_license_key($license_key) {
        $license_key = sanitize_text_field($license_key);

        // Clear cache when key changes
        $this->clear_license_cache();

        return update_option('nietos_ai_license_key', $license_key);
    }

    /**
     * Verify license with server
     */
    private function verify_license_with_server($license_key) {
        $domain = $this->get_site_domain();
        $server_url = $this->get_license_server_url();

        $response = wp_remote_post($server_url . '/wp-json/nietos/v1/verify-license', array(
            'body' => json_encode(array(
                'license_key' => $license_key,
                'domain' => $domain,
            )),
            'headers' => array(
                'Content-Type' => 'application/json',
            ),
            'timeout' => 10,
            'sslverify' => true,
        ));

        if (is_wp_error($response)) {
            // Network error - assume valid if previously verified
            error_log('Nietos AI: License verification failed - ' . $response->get_error_message());
            return $this->was_previously_valid($license_key);
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);

        if (isset($body['valid']) && $body['valid'] === true) {
            // License is valid
            $this->mark_as_previously_valid($license_key);
            $this->save_license_info($body);
            return true;
        }

        // License is invalid
        return false;
    }

    /**
     * Activate license on this domain
     */
    public function activate_license($license_key) {
        $domain = $this->get_site_domain();
        $server_url = $this->get_license_server_url();

        $response = wp_remote_post($server_url . '/wp-json/nietos/v1/activate-license', array(
            'body' => json_encode(array(
                'license_key' => $license_key,
                'domain' => $domain,
            )),
            'headers' => array(
                'Content-Type' => 'application/json',
            ),
            'timeout' => 10,
            'sslverify' => true,
        ));

        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => __('Network error: ', 'nietos-ai') . $response->get_error_message(),
            );
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);

        if (isset($body['success']) && $body['success']) {
            // Activation successful
            $this->save_license_key($license_key);
            $this->clear_license_cache();

            return array(
                'success' => true,
                'message' => $body['message'] ?? __('License activated successfully', 'nietos-ai'),
            );
        }

        return array(
            'success' => false,
            'message' => $body['message'] ?? __('License activation failed', 'nietos-ai'),
        );
    }

    /**
     * Deactivate license from this domain
     */
    public function deactivate_license() {
        $license_key = $this->get_license_key();

        if (empty($license_key)) {
            return array(
                'success' => false,
                'message' => __('No license key found', 'nietos-ai'),
            );
        }

        $domain = $this->get_site_domain();
        $server_url = $this->get_license_server_url();

        $response = wp_remote_post($server_url . '/wp-json/nietos/v1/deactivate-license', array(
            'body' => json_encode(array(
                'license_key' => $license_key,
                'domain' => $domain,
            )),
            'headers' => array(
                'Content-Type' => 'application/json',
            ),
            'timeout' => 10,
            'sslverify' => true,
        ));

        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => __('Network error: ', 'nietos-ai') . $response->get_error_message(),
            );
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);

        if (isset($body['success']) && $body['success']) {
            // Deactivation successful
            $this->clear_license_cache();
            delete_option('nietos_ai_license_key');
            delete_option('nietos_ai_license_info');
            delete_option('nietos_ai_license_previously_valid');

            return array(
                'success' => true,
                'message' => $body['message'] ?? __('License deactivated successfully', 'nietos-ai'),
            );
        }

        return array(
            'success' => false,
            'message' => $body['message'] ?? __('License deactivation failed', 'nietos-ai'),
        );
    }

    /**
     * Get license information
     */
    public function get_license_info() {
        return get_option('nietos_ai_license_info', array());
    }

    /**
     * Save license information
     */
    private function save_license_info($info) {
        $license_info = array(
            'status' => $info['status'] ?? 'active',
            'expires' => $info['expires'] ?? 'lifetime',
            'activated_domain' => $info['activated_domain'] ?? '',
            'customer_email' => $info['customer_email'] ?? '',
            'last_checked' => current_time('mysql'),
        );

        update_option('nietos_ai_license_info', $license_info);
    }

    /**
     * Check if license was previously valid (for offline grace period)
     */
    private function was_previously_valid($license_key) {
        $previously_valid = get_option('nietos_ai_license_previously_valid', array());

        if (isset($previously_valid[$license_key])) {
            $last_valid = $previously_valid[$license_key];
            // Grace period of 7 days
            return (time() - $last_valid) < (7 * DAY_IN_SECONDS);
        }

        return false;
    }

    /**
     * Mark license as previously valid
     */
    private function mark_as_previously_valid($license_key) {
        $previously_valid = get_option('nietos_ai_license_previously_valid', array());
        $previously_valid[$license_key] = time();
        update_option('nietos_ai_license_previously_valid', $previously_valid);
    }

    /**
     * Get site domain
     */
    private function get_site_domain() {
        $domain = wp_parse_url(get_site_url(), PHP_URL_HOST);
        // Remove www
        $domain = preg_replace('/^www\./', '', $domain);
        return strtolower($domain);
    }

    /**
     * Clear license cache
     */
    public function clear_license_cache() {
        $license_key = $this->get_license_key();
        if (!empty($license_key)) {
            delete_transient('nietos_license_valid_' . md5($license_key));
        }
    }

    /**
     * Force refresh license status
     */
    public function refresh_license_status() {
        $this->clear_license_cache();
        return $this->is_premium_active();
    }
}
