<?php
/**
 * License Verification System for Laravel
 * Product: Ekinor
 * Generated: 2025-12-03 09:53:11
 */

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class LaravelLicenseVerifier
{
    protected $apiUrl = 'check.kaaliicore.com/api/license/verify';
    protected $productSlug = 'ekinor';
    protected $verificationKey = '63935b5e0df0a72677c2d3a192a7a40ebcff24f6f19b41bc645b52e6a3d74abb';
    protected $apiToken = 'bad2a84a658805fd72c70eaad96078a0706ce805248cd2add3349cb60e3a15a5';

    /**
     * Verify license with purchase code
     * This method sends a single request to our system which handles both Envato and database verification
     */
    public function verifyLicense(string $purchaseCode, ?string $domain = null): array
    {
        try {
            // Send single request to our system
            $result = $this->verifyWithOurSystem($purchaseCode, $domain);
            
            if ($result['valid']) {
                return $this->createLicenseResponse(true, $result['message'], $result['data']);
            } else {
                return $this->createLicenseResponse(false, $result['message']);
            }

        } catch (\Exception $e) {
            return $this->createLicenseResponse(false, 'Verification failed: ' . $e->getMessage());
        }
    }

    /**
     * Verify with our license system
     */
    protected function verifyWithOurSystem(string $purchaseCode, ?string $domain = null): array
    {
        try {
            $response = Http::timeout(15)
                ->withHeaders([
                    'Content-Type' => 'application/x-www-form-urlencoded',
                    'User-Agent' => 'LicenseVerifier/1.0',
                    'Authorization' => 'Bearer ' . $this->apiToken
                ])
                ->asForm()
                ->post($this->apiUrl, [
                    'purchase_code' => $purchaseCode,
                    'product_slug' => $this->productSlug,
                    'domain' => $domain,
                    'verification_key' => $this->verificationKey
                ]);

            if ($response->successful()) {
                $data = $response->json();

                return $this->createLicenseResponse(
                    $data['valid'] ?? false,
                    $data['message'] ?? 'Verification completed',
                    $data
                );
            }

            return $this->createLicenseResponse(false, 'Unable to verify license');
        } catch (\Exception $e) {
            // Log::error('License API network error', ['error' => $e->getMessage()]);
            return $this->createLicenseResponse(false, 'Network error: ' . $e->getMessage());
        }
    }

    /**
     * Create standardized response
     */
    protected function createLicenseResponse(bool $valid, string $message, ?array $data = null): array
    {
        return [
            'valid' => $valid,
            'message' => $message,
            'data' => $data,
            'verified_at' => now()->toISOString(),
            'product' => $this->productSlug
        ];
    }

    /**
     * Cache license verification result
     */
    public function cacheLicenseResult(string $purchaseCode, array $result, int $minutes = 60): void
    {
        $cacheKey = 'license_result_' . md5($purchaseCode . $this->productSlug);
        Cache::put($cacheKey, $result, now()->addMinutes($minutes));
    }

    /**
     * Get cached license result
     */
    public function getCachedLicenseResult(string $purchaseCode): ?array
    {
        $cacheKey = 'license_result_' . md5($purchaseCode . $this->productSlug);
        return Cache::get($cacheKey);
    }

    /**
     * Clear license cache
     */
    public function clearLicenseCache(string $purchaseCode): void
    {
        $cacheKey = 'license_result_' . md5($purchaseCode . $this->productSlug);
        Cache::forget($cacheKey);
    }
}

// Usage example:
/*
// In your controller or service
use App\Services\LaravelLicenseVerifier;

$verifier = new LaravelLicenseVerifier();
$result = $verifier->verifyLicense('YOUR_PURCHASE_CODE', request()->getHost());

if ($result['valid']) {
    // License is valid
    $verifier->cacheLicenseResult('YOUR_PURCHASE_CODE', $result);
    return response()->json(['app.Status' => 'success', 'message' => 'License verified']);
} else {
    // License invalid
    return response()->json(['app.Status' => 'error', 'message' => $result['message']], 403);
}
*/
?>