<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\PowerDNSService;
use Illuminate\Support\Facades\Session;
use App\Http\Controllers\cPanelController;
use App\Services\WhmcsService;
class DnsController extends Controller
{
    protected $powerdns;
    protected $whmcs;

    public function __construct(WhmcsService $whmcs, PowerDNSService $powerdns)
    {
        $this->powerdns = $powerdns;
        $this->whmcs = $whmcs;
    }

    public function getZone(Request $request, $domain)
    {
        $clientId = Session::get('client'); // Laravel Auth yerine WHMCS oturumu

        $expected = hash_hmac('sha256', $domain, $clientId . env('DOMAIN_HASH_SECRET'));

        if (!hash_equals($expected, $request->input('hash'))) {
            abort(403, 'Yetkisiz erişim!');
        }

        return $this->powerdns->getZone($domain);
    }

    public function applyRecords(Request $request, $domain)
{
    $records = $request->input('records', []);

    $rrsets = array_map(function ($record) {
        return [
            'name' => rtrim($record['name'], '.') . '.',
            'type' => $record['type'],
            'ttl' => (int) ($record['ttl'] === 'Auto' ? 3600 : $record['ttl']),
            'changetype' => 'REPLACE',
            'records' => [
                ['content' => $record['content'], 'disabled' => false]
            ],
        ];
    }, $records);

    $response = $this->powerdns->applyZoneChanges($domain, $rrsets);

    if ($response->successful()) {
        return response()->json(['status' => 'success']);
    }

    return response()->json(['status' => 'error', 'message' => $response->body()], $response->status());
}

public function apply(Request $request, $domain)
{
    $incoming = $request->input('records', []);
    $domainWithDot = rtrim($domain, '.') . '.';

    // Mevcut zone verisini çek
    $zone = $this->powerdns->getZoneData($domainWithDot);
    $existing = collect($zone['rrsets'] ?? []);

    $changed = [];

    foreach ($incoming as $record) {
        $name = $this->normalizeDNSName($record['name'], $domain);
        $type = $record['type'];
        $ttl = isset($record['ttl']) && is_numeric($record['ttl']) ? (int)$record['ttl'] : 3600;
        $content = trim($record['content']);

        if (strtoupper($type) === 'TXT') {
            // Eğer içerik zaten tırnaklı değilse, tırnaklara al
            if (!str_starts_with($content, '"')) {
                $content = '"' . $content . '"';
            }
        }

        // Mevcut kaydı bul
        $old = $existing->first(function ($rr) use ($name, $type) {
            return rtrim($rr['name'], '.') === rtrim($name, '.') && $rr['type'] === $type;
        });

        $oldContent = $old['records'][0]['content'] ?? null;
        $oldTTL = $old['ttl'] ?? null;

        // İçerik veya TTL değişmişse REPLACE işlemi yap
        if ($oldContent !== $content || $oldTTL != $ttl) {
            $changed[] = [
                'name' => $name,
                'type' => $type,
                'ttl' => $ttl,
                'changetype' => 'REPLACE',
                'records' => [
                    [
                        'content' => $content,
                        'disabled' => false,
                    ]
                ],
            ];
        }
    }

    if (empty($changed)) {
        return response()->json(['status' => 'success', 'message' => 'Değişiklik yok']);
    }

    $response = $this->powerdns->updateZoneRecords($domainWithDot, $changed);

    if ($response->successful()) {
        return response()->json(['status' => 'success']);
    }

    return response()->json([
        'status' => 'error',
        'message' => $response->body()
    ], $response->status());
}

// İsim normalizasyon fonksiyonu
private function normalizeDNSName($name, $domain)
{
    $name = rtrim($name, '.');
    $domain = rtrim($domain, '.');

    // Eğer name zaten domain ile bitiyorsa (örn. www.eddys-werkstatt.de gibi), olduğu gibi bırak
    if (str_ends_with($name, $domain)) {
        return $name . '.';
    }

    // Root domainse sadece "." ekle
    if ($name === '' || $name === '@') {
        return $domain . '.';
    }

    // Kısa isimse (örn. www) domain'i ekle
    return $name . '.' . $domain . '.';
}
}

 ?>
