<?php
namespace App\Services;

use Illuminate\Support\Facades\Http;

class PowerDNSService
{
    protected $host;
    protected $apiKey;

    public function __construct()
    {
        $this->host = 'http://powerdns.serversistemleri.com:9191';
        $this->apiKey = 'ZkoxZU5PQWVORVhpVENX';
    }

    protected function buildUrl($endpoint)
    {
        return "{$this->host}/api/v1/" . ltrim($endpoint, '/');
    }

    public function getZone($domain)
    {
        $domain = rtrim($domain, '.') . '.';

        $url = $this->buildUrl("servers/localhost/zones/{$domain}");

        $res = Http::withHeaders([
            'X-API-Key' => $this->apiKey,
        ])->get($url);

        if (!$res->successful()) {
            logger()->error("PowerDNS getZone hatası", [
                'status' => $res->status(),
                'url' => $url,
                'body' => $res->body()
            ]);
            return null;
        }

        return view('dns', [
            'dnsZone' => $res->json(),
        ]);
    }
    public function getZoneData($domain)
    {
        $domain = rtrim($domain, '.') . '.';
        $url = $this->buildUrl("servers/localhost/zones/{$domain}");

        $res = Http::withHeaders([
            'X-API-Key' => $this->apiKey,
        ])->get($url);

        if ($res->successful()) {
            return $res->json();
        }

        return [];
    }
    public function createZone($domain)
    {
        $domain = rtrim($domain, '.') . '.';
        $url = $this->buildUrl("servers/localhost/zones");

        return Http::withHeaders([
            'X-API-Key' => $this->apiKey,
        ])->post($url, [
            'name' => $domain,
            'kind' => 'Native',
            'masters' => [],
            'nameservers' => [
                'ns1.serversistemleri.com.',
                'ns2.serversistemleri.com.',
            ]
        ]);
    }

    public function updateZoneRecords($domain, $records)
    {
        $domain = rtrim($domain, '.') . '.';
        $url = $this->buildUrl("servers/localhost/zones/{$domain}");

        return Http::withHeaders([
            'X-API-Key' => $this->apiKey,
        ])->patch($url, [
            'rrsets' => $records
        ]);
    }
    public function applyZoneChanges($domain, $records)
{
    $domain = rtrim($domain, '.') . '.';
    $url = $this->buildUrl("servers/localhost/zones/{$domain}");

    return Http::withHeaders([
        'X-API-Key' => $this->apiKey,
    ])->patch($url, [
        'rrsets' => $records
    ]);
}
public function deleteRecord($domain, $record)
{
    $domain = rtrim($domain, '.') . '.';
    $url = $this->buildUrl("servers/localhost/zones/{$domain}");

    $record['changetype'] = 'DELETE';
    $record['ttl'] = $record['ttl'] ?? 3600;

    return Http::withHeaders([
        'X-API-Key' => $this->apiKey,
    ])->patch($url, [
        'rrsets' => [$record]
    ]);
}
}
