<?php

namespace FleekDash\Controllers\License;

// Load debug helpers
if (!function_exists('fleekdash_log_debug')) {
    require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/debug-helpers.php';
}

/**
 * License Helpers
 *
 * Utility methods for license operations
 *
 * @package FleekDash\Controllers\License
 */
class LicenseHelpers
{
    /**
     * Returns the canonical license row (Supabase `licenses` shape) from stored option data.
     *
     * {@see LicenseAPIClient::fetchLicense()} persists a wrapper:
     * `{ valid, license: { deal_tier_id, ... }, instances, message }`.
     * Feature tier logic expects `deal_tier_id` on this row — not on the wrapper.
     *
     * @param array<string, mixed>|mixed $stored Raw `fleekdash_v2_license_data` option value
     * @return array<string, mixed>|null Canonical license row, or null if unusable
     */
    public static function getCanonicalLicenseRecord($stored): ?array
    {
        $result = null;

        if ($stored !== null && \is_array($stored)) {
            $inner = (isset($stored['license']) && \is_array($stored['license']))
                ? $stored['license']
                : null;

            if ($inner !== null && isset($inner['deal_tier_id'])) {
                $result = $inner;
            } elseif (isset($stored['deal_tier_id'])) {
                $result = $stored;
            } elseif ($inner !== null) {
                $result = $inner;
            } else {
                $result = $stored;
            }
        }

        return $result;
    }

    /**
     * Calculate expiration date from license data
     *
     * @param array|null $license_data License data
     * @return string Expiration date (Y-m-d format) or 'Never' for LTD
     */
    public static function calculateExpirationDate($license_data = null): string
    {
        if (!$license_data) {
            $license_data = \get_option('fleekdash_v2_license_data');
        }

        if (\is_array($license_data)) {
            $canonical = self::getCanonicalLicenseRecord($license_data);
            $license_data = $canonical ?? $license_data;
        }

        fleekdash_log_debug('FleekDash V2: Calculating expiration for license data: ' . print_r($license_data, true));

        $result = null;

        if (!$license_data || !is_array($license_data)) {
            fleekdash_log_debug('FleekDash V2: No license data found, using default 1 year expiration');
            $result = date('Y-m-d', strtotime('+1 year'));
        } else {
            $result = self::resolveExpirationFromExpiresAt($license_data);
            if ($result === null) {
                $result = self::resolveExpirationFromCreatedAt($license_data);
            }
            if ($result === null) {
                fleekdash_log_debug('FleekDash V2: Using fallback 1 year from now');
                $result = date('Y-m-d', strtotime('+1 year'));
            }
        }

        return $result;
    }

    /**
     * @param array<string, mixed> $license_data
     */
    private static function resolveExpirationFromExpiresAt(array $license_data): ?string
    {
        $resolved = null;
        if (array_key_exists('expires_at', $license_data)) {
            if ($license_data['expires_at'] === null) {
                fleekdash_log_debug('FleekDash V2: License has null expires_at, treating as LTD - returning "Never"');
                $resolved = 'Never';
            } elseif (!empty($license_data['expires_at'])) {
                $expires_at = $license_data['expires_at'];
                if (strtotime($expires_at)) {
                    fleekdash_log_debug('FleekDash V2: Using explicit expiration date: ' . $expires_at);
                    $resolved = date('Y-m-d', strtotime($expires_at));
                }
            }
        }

        return $resolved;
    }

    /**
     * @param array<string, mixed> $license_data
     */
    private static function resolveExpirationFromCreatedAt(array $license_data): ?string
    {
        $resolved = null;
        if (isset($license_data['created_at']) && !empty($license_data['created_at'])) {
            $created_at = $license_data['created_at'];
            if (strtotime($created_at)) {
                $calculated_expiry = date('Y-m-d', strtotime($created_at . ' +1 year'));
                fleekdash_log_debug('FleekDash V2: Calculated expiration from created_at: ' . $calculated_expiry);
                $resolved = $calculated_expiry;
            }
        }

        return $resolved;
    }

    /**
     * Check permissions - always return true
     * Let AuthMiddleware handle authentication
     */
    public static function checkPermissions(): bool
    {
        return true;
    }

    /**
     * Build REST payload when activate_license_instance RPC does not succeed.
     * Preserves server message (e.g. seat limit) and optional usage fields.
     *
     * @param int $statusCode HTTP status from Supabase/PostgREST
     * @param array|null $body Decoded JSON body
     * @return array<string, mixed>
     */
    public static function buildActivationFailurePayload(int $statusCode, $body): array
    {
        $payload = [
            'activated' => false,
            'message' => 'Unable to activate license. Please try again.',
            'code' => 'activation_failed',
        ];

        if (!is_array($body)) {
            if ($statusCode !== 200) {
                $payload['message'] = 'License server returned an error (HTTP ' . $statusCode . ').';
            }
            return $payload;
        }

        if (isset($body['message']) && is_string($body['message']) && $body['message'] !== '') {
            $payload['message'] = $body['message'];
        }

        if (isset($body['code']) && is_string($body['code']) && $body['code'] !== '') {
            $payload['code'] = $body['code'];
        }

        $optionalKeys = [
            'activation_limit',
            'activation_usage',
            'max_activations',
            'current_activations',
        ];
        foreach ($optionalKeys as $key) {
            if (array_key_exists($key, $body)) {
                $payload[$key] = $body[$key];
            }
        }

        $defaultMsg = 'Unable to activate license. Please try again.';
        if (
            $payload['message'] === $defaultMsg
            && isset($body['activation_limit'], $body['activation_usage'])
        ) {
            $payload['message'] = sprintf(
                'This license has reached its activation limit (%s of %s sites).',
                $body['activation_usage'],
                $body['activation_limit']
            );
        }

        return $payload;
    }
}
