<?php $pageTitle = 'DNS Kayıtları'; ?>
<?php echo $__env->make("layouts.header", \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>

<?php
$recordsRaw = $dnsZone ?? [];

// Handle nested structures if the controller didn't fully flatten it
if (isset($recordsRaw[0]['record']) && is_array($recordsRaw[0]['record'])) {
    $recordsRaw = $recordsRaw[0]['record'];
} elseif (isset($recordsRaw['record']) && is_array($recordsRaw['record'])) {
    $recordsRaw = $recordsRaw['record'];
} elseif (isset($recordsRaw['records']) && is_array($recordsRaw['records'])) {
    $recordsRaw = $recordsRaw['records'];
} elseif (isset($recordsRaw[0]['records']) && is_array($recordsRaw[0]['records'])) {
    $recordsRaw = $recordsRaw[0]['records'];
}

$domainName = $domain ?? 'Unknown Domain'; // Controller'dan gelen domain değişkeni

// Eğer domain adı controllerdan gelmediyse kayıtlardan bulmaya çalış
if ($domainName === 'Unknown Domain') {
    foreach ($recordsRaw as $rec) {
        if (($rec['type'] ?? '') === 'SOA') {
            $domainName = rtrim($rec['name'] ?? '', '.');
            break;
        }
    }
}

// Zone domain normalize (son nokta vs)
$zoneDomain = rtrim((string)$domainName, '.');

// PHP tarafı: name normalize helper
function normalizeDnsName(?string $rawName, string $zoneDomain): string
{
    $name = $rawName ?? '@';
    $name = trim($name);
    if ($name === '' || $name === '@') return '@';

    // sonundaki noktayı kaldır
    $name = rtrim($name, '.');

    // Eğer name direkt zone domain ise -> @
    if (strcasecmp($name, $zoneDomain) === 0) {
        return '@';
    }

    // Eğer ".zoneDomain" ile bitiyorsa suffix'i kırp
    $pattern = '/\.?' . preg_quote($zoneDomain, '/') . '$/i';
    $name = preg_replace($pattern, '', $name);

    // boş kaldıysa root
    if ($name === '' || $name === null) return '@';

    return $name;
}

$parsedRecords = [];
foreach ($recordsRaw as $rec) {
    if (!isset($rec['type'])) continue;
    if (in_array($rec['type'], [':RAW', '$TTL'])) continue;

    $content = '';
    $type = strtoupper($rec['type']);

    // Map cPanel-specific fields to a generic "content" string
    switch ($type) {
        case 'A':
        case 'AAAA':
            $content = $rec['address'] ?? '';
            break;

        case 'CNAME':
            $content = $rec['cname'] ?? '';
            break;

        case 'MX':
            // "0 domain.com" format
            $content = trim(($rec['preference'] ?? 0) . ' ' . ($rec['exchange'] ?? ''));
            break;

        case 'TXT':
            // cPanel TXT verilerini farklı anahtarlarda saklayabilir
            if (!empty($rec['txtdata'])) {
                $content = is_array($rec['txtdata']) ? implode('', $rec['txtdata']) : $rec['txtdata'];
            } elseif (!empty($rec['record'])) {
                $content = is_array($rec['record']) ? implode('', $rec['record']) : $rec['record'];
            } elseif (!empty($rec['data'])) {
                $content = is_array($rec['data']) ? implode('', $rec['data']) : $rec['data'];
            } elseif (!empty($rec['char_str_list'])) {
                $content = is_array($rec['char_str_list']) ? implode('', $rec['char_str_list']) : $rec['char_str_list'];
            } elseif (!empty($rec['text'])) {
                $content = is_array($rec['text']) ? implode('', $rec['text']) : $rec['text'];
            } else {
                // Hiçbiri yoksa tüm rec içinden bulmaya çalış
                $content = '';
                foreach (['txtdata', 'record', 'data', 'char_str_list', 'text', 'rdata'] as $key) {
                    if (isset($rec[$key]) && !empty($rec[$key])) {
                        $content = is_array($rec[$key]) ? implode('', $rec[$key]) : $rec[$key];
                        break;
                    }
                }
            }
            // Tırnak işaretlerini temizle
            $content = trim($content, '"\'');
            break;

        case 'NS':
            $content = $rec['nsdname'] ?? '';
            break;

        case 'SRV':
            // "priority weight port target" format
            $content = trim(
                ($rec['priority'] ?? 0) . ' ' .
                ($rec['weight'] ?? 0) . ' ' .
                ($rec['port'] ?? 0) . ' ' .
                ($rec['target'] ?? '')
            );
            break;

        case 'SOA':
            // "mname rname"
            $content = trim(($rec['mname'] ?? '') . ' ' . ($rec['rname'] ?? ''));
            break;

        default:
            $content = json_encode($rec);
    }

    // ✅ BURASI KRİTİK: name normalize
    $name = normalizeDnsName($rec['name'] ?? '@', $zoneDomain);

    $parsedRecords[] = [
        'line' => $rec['Line'] ?? 0,
        'type' => $type,
        'name' => $name,
        'content' => $content,
        'ttl' => $rec['ttl'] ?? 14400,
        'raw_keys' => [
            // A/AAAA
            'address' => $rec['address'] ?? '',
            // CNAME
            'cname' => $rec['cname'] ?? '',
            // MX
            'preference' => $rec['preference'] ?? 0,
            'exchange' => $rec['exchange'] ?? '',
            // SRV
            'weight' => $rec['weight'] ?? 0,
            'port' => $rec['port'] ?? 0,
            'target' => $rec['target'] ?? '',
            'priority' => $rec['priority'] ?? 0,
            // NS
            'nsdname' => $rec['nsdname'] ?? '',
            // PTR
            'ptrdname' => $rec['ptrdname'] ?? '',
            // TXT
            'txtdata' => $content, // TXT için content'i kullan
            // CAA
            'flag' => $rec['flag'] ?? 0,
            'tag' => $rec['tag'] ?? '',
            'value' => $rec['value'] ?? '',
            // AFSDB
            'subtype' => $rec['subtype'] ?? 0,
            'hostname' => $rec['hostname'] ?? '',
            // DS
            'keytag' => $rec['keytag'] ?? 0,
            'algorithm' => $rec['algorithm'] ?? 0,
            'digesttype' => $rec['digesttype'] ?? 0,
            'digest' => $rec['digest'] ?? '',
            // HINFO
            'cpu' => $rec['cpu'] ?? '',
            'os' => $rec['os'] ?? '',
            // LOC
            'location' => $rec['location'] ?? '',
            // NAPTR
            'order' => $rec['order'] ?? 0,
            'flags' => $rec['flags'] ?? '',
            'service' => $rec['service'] ?? '',
            'regexp' => $rec['regexp'] ?? '',
            'replacement' => $rec['replacement'] ?? '',
            // RP
            'mbox' => $rec['mbox'] ?? '',
            'txtdname' => $rec['txtdname'] ?? '',
        ]
    ];
}
?>

<!-- CSRF Token -->
<meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">

<style>
.sm\:text-sm {
  color: black;
}
html.dark .dark-color-text-title {
  color: #ffffff !important;
}

    .custom-scrollbar::-webkit-scrollbar { width: 6px; height: 6px; }
    .custom-scrollbar::-webkit-scrollbar-track { background: #f1f1f1; border-radius: 4px; }
    .custom-scrollbar::-webkit-scrollbar-thumb { background: #d1d5db; border-radius: 4px; }
    .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: #9ca3af; }

    .glass-panel { background: rgba(255, 255, 255, 0.95); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); }
    .smooth-transition { transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1); }

    .table-row-hover:hover {
        background-color: #f8fafc;
        transform: translateY(-1px);
        box-shadow: 0 2px 4px rgba(0,0,0,0.02);
    }

    .badge {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 65px;
        padding: 0.25rem 0.5rem;
        border-radius: 0.375rem;
        font-size: 0.75rem;
        font-weight: 600;
        letter-spacing: 0.5px;
    }
    .badge-A { background-color: #DBEAFE; color: #1E40AF; }
    .badge-AAAA { background-color: #E0E7FF; color: #3730A3; }
    .badge-CNAME { background-color: #F3E8FF; color: #6B21A8; }
    .badge-MX { background-color: #FFEDD5; color: #9A3412; }
    .badge-TXT { background-color: #F1F5F9; color: #475569; }
    .badge-NS { background-color: #DCFCE7; color: #166534; }
    .badge-SRV { background-color: #FCE7F3; color: #9D174D; }
    .badge-SOA { background-color: #FEF3C7; color: #92400E; }
    .badge-DEFAULT { background-color: #F3F4F6; color: #374151; }

    .modal-enter { opacity: 0; transform: scale(0.95); }
    .modal-enter-active { opacity: 1; transform: scale(1); transition: all 0.2s ease-out; }
    .modal-exit { opacity: 1; transform: scale(1); }
    .modal-exit-active { opacity: 0; transform: scale(0.95); transition: all 0.15s ease-in; }

    input:focus, select:focus, textarea:focus {
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.15);
    }
</style>

<div class="min-h-screen py-8 px-4 sm:px-6 lg:px-8">
    <div class="mx-auto space-y-6">

        <!-- Header Section -->
        <div class="flex flex-col md:flex-row md:items-center justify-between gap-4
            rounded-xl border border-gray-200 dark:border-gray-800
            bg-white dark:bg-gray-900
            p-5 shadow-sm">

    <!-- Sol Alan -->
    <div>
        <h1 class="dark-color-text-title text-2xl font-semibold tracking-tight
                   text-gray-900 dark:text-gray-100
                   flex items-center gap-3">
            <div class="dark-color-text-title flex items-center justify-center w-10 h-10
                        rounded-lg bg-blue-100 dark:bg-blue-900/40">
                <svg class="w-6 h-6 text-blue-600 dark:text-blue-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9" />
                </svg>
            </div>
            DNS Yönetimi
        </h1>

        <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
            <span class="font-medium text-gray-800 dark:text-gray-200">
                <?php echo e($zoneDomain); ?>

            </span>
            bölgesi için yapılandırma
        </p>
    </div>

    <!-- Sağ Alan / Status -->
    <div class="flex items-center gap-3">
        <div class="flex items-center gap-2 px-4 py-1.5 rounded-full
                    border border-green-200 dark:border-green-800
                    bg-green-100 dark:bg-green-900/30">
            <span class="relative flex h-2.5 w-2.5">
                <span class="animate-ping absolute inline-flex h-full w-full
                             rounded-full bg-green-400 opacity-75"></span>
                <span class="relative inline-flex h-2.5 w-2.5
                             rounded-full bg-green-500"></span>
            </span>
            <span class="text-xs font-semibold
                         text-green-700 dark:text-green-400">
                Aktif
            </span>
        </div>
    </div>
</div>

        <!-- Main Content Card -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">

            <!-- Toolbar -->
            <div class="p-5 border-b border-gray-100 bg-gray-50/50 flex flex-col md:flex-row gap-4 items-center justify-between">
                <div class="relative w-full md:w-96">
                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                        <svg class="h-5 w-5 text-gray-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                            <path fill-rule="evenodd" d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z" clip-rule="evenodd" />
                        </svg>
                    </div>
                    <input type="text" id="searchInput"
                        class="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg leading-5 bg-white placeholder-gray-500 focus:outline-none focus:placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 sm:text-sm smooth-transition"
                        placeholder="Kayıt ara (Ad, IP, Tür...)"
                    >
                </div>

                <div class="flex gap-3 w-full md:w-auto">
                    <button onclick="showAddForm()" class="flex-1 md:flex-none inline-flex items-center justify-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-lg text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 smooth-transition">
                        <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
                        Kayıt Ekle
                    </button>
                </div>
            </div>

            <!-- DNS Records Table -->
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50/80">
                        <tr>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider cursor-pointer hover:text-gray-700 select-none" onclick="sortTable('type')">Tür</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider cursor-pointer hover:text-gray-700 select-none" onclick="sortTable('name')">Ad</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider cursor-pointer hover:text-gray-700 select-none" onclick="sortTable('content')">İçerik</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider cursor-pointer hover:text-gray-700 select-none" onclick="sortTable('ttl')">TTL</th>
                            <th scope="col" class="px-6 py-3 text-right text-xs font-semibold text-gray-500 uppercase tracking-wider">İşlemler</th>
                        </tr>
                    </thead>
                    <tbody id="recordsTable" class="bg-white divide-y divide-gray-100">
                        <!-- Filled by JS -->
                    </tbody>
                </table>
            </div>

            <!-- Table Footer/Info -->
            <div class="bg-gray-50 px-6 py-3 border-t border-gray-200 text-xs text-gray-500 flex justify-between items-center">
                <span id="recordCount">Toplam 0 kayıt</span>
            </div>
        </div>

        <!-- Info Card: Server Nameservers -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 flex flex-col md:flex-row gap-6">
            <div class="flex-shrink-0">
                <div class="w-12 h-12 bg-indigo-100 rounded-lg flex items-center justify-center text-indigo-600">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2m-2-4h.01M17 16h.01"></path></svg>
                </div>
            </div>
            <div>
                <h3 class="text-base font-semibold text-gray-900">Aktif Nameserver'lar</h3>
                <p class="mt-1 text-sm text-gray-600">
                    Bu alan adı için yetkili nameserver'lar. DNS değişikliklerinin yayılması 24-48 saat sürebilir.
                </p>
                <div class="mt-4 flex flex-wrap gap-3">
                    <div class="px-3 py-1.5 bg-gray-100 rounded text-sm text-gray-700 border border-gray-200 font-mono">ns1.serversistemleri.com</div>
                    <div class="px-3 py-1.5 bg-gray-100 rounded text-sm text-gray-700 border border-gray-200 font-mono">ns2.serversistemleri.com</div>
                </div>
            </div>
        </div>

    </div>
</div>

<!-- Modal -->
<div id="recordModal" class="fixed inset-0 z-50 hidden overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
    <div class="fixed inset-0 bg-gray-900 bg-opacity-40 transition-opacity backdrop-filter backdrop-blur-sm" onclick="closeModal()"></div>

    <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>

        <div class="inline-block align-bottom bg-white rounded-2xl text-left overflow-hidden shadow-2xl transform transition-all sm:my-8 sm:align-middle sm:max-w-xl w-full">
            <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                <div class="sm:flex sm:items-start">
                    <div class="mt-3 text-center sm:mt-0 sm:text-left w-full">
                        <div class="flex justify-between items-center mb-5">
                            <h3 class="text-lg leading-6 font-semibold text-gray-900" id="modalTitle">DNS Kaydı Ekle</h3>
                            <button onclick="closeModal()" class="text-gray-400 hover:text-gray-500 smooth-transition">
                                <svg class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" /></svg>
                            </button>
                        </div>

                        <form id="recordForm" onsubmit="saveRecord(event)" class="space-y-4">
                            <!-- Type & Name Row -->
                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <label for="recordType" class="block text-sm font-medium text-gray-700 mb-1">Tür</label>
                                    <select id="recordType" onchange="updateFormFields()" class="block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-lg border bg-white">
                                        <option value="A">A</option>
                                        <option value="SOA">SOA</option>
                                        <option value="AAAA">AAAA</option>
                                        <option value="AFSDB">AFSDB</option>
                                        <option value="CAA">CAA</option>
                                        <option value="CNAME">CNAME</option>
                                        <option value="DNAME">DNAME</option>
                                        <option value="DS">DS</option>
                                        <option value="HINFO">HINFO</option>
                                        <option value="LOC">LOC</option>
                                        <option value="MX">MX</option>
                                        <option value="NS">NS</option>
                                        <option value="NAPTR">NAPTR</option>
                                        <option value="PTR">PTR</option>
                                        <option value="RP">RP</option>
                                        <option value="SRV">SRV</option>
                                        <option value="TXT">TXT</option>
                                    </select>
                                </div>
                                <div>
                                    <label for="recordTTL" class="block text-sm font-medium text-gray-700 mb-1">TTL</label>
                                    <select id="recordTTL" class="block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-lg border bg-white">
                                        <option value="300">5 dakika (300)</option>
                                        <option value="600">10 dakika (600)</option>
                                        <option value="900">15 dakika (900)</option>
                                        <option value="1800">30 dakika (1800)</option>
                                        <option value="3600">1 saat (3600)</option>
                                        <option value="7200">2 saat (7200)</option>
                                        <option value="14400" selected>4 saat (14400)</option>
                                        <option value="21600">6 saat (21600)</option>
                                        <option value="43200">12 saat (43200)</option>
                                        <option value="86400">1 gün (86400)</option>
                                        <option value="172800">2 gün (172800)</option>
                                        <option value="604800">1 hafta (604800)</option>
                                    </select>
                                </div>
                            </div>

                            <!-- Ad (Host) -->
                            <div>
                                <label for="recordName" class="block text-sm font-medium text-gray-700 mb-1">Ad (Host)</label>
                                <div class="flex rounded-lg shadow-sm">
                                    <input type="text" id="recordName" class="flex-1 min-w-0 block w-full px-3 py-2 border border-gray-300 rounded-l-lg focus:ring-blue-500 focus:border-blue-500 sm:text-sm" placeholder="@ veya www">
                                    <span class="inline-flex items-center px-3 py-2 border border-l-0 border-gray-300 bg-gray-100 text-gray-500 sm:text-sm rounded-r-lg select-none">
                                        .<?php echo e($zoneDomain); ?>

                                    </span>
                                </div>
                                <p class="mt-1 text-xs text-gray-500">Root domain için @ kullanın</p>
                            </div>


                            <!-- Dynamic Fields Container -->
                            <div id="dynamicFields" class="space-y-4">
                                <!-- Fields will be injected here based on type -->
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                <button type="button" onclick="document.getElementById('recordForm').dispatchEvent(new Event('submit'))" class="w-full inline-flex justify-center rounded-lg border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:ml-3 sm:w-auto sm:text-sm smooth-transition">
                    Kaydet
                </button>
                <button type="button" onclick="closeModal()" class="mt-3 w-full inline-flex justify-center rounded-lg border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm smooth-transition">
                    İptal
                </button>
            </div>
        </div>
    </div>
</div>

<script>
    // Injected parsed PHP data
    let records = <?php echo json_encode($parsedRecords, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
    const domainName = "<?php echo e($zoneDomain); ?>";
    const serverId = <?php echo e($serverId ?? 'null'); ?>;
    const hash = "<?php echo e($hash ?? ''); ?>";

    let currentSort = { field: null, direction: 'asc' };
    let editingIndex = -1;

    // JS tarafı: name normalize (kullanıcı full domain yazsa bile düzeltir)
    function normalizeName(inputName) {
        let name = (inputName ?? '').trim();
        if (!name || name === '@') return '@';

        // sonda nokta varsa fqdn olabilir -> sadece noktasını kırp
        name = name.replace(/\.+$/, '');

        // tam domain yazdıysa -> @
        if (name.toLowerCase() === domainName.toLowerCase()) return '@';

        // subdomain.domain.com yazdıysa suffix kırp
        const re = new RegExp('(\\.)?' + domainName.replace(/\./g, '\\.') + '$', 'i');
        name = name.replace(re, '');

        if (!name) return '@';
        return name;
    }

    document.addEventListener('DOMContentLoaded', () => {
        // records içinden güvenlik için bir tur daha normalize edelim
        records = records.map(r => ({ ...r, name: normalizeName(r.name) }));

        renderRecords();
        updateRecordCount();
        updateFormFields(); // İlk yüklemede form alanlarını oluştur

        document.getElementById('searchInput').addEventListener('input', (e) => {
            const term = e.target.value.toLowerCase();
            const filtered = records.filter(r =>
                String(r.name).toLowerCase().includes(term) ||
                String(r.content).toLowerCase().includes(term) ||
                String(r.type).toLowerCase().includes(term)
            );
            renderRecords(filtered);
        });
    });

    // DNS kayıt türlerine göre form alanları tanımları
    const fieldDefinitions = {
        'A': [
            { id: 'address', label: 'IPv4 Adresi', placeholder: '192.168.1.1', type: 'text' }
        ],
        'AAAA': [
            { id: 'address', label: 'IPv6 Adresi', placeholder: '2001:db8::1', type: 'text' }
        ],
        'AFSDB': [
            { id: 'subtype', label: 'Alt Tür', placeholder: '1', type: 'number' },
            { id: 'hostname', label: 'Hostname', placeholder: 'afsdb.example.com', type: 'text' }
        ],
        'CAA': [
            { id: 'flag', label: 'Bayrak', placeholder: '0', type: 'number' },
            { id: 'tag', label: 'Etiket', placeholder: 'issue', type: 'text' },
            { id: 'value', label: 'Değer', placeholder: 'letsencrypt.org', type: 'text' }
        ],
        'CNAME': [
            { id: 'cname', label: 'Hedef (FQDN)', placeholder: 'target.example.com', type: 'text' }
        ],
        'DNAME': [
            { id: 'target', label: 'Hedef', placeholder: 'target.example.com', type: 'text' }
        ],
        'DS': [
            { id: 'keytag', label: 'Key Tag', placeholder: '12345', type: 'number' },
            { id: 'algorithm', label: 'Algoritma', placeholder: '8', type: 'number' },
            { id: 'digesttype', label: 'Digest Türü', placeholder: '2', type: 'number' },
            { id: 'digest', label: 'Digest', placeholder: 'ABC123...', type: 'text' }
        ],
        'HINFO': [
            { id: 'cpu', label: 'CPU', placeholder: 'Intel', type: 'text' },
            { id: 'os', label: 'İşletim Sistemi', placeholder: 'Linux', type: 'text' }
        ],
        'LOC': [
            { id: 'location', label: 'Konum', placeholder: '52 22 23.000 N 4 53 32.000 E -2.00m 0.00m 10000m 10m', type: 'text' }
        ],
        'MX': [
            { id: 'preference', label: 'Öncelik', placeholder: '10', type: 'number' },
            { id: 'exchange', label: 'Hedef Yer', placeholder: 'mail.example.com', type: 'text' }
        ],
        'NS': [
            { id: 'nsdname', label: 'Nameserver', placeholder: 'ns1.example.com', type: 'text' }
        ],
        'NAPTR': [
            { id: 'order', label: 'Sıra', placeholder: '100', type: 'number' },
            { id: 'preference', label: 'Öncelik', placeholder: '10', type: 'number' },
            { id: 'flags', label: 'Bayraklar', placeholder: 'U', type: 'text' },
            { id: 'service', label: 'Servis', placeholder: 'E2U+sip', type: 'text' },
            { id: 'regexp', label: 'Regex', placeholder: '!^.*$!sip:info@example.com!', type: 'text' },
            { id: 'replacement', label: 'Değiştirme', placeholder: '.', type: 'text' }
        ],
        'PTR': [
            { id: 'ptrdname', label: 'Hedef Alan Adı', placeholder: 'host.example.com', type: 'text' }
        ],
        'RP': [
            { id: 'mbox', label: 'E-posta', placeholder: 'admin.example.com', type: 'text' },
            { id: 'txtdname', label: 'TXT Alan Adı', placeholder: 'example.com', type: 'text' }
        ],
        'SRV': [
            { id: 'priority', label: 'Öncelik', placeholder: '0', type: 'number' },
            { id: 'weight', label: 'Ağırlık', placeholder: '5', type: 'number' },
            { id: 'port', label: 'Port', placeholder: '5060', type: 'number' },
            { id: 'target', label: 'Hedef', placeholder: 'sip.example.com', type: 'text' }
        ],
        'TXT': [
            { id: 'txtdata', label: 'Metin Verisi', placeholder: 'v=spf1 include:_spf.google.com ~all', type: 'textarea' }
        ]
    };

    function updateFormFields() {
        const type = document.getElementById('recordType').value;
        const container = document.getElementById('dynamicFields');
        const fields = fieldDefinitions[type] || [];

        let html = '';

        if (fields.length === 1) {
            // Tek alan - tam genişlik
            const f = fields[0];
            if (f.type === 'textarea') {
                html += `<div>
                    <label for="field_${f.id}" class="block text-sm font-medium text-gray-700 mb-1">${f.label}</label>
                    <textarea id="field_${f.id}" rows="3" class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border border-gray-300 rounded-lg px-3 py-2" placeholder="${f.placeholder}"></textarea>
                </div>`;
            } else {
                html += `<div>
                    <label for="field_${f.id}" class="block text-sm font-medium text-gray-700 mb-1">${f.label}</label>
                    <input type="${f.type}" id="field_${f.id}" class="block w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-blue-500 focus:border-blue-500 sm:text-sm" placeholder="${f.placeholder}">
                </div>`;
            }
        } else if (fields.length === 2) {
            // İki alan - yan yana
            html += '<div class="grid grid-cols-2 gap-4">';
            fields.forEach(f => {
                html += `<div>
                    <label for="field_${f.id}" class="block text-sm font-medium text-gray-700 mb-1">${f.label}</label>
                    <input type="${f.type}" id="field_${f.id}" class="block w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-blue-500 focus:border-blue-500 sm:text-sm" placeholder="${f.placeholder}">
                </div>`;
            });
            html += '</div>';
        } else if (fields.length > 2) {
            // Çok alan - grid düzeni
            html += '<div class="grid grid-cols-2 gap-4">';
            fields.forEach(f => {
                if (f.type === 'textarea') {
                    html += `</div><div class="mt-4">
                        <label for="field_${f.id}" class="block text-sm font-medium text-gray-700 mb-1">${f.label}</label>
                        <textarea id="field_${f.id}" rows="2" class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border border-gray-300 rounded-lg px-3 py-2" placeholder="${f.placeholder}"></textarea>
                    </div><div class="grid grid-cols-2 gap-4">`;
                } else {
                    html += `<div>
                        <label for="field_${f.id}" class="block text-sm font-medium text-gray-700 mb-1">${f.label}</label>
                        <input type="${f.type}" id="field_${f.id}" class="block w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-blue-500 focus:border-blue-500 sm:text-sm" placeholder="${f.placeholder}">
                    </div>`;
                }
            });
            html += '</div>';
        }

        container.innerHTML = html;
    }

    function renderRecords(data = records) {
        const tbody = document.getElementById('recordsTable');
        tbody.innerHTML = '';

        if (data.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="5" class="px-6 py-10 text-center text-gray-400">
                        <svg class="mx-auto h-12 w-12 text-gray-300" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                        <p class="mt-2 text-sm font-medium">Kayıt Bulunamadı</p>
                    </td>
                </tr>`;
            return;
        }

        data.forEach((record) => {
            const originalIndex = records.indexOf(record);

            // @ ise suffix göstermeyelim (istersen bunu kaldırıp her zaman gösterebilirsin)
            const showSuffix = record.name !== '@' && !String(record.name).endsWith('.');

            const row = document.createElement('tr');
            row.className = 'table-row-hover transition-colors duration-150 group';
            row.innerHTML = `
                <td class="px-6 py-4 whitespace-nowrap">
                    <span class="badge badge-${record.type || 'DEFAULT'}">${record.type}</span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                    ${record.name}
                    ${showSuffix ? `<span class="text-gray-400 group-hover:text-gray-500 font-normal ml-1 text-xs hidden sm:inline-block truncate max-w-[100px] align-bottom">.${domainName}</span>` : ''}
                </td>
                <td class="px-6 py-4 text-sm text-gray-600 font-mono break-all max-w-xs">
                    <div class="line-clamp-2" title="${String(record.content).replace(/"/g, '&quot;')}">${record.content}</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    ${record.ttl}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                    <button onclick="editRecord(${originalIndex})" class="text-blue-600 hover:text-blue-900 mr-3 p-1 hover:bg-blue-50 rounded smooth-transition" title="Düzenle">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" />
                        </svg>
                    </button>
                    ${record.line ?
                    `<button onclick="deleteRecord(${originalIndex})" class="text-red-600 hover:text-red-900 p-1 hover:bg-red-50 rounded smooth-transition" title="Sil">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                        </svg>
                    </button>` : ''}
                </td>
            `;
            tbody.appendChild(row);
        });
    }

    function updateRecordCount() {
        document.getElementById('recordCount').textContent = `Toplam ${records.length} kayıt`;
    }

    function sortTable(field) {
        if (currentSort.field === field) {
            currentSort.direction = currentSort.direction === 'asc' ? 'desc' : 'asc';
        } else {
            currentSort.field = field;
            currentSort.direction = 'asc';
        }

        records.sort((a, b) => {
            let aVal = a[field];
            let bVal = b[field];

            if (field === 'ttl') {
                aVal = parseInt(aVal) || 0;
                bVal = parseInt(bVal) || 0;
            } else {
                aVal = String(aVal).toLowerCase();
                bVal = String(bVal).toLowerCase();
            }

            if (aVal < bVal) return currentSort.direction === 'asc' ? -1 : 1;
            if (aVal > bVal) return currentSort.direction === 'asc' ? 1 : -1;
            return 0;
        });

        renderRecords();
        showNotification(`Kayıtlar ${field} alanına göre sıralandı`);
    }

    function showAddForm() {
        editingIndex = -1;
        document.getElementById('modalTitle').textContent = 'Yeni DNS Kaydı';
        document.getElementById('recordForm').reset();
        document.getElementById('recordType').value = 'A';
        updateFormFields();
        document.getElementById('recordModal').classList.remove('hidden');
        document.getElementById('recordName').focus();
    }

    function editRecord(index) {
        editingIndex = index;
        const rec = records[index];

        document.getElementById('modalTitle').textContent = 'Kaydı Düzenle';
        document.getElementById('recordType').value = rec.type;
        document.getElementById('recordName').value = normalizeName(rec.name);
        document.getElementById('recordTTL').value = rec.ttl;

        // Önce form alanlarını oluştur
        updateFormFields();

        // Sonra değerleri doldur
        setTimeout(() => {
            populateFieldsFromContent(rec.type, rec.content, rec.raw_keys || {});
        }, 50);

        document.getElementById('recordModal').classList.remove('hidden');
    }

    // Mevcut kayıt verisinden form alanlarını doldur
    function populateFieldsFromContent(type, content, rawKeys) {
        const fields = fieldDefinitions[type] || [];

        // raw_keys varsa öncelikli kullan
        if (rawKeys && Object.keys(rawKeys).length > 0) {
            fields.forEach(f => {
                const el = document.getElementById('field_' + f.id);
                if (el && rawKeys[f.id] !== undefined) {
                    el.value = rawKeys[f.id];
                }
            });
            return;
        }

        // raw_keys yoksa content'i parse et
        switch(type) {
            case 'A':
            case 'AAAA':
                setFieldValue('address', content);
                break;
            case 'CNAME':
                setFieldValue('cname', content);
                break;
            case 'NS':
                setFieldValue('nsdname', content);
                break;
            case 'PTR':
                setFieldValue('ptrdname', content);
                break;
            case 'TXT':
                setFieldValue('txtdata', content);
                break;
            case 'MX':
                const mxParts = content.trim().split(/\s+/);
                setFieldValue('preference', mxParts[0] || '10');
                setFieldValue('exchange', mxParts.slice(1).join(' ') || '');
                break;
            case 'SRV':
                const srvParts = content.trim().split(/\s+/);
                setFieldValue('priority', srvParts[0] || '0');
                setFieldValue('weight', srvParts[1] || '0');
                setFieldValue('port', srvParts[2] || '0');
                setFieldValue('target', srvParts.slice(3).join(' ') || '');
                break;
            case 'CAA':
                const caaParts = content.trim().split(/\s+/);
                setFieldValue('flag', caaParts[0] || '0');
                setFieldValue('tag', caaParts[1] || 'issue');
                setFieldValue('value', caaParts.slice(2).join(' ') || '');
                break;
            default:
                // Tek alanlı tipler için ilk alanı doldur
                if (fields.length > 0) {
                    setFieldValue(fields[0].id, content);
                }
        }
    }

    function setFieldValue(fieldId, value) {
        const el = document.getElementById('field_' + fieldId);
        if (el) el.value = value || '';
    }

    function closeModal() {
        document.getElementById('recordModal').classList.add('hidden');
    }

    function saveRecord(event) {
        event.preventDefault();

        const type = document.getElementById('recordType').value;
        const nameRaw = document.getElementById('recordName').value;
        const ttl = document.getElementById('recordTTL').value || '14400';
        const name = normalizeName(nameRaw);

        // Dinamik alanlardan değerleri topla
        const fields = fieldDefinitions[type] || [];
        let fieldValues = {};
        let content = '';

        fields.forEach(f => {
            const el = document.getElementById('field_' + f.id);
            if (el) {
                fieldValues[f.id] = el.value;
            }
        });

        // En az bir alanın dolu olduğunu kontrol et
        const hasValue = Object.values(fieldValues).some(v => v && String(v).trim() !== '');
        if (!hasValue) {
            showNotification('Lütfen gerekli alanları doldurun', 'error');
            return;
        }

        // Content oluştur (görüntüleme için)
        switch(type) {
            case 'A':
            case 'AAAA':
                content = fieldValues.address || '';
                break;
            case 'CNAME':
                content = fieldValues.cname || '';
                break;
            case 'NS':
                content = fieldValues.nsdname || '';
                break;
            case 'PTR':
                content = fieldValues.ptrdname || '';
                break;
            case 'TXT':
                content = fieldValues.txtdata || '';
                break;
            case 'MX':
                content = `${fieldValues.preference || 0} ${fieldValues.exchange || ''}`.trim();
                break;
            case 'SRV':
                content = `${fieldValues.priority || 0} ${fieldValues.weight || 0} ${fieldValues.port || 0} ${fieldValues.target || ''}`.trim();
                break;
            case 'CAA':
                content = `${fieldValues.flag || 0} ${fieldValues.tag || 'issue'} ${fieldValues.value || ''}`.trim();
                break;
            case 'AFSDB':
                content = `${fieldValues.subtype || 1} ${fieldValues.hostname || ''}`.trim();
                break;
            case 'DS':
                content = `${fieldValues.keytag || ''} ${fieldValues.algorithm || ''} ${fieldValues.digesttype || ''} ${fieldValues.digest || ''}`.trim();
                break;
            case 'HINFO':
                content = `${fieldValues.cpu || ''} ${fieldValues.os || ''}`.trim();
                break;
            case 'LOC':
                content = fieldValues.location || '';
                break;
            case 'NAPTR':
                content = `${fieldValues.order || ''} ${fieldValues.preference || ''} "${fieldValues.flags || ''}" "${fieldValues.service || ''}" "${fieldValues.regexp || ''}" ${fieldValues.replacement || '.'}`.trim();
                break;
            case 'RP':
                content = `${fieldValues.mbox || ''} ${fieldValues.txtdname || ''}`.trim();
                break;
            case 'DNAME':
                content = fieldValues.target || '';
                break;
            default:
                content = Object.values(fieldValues).join(' ').trim();
        }

        const newRecord = {
            line: editingIndex !== -1 ? records[editingIndex].line : null,
            type: type,
            name: name,
            content: content,
            ttl: ttl,
            class: 'IN',
            ...fieldValues
        };

        if (editingIndex === -1) {
            records.push(newRecord);
            showNotification('Kayıt listeye eklendi.', 'success');
        } else {
            records[editingIndex] = { ...records[editingIndex], ...newRecord };
            showNotification('Kayıt güncellendi', 'success');
        }

        closeModal();
        renderRecords();
        updateRecordCount();

        applyChanges(newRecord);
    }

    function deleteRecord(index) {
        const record = records[index];
        if (!record || !record.line) {
            showNotification('Bu kayıt silinemez (line bilgisi yok).', 'error');
            return;
        }

        const confirmMsg = `"${record.name}" (${record.type}) kaydını silmek istediğinize emin misiniz?`;
        if (!confirm(confirmMsg)) {
            return;
        }

        if (!serverId) {
            showNotification('Server ID eksik, işlem yapılamaz.', 'error');
            return;
        }

        const csrfToken = "<?php echo e(csrf_token()); ?>";

        fetch(`/dns/<?php echo e(rtrim($zoneDomain, '.')); ?>/delete`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "X-CSRF-TOKEN": csrfToken,
                "Accept": "application/json"
            },
            body: JSON.stringify({
                serverId: serverId,
                hash: hash,
                line: record.line
            })
        })
        .then(async res => {
            const isJson = res.headers.get('content-type')?.includes('application/json');
            const data = isJson ? await res.json() : null;

            if (!res.ok) {
                const errorMessage = (data && data.message) || res.statusText || 'Sunucu hatası';
                throw new Error(errorMessage);
            }
            return data;
        })
        .then(data => {
            if (!data || data.status === 'success' || data.ok === true) {
                // Listeden kaldır
                records.splice(index, 1);
                renderRecords();
                updateRecordCount();
                showNotification('Kayıt başarıyla silindi', 'success');
            } else if (data.status === 'error') {
                showNotification('Hata: ' + (data.message || 'Silme başarısız'), 'error');
            } else {
                records.splice(index, 1);
                renderRecords();
                updateRecordCount();
                showNotification('Kayıt başarıyla silindi', 'success');
            }
        })
        .catch(err => {
            showNotification('Silme Başarısız: ' + err.message, 'error');
            console.error(err);
        });
    }

    function applyChanges(record) {
        if (!serverId) {
            showNotification('Server ID eksik, işlem yapılamaz.', 'error');
            return;
        }

        const csrfToken = "<?php echo e(csrf_token()); ?>";

        fetch(`/dns/<?php echo e(rtrim($zoneDomain, '.')); ?>/apply`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "X-CSRF-TOKEN": csrfToken,
                "Accept": "application/json"
            },
            body: JSON.stringify({
                serverId: serverId,
                hash: hash,
                records: [record]
            })
        })
        .then(async res => {
            const isJson = res.headers.get('content-type')?.includes('application/json');
            const data = isJson ? await res.json() : null;

            if (!res.ok) {
                const errorMessage = (data && data.message) || res.statusText || 'Sunucu hatası';
                throw new Error(errorMessage);
            }
            return data;
        })
        .then(data => {
            // data null olabilir veya status alanı olmayabilir
            // HTTP 200 ile geldiyse başarılı kabul et
            if (!data || data.status === 'success' || data.ok === true) {
                showNotification('Değişiklikler sunucuda uygulandı', 'success');
            } else if (data.status === 'error') {
                showNotification('Hata: ' + (data.message || 'Bilinmeyen hata'), 'error');
            } else {
                // Bilinmeyen format ama HTTP 200 geldi, başarılı kabul et
                showNotification('Değişiklikler sunucuda uygulandı', 'success');
            }
        })
        .catch(err => {
            showNotification('İşlem Başarısız: ' + err.message, 'error');
            console.error(err);
        });
    }

    function showNotification(message, type = 'info') {
        const div = document.createElement('div');
        const colorClass = type === 'success' ? 'bg-green-600' : (type === 'error' ? 'bg-red-600' : (type === 'warning' ? 'bg-yellow-600' : 'bg-gray-800'));

        div.className = `fixed bottom-5 right-5 ${colorClass} text-white px-6 py-3 rounded-lg shadow-lg transform transition-all duration-300 translate-y-20 z-50 flex items-center font-medium text-sm`;
        div.innerHTML = `
            <svg class="w-5 h-5 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
            ${message}
        `;

        document.body.appendChild(div);

        requestAnimationFrame(() => {
            div.classList.remove('translate-y-20');
        });

        setTimeout(() => {
            div.classList.add('translate-y-20', 'opacity-0');
            setTimeout(() => div.remove(), 300);
        }, 3000);
    }

    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') closeModal();
    });
</script>

<?php echo $__env->make("layouts.footer", \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
<?php /**PATH /home/ssplus/sspanel.serversistemleri.com/resources/views/dns.blade.php ENDPATH**/ ?>