<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\NetworkTools\DnsRequest;
use App\Http\Requests\Admin\NetworkTools\MxRequest;
use App\Http\Requests\Admin\NetworkTools\PingRequest;
use App\Http\Requests\Admin\NetworkTools\TracerouteRequest;
use App\Http\Requests\Admin\NetworkTools\TxtRequest;
use App\Http\Requests\Admin\NetworkTools\WhoisRequest;
use App\Services\NetworkToolsService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class NetworkToolsController extends Controller
{
    protected NetworkToolsService $networkToolsService;

    public function __construct(NetworkToolsService $networkToolsService)
    {
        $this->networkToolsService = $networkToolsService;
    }

    /**
     * Network araçları ana sayfası
     */
    public function index()
    {
        return view('admin.network-tools.index');
    }

    /**
     * TLD Config yönetim sayfası
     */
    public function tldConfigPage()
    {
        return view('admin.network-tools.tld-config');
    }

    /**
     * Whois sayfası
     */
    public function whoisPage()
    {
        return view('admin.network-tools.whois');
    }

    /**
     * Ping sayfası
     */
    public function pingPage()
    {
        return view('admin.network-tools.ping');
    }

    /**
     * Traceroute sayfası
     */
    public function traceroutePage()
    {
        return view('admin.network-tools.traceroute');
    }

    /**
     * DNS sayfası
     */
    public function dnsPage()
    {
        return view('admin.network-tools.dns');
    }

    /**
     * MX sayfası
     */
    public function mxPage()
    {
        return view('admin.network-tools.mx');
    }

    /**
     * TXT sayfası
     */
    public function txtPage()
    {
        return view('admin.network-tools.txt');
    }

    /**
     * Whois sorgusu
     */
    public function whois(WhoisRequest $request): JsonResponse
    {
        $validated = $request->validated();

        try {
            $result = $this->networkToolsService->whois($validated['domain']);

            return response()->json([
                'success' => true,
                'data' => $result,
            ]);
        } catch (\Exception $e) {
            \Log::error('Whois query failed', ['error' => $e->getMessage(), 'trace' => $e->getTraceAsString()]);
            return response()->json([
                'success' => false,
                'message' => __('admin/common.general_error'),
            ], 500);
        }
    }

    /**
     * Ping sorgusu
     */
    public function ping(PingRequest $request): JsonResponse
    {
        $validated = $request->validated();

        try {
            $result = $this->networkToolsService->ping($validated['host'], $validated['count'] ?? 4);

            return response()->json([
                'success' => true,
                'data' => $result,
            ]);
        } catch (\Exception $e) {
            \Log::error('Ping query failed', ['error' => $e->getMessage(), 'trace' => $e->getTraceAsString()]);
            return response()->json([
                'success' => false,
                'message' => __('admin/common.general_error'),
            ], 500);
        }
    }

    /**
     * Traceroute sorgusu
     */
    public function traceroute(TracerouteRequest $request): JsonResponse
    {
        $validated = $request->validated();

        try {
            $result = $this->networkToolsService->traceroute($validated['host'], $validated['max_hops'] ?? 30);

            return response()->json([
                'success' => true,
                'data' => $result,
            ]);
        } catch (\Exception $e) {
            \Log::error('Traceroute query failed', ['error' => $e->getMessage(), 'trace' => $e->getTraceAsString()]);
            return response()->json([
                'success' => false,
                'message' => __('admin/common.general_error'),
            ], 500);
        }
    }

    /**
     * DNS sorgusu
     */
    public function dns(DnsRequest $request): JsonResponse
    {
        $validated = $request->validated();

        try {
            $result = $this->networkToolsService->dns($validated['domain'], $validated['type'] ?? 'A');

            return response()->json([
                'success' => true,
                'data' => $result,
            ]);
        } catch (\Exception $e) {
            \Log::error('DNS query failed', ['error' => $e->getMessage(), 'trace' => $e->getTraceAsString()]);
            return response()->json([
                'success' => false,
                'message' => __('admin/common.general_error'),
            ], 500);
        }
    }

    /**
     * MX sorgusu
     */
    public function mx(MxRequest $request): JsonResponse
    {
        $validated = $request->validated();

        try {
            $result = $this->networkToolsService->mx($validated['domain']);

            return response()->json([
                'success' => true,
                'data' => $result,
            ]);
        } catch (\Exception $e) {
            \Log::error('MX query failed', ['error' => $e->getMessage(), 'trace' => $e->getTraceAsString()]);
            return response()->json([
                'success' => false,
                'message' => __('admin/common.general_error'),
            ], 500);
        }
    }

    /**
     * TXT sorgusu
     */
    public function txt(TxtRequest $request): JsonResponse
    {
        $validated = $request->validated();

        try {
            $result = $this->networkToolsService->txt($validated['domain']);

            return response()->json([
                'success' => true,
                'data' => $result,
            ]);
        } catch (\Exception $e) {
            \Log::error('TXT query failed', ['error' => $e->getMessage(), 'trace' => $e->getTraceAsString()]);
            return response()->json([
                'success' => false,
                'message' => __('admin/common.general_error'),
            ], 500);
        }
    }

    /**
     * TLD Config API - Create/Update
     */
    public function tldConfig(Request $request): JsonResponse
    {
        try {
            $validated = $request->validate([
                'tld' => 'required|string|max:10',
                'server' => 'required|string|max:255',
                'query_format' => 'required|string|max:100',
                'response_encoding' => 'required|string|max:20',
                'timeout' => 'required|integer|min:1|max:300',
                'available_pattern' => 'required|string|max:255',
            ]);

            $this->updateWhoisConfig($validated['tld'], $validated, 'update');

            return response()->json([
                'success' => true,
                'message' => __('admin/common.messages_tld_config_updated'),
            ]);
        } catch (\Exception $e) {
            \Log::error('TLD config update failed', ['error' => $e->getMessage(), 'trace' => $e->getTraceAsString()]);
            return response()->json([
                'success' => false,
                'message' => __('admin/common.general_error'),
            ], 500);
        }
    }

    /**
     * TLD Config API - Delete
     */
    public function deleteTldConfig(Request $request): JsonResponse
    {
        try {
            $validated = $request->validate([
                'tld' => 'required|string|max:10',
            ]);

            $this->removeTldFromConfig($validated['tld']);

            return response()->json([
                'success' => true,
                'message' => 'TLD config silindi',
            ]);
        } catch (\Exception $e) {
            \Log::error('TLD config deletion failed', ['error' => $e->getMessage(), 'trace' => $e->getTraceAsString()]);
            return response()->json([
                'success' => false,
                'message' => __('admin/common.general_error'),
            ], 500);
        }
    }

    /**
     * Whois config dosyasını güncelle
     */
    protected function updateWhoisConfig(string $tld, array $config, string $action): void
    {
        $configPath = config_path('whois.php');
        $currentConfig = require $configPath;

        if ($action === 'update') {
            $currentConfig['tlds'][$tld] = $config;
        } elseif ($action === 'delete') {
            unset($currentConfig['tlds'][$tld]);
        }

        $configContent = "<?php\n\nreturn ".var_export($currentConfig, true).";\n";
        file_put_contents($configPath, $configContent);
    }

    /**
     * TLD'yi config'den kaldır
     */
    protected function removeTldFromConfig(string $tld): void
    {
        $this->updateWhoisConfig($tld, [], 'delete');
    }
}
