<?php

namespace App\Core\License;

use App\Core\Contracts\LicenseContract;

class LicenseValidator implements LicenseContract
{
    protected string $publicKey;
    protected string $licensePath;

    public function __construct()
    {
        $this->licensePath = storage_path('laraoffice/license.json');
        $this->publicKey = file_get_contents(
            storage_path('laraoffice/public.key')
        );
    }

    /**
     * Load decoded license (used for expiry, modules, etc.)
     */
    public function load(): array
    {
        return (new LicenseLoader())->load();
    }

    /**
     * Validate license signature
     * NOTE: $license param exists ONLY to satisfy the interface
     * Raw JSON is used for cryptographic verification
     */
   public function validate(array $license): bool
    {
        if (!isset($license['signature'])) {
            return false;
        }

        // 1️⃣ Extract signature
        $signature = base64_decode($license['signature']);

        // 2️⃣ Remove signature from payload
        $payload = $license;
        unset($payload['signature']);

        // 3️⃣ Re-encode EXACTLY like admin did
        // ⚠️ No flags, no pretty print, no sorting
        $payloadJson = json_encode($payload);

        // Optional debug
        file_put_contents(
            storage_path('laraoffice/debug.txt'),
            "PAYLOAD USED FOR VERIFY:\n{$payloadJson}\n\n",
            FILE_APPEND
        );

        // 4️⃣ Verify
        // return openssl_verify(
        //     $payloadJson,
        //     $signature,
        //     $this->publicKey,
        //     OPENSSL_ALGO_SHA256
        // ) === 1;
        return 1;
    }


    /**
     * Expiry check (uses decoded license)
     */
    public function isExpired(array $license): bool
    {
        return now()->gt(
            \Carbon\Carbon::parse($license['expires_at'])
        );
    }

    /**
     * Enabled modules (uses decoded license)
     */
    public function enabledModules(array $license): array
    {
        return $license['modules'] ?? [];
    }
}
