<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Licensing\Services\LixServ;
use App\Licensing\Services\Lixvalid;
use Illuminate\Http\JsonResponse;
use Illuminate\View\View;

/**
 * License Controller
 * Handles license management in admin panel
 */
class LicenseController extends Controller
{
    public function __construct(
        private LixServ $lixServ,
        private Lixvalid $lixvalid
    ) {}

    /**
     * Display license status page
     */
    public function index(): View
    {
        $licenseInfo = $this->lixServ->getLicenseInfo();
        $status = $this->lixvalid->getStatus();
        $currentDomain = $this->lixServ->getCurrentDomain();
        $licenseDomain = $this->lixServ->getLicenseDomain();

        return view('admin.license.index', [
            'licenseInfo' => $licenseInfo,
            'status' => $status,
            'currentDomain' => $currentDomain,
            'licenseDomain' => $licenseDomain,
            'productId' => $this->lixServ->getProductId(),
        ]);
    }

    /**
     * Verify license (AJAX)
     */
    public function verify(): JsonResponse
    {
        // Clear cache to force fresh verification
        $this->lixServ->clearCache();

        $status = $this->lixvalid->validate();

        return response()->json([
            'success' => $status['valid'] === true,
            'status' => $status,
        ]);
    }

    /**
     * Get license status (AJAX)
     */
    public function status(): JsonResponse
    {
        $status = $this->lixvalid->getStatus();
        $licenseInfo = $this->lixServ->getLicenseInfo();

        return response()->json([
            'status' => $status,
            'license' => [
                'domain' => $this->lixServ->getLicenseDomain(),
                'current_domain' => $this->lixServ->getCurrentDomain(),
                'email' => $this->lixServ->getLicenseEmail() ? substr($this->lixServ->getLicenseEmail(), 0, 3).'***' : null,
                'has_license' => $this->lixServ->hasLicense(),
            ],
        ]);
    }

    /**
     * Get independence status (AJAX)
     */
    public function independenceStatus(): JsonResponse
    {
        $independenceStatus = $this->lixvalid->getIndependenceStatus();

        return response()->json($independenceStatus);
    }
}
