<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Setting;
use App\Services\LicenseGuard;

class LicenseController extends Controller
{
    public function showActivateForm()
    {
        $status = Setting::where('key', 'license_status')->value('value');
        $expiresAt = Setting::where('key', 'license_expires_at')->value('value');

        if (LicenseGuard::verifyLocalIntegrity()) {
            return redirect('/admin');
        }

        return view('license_activate', [
            'domain' => request()->getHost(),
            'status' => $status ?: 'UNLICENSED',
            'expiresAt' => $expiresAt,
        ]);
    }

    public function activate(Request $request)
    {
        $request->validate([
            'license_key' => 'required|string',
        ]);

        $licenseKey = trim($request->license_key);
        $domain = $request->getHost();

        $result = LicenseGuard::checkRemote($licenseKey, $domain);

        if ($result['valid']) {
            Setting::updateOrCreate(['key' => 'license_key'], ['value' => $licenseKey]);
            \Illuminate\Support\Facades\Artisan::call('optimize:clear');
            return redirect('/admin')->with('success', 'License activated and cryptographically signed successfully!');
        }

        $errorMessage = $result['message'] ?? 'License activation failed. Please verify your license key and domain.';
        return back()->withErrors(['license_key' => $errorMessage]);
    }
}
