<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class PurchaseController extends Controller
{
    public function validatePurchase(Request $request)
    {
        $domain = $request->input('domain');
        $purchaseCode = $request->input('purchase_code');

        // Fetch the purchase codes from the external server
        try {
    $purchaseCodesResponse = Http::timeout(20)->get('https://teeflow14.github.io/tundeblog-license-api/purchasecode.json');
    if ($purchaseCodesResponse->failed()) {
        return back()->withErrors('Could not verify purchase code. Please try again later.');
    }
} catch (\Exception $e) {
    return back()->withErrors('Connection error: ' . $e->getMessage());
}


        $purchaseCodes = $purchaseCodesResponse->json();

        // Check if the provided purchase code is valid
        if (!in_array($purchaseCode, $purchaseCodes)) {
            return back()->withErrors('Invalid purchase code. Please try again.');
        }

        // Fetch the allowed domains from the external server
        $allowedDomainsResponse = Http::get('https://teeflow14.github.io/tundeblog-license-api/allowed-domains.json');
        if ($allowedDomainsResponse->failed()) {
            return back()->withErrors('Could not update allowed domains. Please try again later.');
        }

        $allowedDomains = $allowedDomainsResponse->json();

        // Add the new domain to the allowed domains list if not already present
        if (!in_array($domain, $allowedDomains)) {
            $allowedDomains[] = $domain;

            // Save the updated list back to the server
            $response = Http::post('https://tundeblog.com/api/update-allowed-domains.php', [
                'allowed_domains' => $allowedDomains
            ]);

            if ($response->failed()) {
                return back()->withErrors('Could not update allowed domains. Please try again later.');
            }
        }

        return back()->with('success', 'Domain has been successfully activated.');
    }
}
