<?php $pageTitle = 'DNS Kayıtları'; ?>
@include("layouts.header")
  <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
  <style media="screen">
    #recordModal select, input, textarea{
      color: black;
    }
  </style>
  <div style="width: 100%;" class=" mx-auto p-6">
    <!-- DNS Management Card -->
    <div class="bg-white border border-gray-200 rounded-lg shadow-sm overflow-hidden">
      <!-- Card Header -->
      <div class="px-6 py-4 border-b border-gray-200 bg-gray-50">
        <div class="flex justify-between items-start">
          <div>
            <h2 class="text-lg font-semibold text-gray-900 mb-1">DNS yönetimi <strong class="text-blue-600"><?php echo $dnsZone['id']; ?></strong> için</h2>
            <p class="text-sm text-gray-600">DNS kayıtlarını inceleyin, ekleyin ve düzenleyin. Düzenlemeler kaydedildikten sonra etkili olacaktır.</p>
            <p class="text-sm text-gray-600 dark:text-gray-800">
              ⚠️ <strong>Uyarı:</strong> Yapacağınız işlemler kaydedilecek ve geri alınamaz. Sayfa yenileme güvenlik nedeniyle engellenmiştir.
            </p>
          </div>
          <div class="flex flex-col items-end space-y-2">
            <div class="flex items-center space-x-2 px-3 py-1 bg-green-50 border border-green-200 rounded-md">
              <div class="w-2 h-2 bg-green-500 rounded-full"></div>
              <span class="text-sm font-medium text-green-800">DNS Kurulumu: Tam</span>
            </div>
            <div class="flex space-x-3">
              <button class="text-blue-600 hover:text-blue-800 text-sm font-medium smooth-transition" onclick="importExport()">İçe ve Dışa Aktar</button>
              <button class="text-blue-600 hover:text-blue-800 text-sm font-medium smooth-transition" onclick="dashboardSettings()">Gösterge Paneli Ayarları</button>
            </div>
          </div>
        </div>
      </div>

      <!-- Search and Actions -->
      <div class="px-6 py-4 border-b border-gray-200">
        <div class="flex items-center space-x-3">
          <button class="px-4 py-2 bg-gray-100 hover:bg-gray-200 border border-gray-300 rounded-md text-sm font-medium text-gray-700 smooth-transition flex items-center space-x-2" onclick="addFilter()">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"></path>
            </svg>
            <span>Filtre Ekle</span>
          </button>

          <div class="flex-1 relative">
            <svg class="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
            </svg>
            <input type="text" id="searchInput" placeholder="DNS Kayıtlarında Ara" class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm" />
          </div>

          <button class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md text-sm font-medium smooth-transition" onclick="searchRecords()">Ara</button>
          <button class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md text-sm font-medium smooth-transition flex items-center space-x-2" onclick="showAddForm()">
            <svg class="w-4 h-4" 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>
            <span>Kayıt Ekle</span>
          </button>
        </div>
      </div>

      <!-- DNS Records Table -->
      <div class="overflow-x-auto custom-scrollbar">
        <table class="w-full">
          <thead class="bg-gray-50 border-b border-gray-200">
            <tr>
              <th class="text-left px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100 smooth-transition" onclick="sortTable('type')">
                <div class="flex items-center space-x-1">
                  <span>Tür</span>
                  <svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4"></path>
                  </svg>
                </div>
              </th>
              <th class="text-left px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100 smooth-transition" onclick="sortTable('name')">
                <div class="flex items-center space-x-1">
                  <span>Ad</span>
                  <svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4"></path>
                  </svg>
                </div>
              </th>
              <th class="text-left px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100 smooth-transition" onclick="sortTable('content')">
                <div class="flex items-center space-x-1">
                  <span>İçerik</span>
                  <svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4"></path>
                  </svg>
                </div>
              </th>
              <th class="text-left px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100 smooth-transition" onclick="sortTable('ttl')">
                <div class="flex items-center space-x-1">
                  <span>TTL</span>
                  <svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4"></path>
                  </svg>
                </div>
              </th>
              <th class="text-left px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">İşlemler</th>
            </tr>
          </thead>
          <tbody id="recordsTable" class="bg-white divide-y divide-gray-200">
            <!-- Records will be populated here -->
          </tbody>
        </table>
      </div>
    </div>

    <!-- Server Sistemleri Nameservers -->
    <div class="mt-6 bg-white border border-gray-200 rounded-lg shadow-sm overflow-hidden">
      <div class="px-6 py-4 border-b border-gray-200 bg-gray-50">
        <h2 class="text-lg font-semibold text-gray-900">Server Sistemleri Nameserver'ları</h2>
        <p class="text-sm text-gray-600 mt-1">Server Sistemleri'deki her DNS bölgesi, Server Sistemleri markalı nameserver'lar kümesine atanır.</p>
      </div>
      <div class="overflow-x-auto">
        <table class="w-full">
          <thead class="bg-gray-50 border-b border-gray-200">
            <tr>
              <th class="text-left px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">Tür</th>
              <th class="text-left px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">Değer</th>
              <th class="text-left px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">iP Adresi</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">NS</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600 font-mono">ns1.serversistemleri.com</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600 font-mono">185.37.102.2</td>
            </tr>
            <tr>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">NS</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600 font-mono">ns2.serversistemleri.com</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600 font-mono">193.3.35.2</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- Add/Edit Record Modal -->
  <div id="recordModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50 p-4">
    <div class="bg-white rounded-lg shadow-xl max-w-lg w-full max-h-[90vh] overflow-y-auto">
      <div class="px-6 py-4 border-b border-gray-200">
        <div class="flex justify-between items-center">
          <h3 class="text-lg font-semibold text-gray-900" id="modalTitle">DNS Kaydı Ekle</h3>
          <button onclick="closeModal()" class="text-gray-400 hover:text-gray-600 smooth-transition">
            <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="M6 18L18 6M6 6l12 12"></path>
            </svg>
          </button>
        </div>
      </div>

      <div class="px-6 py-4">
        <form id="recordForm" onsubmit="saveRecord(event)">
          <div class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Tür</label>
                <select id="recordType" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm" required>
                  <option value="A">A</option>
                  <option value="AAAA">AAAA</option>
                  <option value="CNAME">CNAME</option>
                  <option value="MX">MX</option>
                  <option value="TXT">TXT</option>
                  <option value="NS">NS</option>
                  <option value="SRV">SRV</option>
                </select>
              </div>

              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Ad</label>
                <input type="text" id="recordName" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm" placeholder="örn: www" required>
              </div>
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">İçerik</label>
              <textarea id="recordContent" rows="3" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm resize-none" placeholder="örn: 192.168.1.1" required></textarea>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-1 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">TTL</label>
                <select id="recordTTL" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm">
                  <option value="Auto">Otomatik</option>
                  <option value="1">1 saniye</option>
                  <option value="30">30 saniye</option>
                  <option value="60">1 dakika</option>
                  <option value="300">5 dakika</option>
                  <option value="900">15 dakika</option>
                  <option value="1800">30 dakika</option>
                  <option value="3600">1 saat</option>
                  <option value="7200">2 saat</option>
                  <option value="14400">4 saat</option>
                  <option value="18000">5 saat</option>
                  <option value="43200">12 saat</option>
                  <option value="86400">1 gün</option>
                </select>
              </div>
            </div>
          </div>

          <div class="flex justify-end space-x-3 mt-6 pt-6 border-t border-gray-200">
            <button type="button" onclick="closeModal()" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 smooth-transition text-sm font-medium">
              İptal
            </button>
            <button type="submit" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md smooth-transition text-sm font-medium">
              Kaydet
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <script>
  // DNS Records Data from PHP
  const dnsRecords = <?php echo json_encode(array_merge(...array_map(function ($rr) {
      $type = $rr['type'];
      $ttl = $rr['ttl'] ?? 'Auto';
      $name = rtrim($rr['name'], '.');
      return array_map(function ($record) use ($type, $ttl, $name) {
          return [
              'type' => $type,
              'name' => $name,
              'content' => trim($record['content'], '"'),
              'ttl' => $ttl,
          ];
      }, $rr['records']);
  }, $dnsZone['rrsets'] ?? [])), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;

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

  // Initialize records
  document.addEventListener('DOMContentLoaded', function() {
      records = [...dnsRecords];
      renderRecords();

      // Search functionality
      document.getElementById('searchInput').addEventListener('input', function() {
          filterRecords(this.value);
      });
  });

  // Truncate text function
  function truncateText(text, maxLength = 60) {
      if (text.length <= maxLength) return text;
      return text.substring(0, maxLength) + '...';
  }

  // Get record type class
  function getRecordTypeClass(type) {
      const typeMap = {
          'A': 'a',
          'AAAA': 'aaaa',
          'CNAME': 'cname',
          'MX': 'mx',
          'TXT': 'txt',
          'NS': 'ns',
          'SRV': 'srv'
      };
      return typeMap[type] || 'a';
  }

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

      if (records.length === 0) {
          tbody.innerHTML = `
              <tr>
                  <td colspan="6" class="px-6 py-8 text-center text-gray-500">
                      <svg class="w-12 h-12 mx-auto mb-4 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                      </svg>
                      <p class="text-lg font-medium">DNS kaydı bulunamadı</p>
                      <p class="text-sm">Yeni bir DNS kaydı ekleyerek başlayın.</p>
                  </td>
              </tr>
          `;
          return;
      }

      records.forEach((record, index) => {
          const row = document.createElement('tr');
          row.className = 'table-row-hover smooth-transition';

          row.innerHTML = `
              <td class="px-6 py-4 whitespace-nowrap">
                  <span style="text-align:center;" class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${record.type}</span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${truncateText(record.name)}</td>
              <td class="px-6 py-4 text-sm text-gray-600 font-mono">
                  <span title="${record.content}">${truncateText(record.content)}</span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">${record.ttl}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm">
                  <div class="flex items-center space-x-2">
                      <button onclick="editRecord(${index})" class="text-blue-600 hover:text-blue-800 smooth-transition p-1 rounded" title="Düzenle">
                          <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                          </svg>
                      </button>
                      <button onclick="deleteRecord(${index})" class="text-red-600 hover:text-red-800 smooth-transition p-1 rounded" title="Sil">
                          <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <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"></path>
                          </svg>
                      </button>
                  </div>
              </td>
          `;

          tbody.appendChild(row);
      });
  }

  // Filter records
  function filterRecords(searchTerm) {
      const filtered = dnsRecords.filter(record =>
          record.type.toLowerCase().includes(searchTerm.toLowerCase()) ||
          record.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
          record.content.toLowerCase().includes(searchTerm.toLowerCase())
      );

      records = filtered;
      renderRecords();
  }

  const domain = "{{ rtrim($dnsZone['id'], '.') }}"; // Laravel route için noktayı kaldır
  // Sort table
  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 === 'Auto') aVal = 0;
          if (field === 'ttl' && bVal === 'Auto') bVal = 0;

          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ı`, 'info');
  }

  // Show add record form
  function showAddForm() {
      editingIndex = -1;
      document.getElementById('modalTitle').textContent = 'DNS Kaydı Ekle';
      document.getElementById('recordForm').reset();
      document.getElementById('recordModal').classList.remove('hidden');
  }

  // Edit record
  function editRecord(index) {
      editingIndex = index;
      const record = records[index];

      document.getElementById('modalTitle').textContent = 'DNS Kaydını Düzenle';
      document.getElementById('recordType').value = record.type;
      document.getElementById('recordName').value = record.name;
      document.getElementById('recordContent').value = record.content;
      document.getElementById('recordTTL').value = record.ttl;

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

  function applySingleChange(record) {
      fetch(`/dns/{{ rtrim($dnsZone['id'], '.') }}/apply`, {
          method: "POST",
          headers: {
              "Content-Type": "application/json",
              "X-CSRF-TOKEN": "<?php echo csrf_token(); ?>"
          },
          credentials: "same-origin",
          body: JSON.stringify({ records: [record] }) // sadece 1 kayıt gönderiyoruz
      })
      .then(response => response.json())
      .then(data => {
          if (data.status === "success") {
              showNotification("Kayıt başarıyla uygulandı", "success");
          } else {
              showNotification("Hata: " + data.message, "error");
          }
      })
      .catch(err => {
          showNotification("İstek hatası: " + err.message, "error");
      });
  }

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

      const record = {
          type: document.getElementById('recordType').value,
          name: document.getElementById('recordName').value,
          content: document.getElementById('recordContent').value,
          ttl: document.getElementById('recordTTL').value,
      };

      if (editingIndex === -1) {
          records.push(record);
          showNotification('DNS kaydı başarıyla eklendi', 'success');
      } else {
          records[editingIndex] = record;
          showNotification('DNS kaydı başarıyla güncellendi', 'success');
      }

      closeModal();
      renderRecords();

      applySingleChange(record); // 🔥 Tüm kayıtları değil sadece bu kaydı gönder
  }
  function applyChanges() {
      fetch(`/dns/{{ rtrim($dnsZone['id'], '.') }}/apply`, {
          method: "POST",
          headers: {
              "Content-Type": "application/json",
              "X-CSRF-TOKEN": "<?php echo csrf_token(); ?>"
          },
          credentials: "same-origin",
          body: JSON.stringify({ records })
      })
      .then(response => response.json())
      .then(data => {
          if (data.status === "success") {
              showNotification("Kayıtlar başarıyla uygulandı", "success");
          } else {
              showNotification("Hata: " + data.message, "error");
          }
      })
      .catch(err => {
          showNotification("İstek hatası: " + err.message, "error");
      });
  }
  // Delete record
  function deleteRecord(index) {
      if (confirm('Bu DNS kaydını silmek istediğinizden emin misiniz?')) {
          records.splice(index, 1);
          renderRecords();
          showNotification('DNS kaydı başarıyla silindi', 'success');
      }
  }

  // Close modal
  function closeModal() {
      document.getElementById('recordModal').classList.add('hidden');
      editingIndex = -1;
  }

  // Search records
  function searchRecords() {
      const searchTerm = document.getElementById('searchInput').value;
      filterRecords(searchTerm);
  }

  // Add filter (placeholder)
  function addFilter() {
      showNotification('Filtre özelliği yakında eklenecek', 'info');
  }

  // Import/Export (placeholder)
  function importExport() {
      showNotification('İçe/Dışa aktarma özelliği yakında eklenecek', 'info');
  }

  // Dashboard settings (placeholder)
  function dashboardSettings() {
      showNotification('Gösterge paneli ayarları yakında eklenecek', 'info');
  }

  // Show notification
  function showNotification(message, type = 'info') {
      const notification = document.createElement('div');
      notification.className = `fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 text-white font-medium smooth-transition ${
          type === 'success' ? 'bg-green-500' :
          type === 'error' ? 'bg-red-500' :
          'bg-blue-500'
      }`;
      notification.textContent = message;

      document.body.appendChild(notification);

      setTimeout(() => {
          notification.remove();
      }, 3000);
  }

  // Close modal when clicking outside
  document.getElementById('recordModal').addEventListener('click', function(e) {
      if (e.target === this) {
          closeModal();
      }
  });

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

@include("layouts.footer")
