<?php

namespace App\Http\Controllers;

use App\Services\PowerDNSService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Contracts\View\View;

class PowerDNSController extends Controller
{
    public function __construct(
        protected PowerDNSService $powerDNS
    ) {}

    /**
     * Tüm WHMCS zone'larını listele (Web View)
     */
    public function index(): View
    {
        $zones = $this->powerDNS->getWhmcsZones();
        
        // Zone'ları alfabetik sırala
        usort($zones, fn(array $a, array $b): int => 
            strcmp($a['name'] ?? '', $b['name'] ?? '')
        );

        return view('powerdns.index', [
            'zones' => $zones,
            'totalZones' => count($zones),
        ]);
    }

    /**
     * Tüm zone'ları listele (API)
     */
    public function apiIndex(): JsonResponse
    {
        $zones = $this->powerDNS->getZones();

        return response()->json([
            'success' => true,
            'data' => $zones,
            'total' => count($zones),
        ]);
    }

    /**
     * Sadece WHMCS zone'larını getir (API)
     */
    public function apiWhmcsZones(): JsonResponse
    {
        $zones = $this->powerDNS->getWhmcsZones();

        return response()->json([
            'success' => true,
            'data' => $zones,
            'total' => count($zones),
        ]);
    }

    /**
     * Zone detaylarını göster (Web View)
     */
    public function show(string $zoneId): View
    {
        $zone = $this->powerDNS->getZone($zoneId);
        
        if ($zone === null) {
            abort(404, 'Zone bulunamadı');
        }

        // WHMCS kontrolü
        $isWhmcs = $this->powerDNS->isWhmcsZone($zoneId);

        // Kayıtları türe göre grupla
        $recordsByType = [];
        if (isset($zone['rrsets']) && is_array($zone['rrsets'])) {
            foreach ($zone['rrsets'] as $rrset) {
                $type = $rrset['type'] ?? 'UNKNOWN';
                if (!isset($recordsByType[$type])) {
                    $recordsByType[$type] = [];
                }
                $recordsByType[$type][] = $rrset;
            }
        }

        return view('powerdns.show', [
            'zone' => $zone,
            'isWhmcs' => $isWhmcs,
            'recordsByType' => $recordsByType,
        ]);
    }

    /**
     * Zone detaylarını getir (API)
     */
    public function apiShow(string $zoneId): JsonResponse
    {
        $zone = $this->powerDNS->getZone($zoneId);

        if ($zone === null) {
            return response()->json([
                'success' => false,
                'message' => 'Zone bulunamadı',
            ], 404);
        }

        return response()->json([
            'success' => true,
            'data' => $zone,
            'is_whmcs' => $this->powerDNS->isWhmcsZone($zoneId),
        ]);
    }

    /**
     * Domain'in WHMCS zone olarak var olup olmadığını kontrol et (API)
     * Bu endpoint views tarafından kullanılacak
     */
    public function checkWhmcsZone(string $domain): JsonResponse
    {
        // Domain'i normalize et
        $domain = strtolower(trim($domain));
        $domain = rtrim($domain, '.');

        // Zone'un var olup olmadığını kontrol et
        $zone = $this->powerDNS->getZone($domain);
        
        if ($zone === null) {
            return response()->json([
                'success' => true,
                'exists' => false,
                'is_whmcs' => false,
                'domain' => $domain,
                'message' => 'Zone bulunamadı',
            ]);
        }

        // WHMCS account kontrolü
        $whmcsAccount = strtolower(config('powerdns.whmcs_account', 'whmcs'));
        $isWhmcs = isset($zone['account']) && strtolower($zone['account']) === $whmcsAccount;

        return response()->json([
            'success' => true,
            'exists' => true,
            'is_whmcs' => $isWhmcs,
            'domain' => $domain,
            'account' => $zone['account'] ?? null,
            'message' => $isWhmcs ? 'WHMCS zone mevcut' : 'Zone mevcut ama WHMCS değil',
        ]);
    }

    /**
     * Yeni zone oluştur (Web Form)
     */
    public function create(): View
    {
        return view('powerdns.create');
    }

    /**
     * Yeni zone kaydet
     */
    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'nameservers' => ['nullable', 'array'],
            'nameservers.*' => ['string'],
            'account' => ['nullable', 'string', 'max:255'],
        ]);

        $account = $validated['account'] ?? config('powerdns.whmcs_account', 'whmcs');
        $nameservers = $validated['nameservers'] ?? [];

        $zone = $this->powerDNS->createZone(
            $validated['name'],
            $nameservers,
            $account
        );

        if ($zone === null) {
            return response()->json([
                'success' => false,
                'message' => 'Zone oluşturulamadı',
            ], 500);
        }

        return response()->json([
            'success' => true,
            'message' => 'Zone başarıyla oluşturuldu',
            'data' => $zone,
        ], 201);
    }

    /**
     * Zone düzenleme formu
     */
    public function edit(string $zoneId): View
    {
        $zone = $this->powerDNS->getZone($zoneId);
        
        if ($zone === null) {
            abort(404, 'Zone bulunamadı');
        }

        return view('powerdns.edit', [
            'zone' => $zone,
        ]);
    }

    /**
     * DNS kaydı ekle
     */
    public function addRecord(Request $request, string $zoneId): JsonResponse
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'type' => ['required', 'string', 'in:A,AAAA,CNAME,MX,TXT,NS,SRV,CAA,PTR,SOA'],
            'content' => ['required', 'string'],
            'ttl' => ['nullable', 'integer', 'min:60', 'max:86400'],
        ]);

        $success = $this->powerDNS->addRecord(
            $zoneId,
            $validated['name'],
            $validated['type'],
            $validated['content'],
            $validated['ttl'] ?? 3600
        );

        if (!$success) {
            return response()->json([
                'success' => false,
                'message' => 'Kayıt eklenemedi',
            ], 500);
        }

        return response()->json([
            'success' => true,
            'message' => 'Kayıt başarıyla eklendi',
        ]);
    }

    /**
     * DNS kaydı sil
     */
    public function deleteRecord(Request $request, string $zoneId): JsonResponse
    {
        $validated = $request->validate([
            'name' => ['required', 'string'],
            'type' => ['required', 'string'],
        ]);

        $success = $this->powerDNS->deleteRecord(
            $zoneId,
            $validated['name'],
            $validated['type']
        );

        if (!$success) {
            return response()->json([
                'success' => false,
                'message' => 'Kayıt silinemedi',
            ], 500);
        }

        return response()->json([
            'success' => true,
            'message' => 'Kayıt başarıyla silindi',
        ]);
    }

    /**
     * Toplu kayıt güncelle
     */
    public function updateRecords(Request $request, string $zoneId): JsonResponse
    {
        $validated = $request->validate([
            'rrsets' => ['required', 'array'],
            'rrsets.*.name' => ['required', 'string'],
            'rrsets.*.type' => ['required', 'string'],
            'rrsets.*.ttl' => ['required', 'integer'],
            'rrsets.*.changetype' => ['required', 'string', 'in:REPLACE,DELETE'],
            'rrsets.*.records' => ['required', 'array'],
        ]);

        $success = $this->powerDNS->updateRecords($zoneId, $validated['rrsets']);

        if (!$success) {
            return response()->json([
                'success' => false,
                'message' => 'Kayıtlar güncellenemedi',
            ], 500);
        }

        return response()->json([
            'success' => true,
            'message' => 'Kayıtlar başarıyla güncellendi',
        ]);
    }

    /**
     * Zone sil
     */
    public function destroy(string $zoneId): JsonResponse
    {
        $success = $this->powerDNS->deleteZone($zoneId);

        if (!$success) {
            return response()->json([
                'success' => false,
                'message' => 'Zone silinemedi',
            ], 500);
        }

        return response()->json([
            'success' => true,
            'message' => 'Zone başarıyla silindi',
        ]);
    }

    /**
     * Bağlantı testi
     */
    public function testConnection(): JsonResponse
    {
        $connected = $this->powerDNS->testConnection();
        $serverInfo = $connected ? $this->powerDNS->getServerInfo() : null;

        return response()->json([
            'success' => $connected,
            'message' => $connected ? 'Bağlantı başarılı' : 'Bağlantı başarısız',
            'server_info' => $serverInfo,
        ]);
    }
}
