<?php $pageTitle = "DNS Yönetimi"; ?>
@extends('layouts.header')

<div class="container-fluid py-4">
    <!-- Back Button & Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <a href="{{ route('powerdns.index') }}" class="btn btn-outline-secondary me-2">
                <i class="fas fa-arrow-left me-1"></i> Geri
            </a>
            <h4 class="d-inline-block mb-0">
                <i class="fas fa-globe me-2 text-primary"></i>
                {{ rtrim($zone['name'] ?? '', '.') }}
            </h4>
        </div>
        <div>
            @if($isWhmcs)
                <span class="badge bg-success me-2">
                    <i class="fas fa-check me-1"></i> WHMCS
                </span>
            @else
                <span class="badge bg-warning me-2">
                    <i class="fas fa-exclamation-triangle me-1"></i> WHMCS Değil
                </span>
            @endif
            <a href="{{ route('powerdns.edit', ['zoneId' => rtrim($zone['name'], '.')]) }}" class="btn btn-primary btn-sm">
                <i class="fas fa-edit me-1"></i> Düzenle
            </a>
        </div>
    </div>

    <!-- Zone Info Card -->
    <div class="card shadow-sm mb-4">
        <div class="card-header bg-secondary text-white">
            <h6 class="mb-0"><i class="fas fa-info-circle me-2"></i> Zone Bilgileri</h6>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-3">
                    <strong>Kind:</strong>
                    <span class="badge bg-info">{{ $zone['kind'] ?? '-' }}</span>
                </div>
                <div class="col-md-3">
                    <strong>Serial:</strong>
                    {{ $zone['serial'] ?? '-' }}
                </div>
                <div class="col-md-3">
                    <strong>Account:</strong>
                    <span class="badge bg-success">{{ $zone['account'] ?? '-' }}</span>
                </div>
                <div class="col-md-3">
                    <strong>DNSSEC:</strong>
                    @if($zone['dnssec'] ?? false)
                        <span class="badge bg-success">Aktif</span>
                    @else
                        <span class="badge bg-secondary">Pasif</span>
                    @endif
                </div>
            </div>
        </div>
    </div>

    <!-- DNS Records -->
    <div class="card shadow-sm">
        <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
            <h6 class="mb-0"><i class="fas fa-list me-2"></i> DNS Kayıtları</h6>
            <button class="btn btn-light btn-sm" data-bs-toggle="modal" data-bs-target="#addRecordModal">
                <i class="fas fa-plus me-1"></i> Kayıt Ekle
            </button>
        </div>
        <div class="card-body">
            @if(count($recordsByType) > 0)
                <!-- Record Type Tabs -->
                <ul class="nav nav-tabs" id="recordTabs" role="tablist">
                    @foreach($recordsByType as $type => $records)
                        <li class="nav-item" role="presentation">
                            <button class="nav-link {{ $loop->first ? 'active' : '' }}"
                                    id="tab-{{ $type }}"
                                    data-bs-toggle="tab"
                                    data-bs-target="#content-{{ $type }}"
                                    type="button"
                                    role="tab">
                                {{ $type }}
                                <span class="badge bg-secondary ms-1">{{ count($records) }}</span>
                            </button>
                        </li>
                    @endforeach
                </ul>

                <div class="tab-content mt-3" id="recordTabsContent">
                    @foreach($recordsByType as $type => $records)
                        <div class="tab-pane fade {{ $loop->first ? 'show active' : '' }}"
                             id="content-{{ $type }}"
                             role="tabpanel">
                            <div class="table-responsive">
                                <table class="table table-sm table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Name</th>
                                            <th>TTL</th>
                                            <th>Content</th>
                                            <th class="text-center">İşlemler</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @foreach($records as $rrset)
                                            @foreach($rrset['records'] ?? [] as $record)
                                                <tr>
                                                    <td class="text-break">
                                                        <code>{{ rtrim($rrset['name'] ?? '', '.') }}</code>
                                                    </td>
                                                    <td>{{ $rrset['ttl'] ?? '-' }}</td>
                                                    <td class="text-break">
                                                        <small>{{ $record['content'] ?? '-' }}</small>
                                                    </td>
                                                    <td class="text-center">
                                                        <button class="btn btn-outline-danger btn-sm btn-delete-record"
                                                                data-name="{{ $rrset['name'] }}"
                                                                data-type="{{ $rrset['type'] }}"
                                                                title="Sil">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    </td>
                                                </tr>
                                            @endforeach
                                        @endforeach
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    @endforeach
                </div>
            @else
                <div class="alert alert-info text-center">
                    <i class="fas fa-info-circle me-2"></i>
                    Bu zone için DNS kaydı bulunamadı.
                </div>
            @endif
        </div>
    </div>
</div>

<!-- Add Record Modal -->
<div class="modal fade" id="addRecordModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title"><i class="fas fa-plus me-2"></i> Yeni DNS Kaydı</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form id="addRecordForm">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Kayıt Adı</label>
                        <input type="text" class="form-control" name="name" required
                               placeholder="subdomain.{{ rtrim($zone['name'] ?? '', '.') }}">
                        <small class="text-muted">Tam domain adı girin (örn: www.example.com)</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Kayıt Tipi</label>
                        <select class="form-select" name="type" 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>
                            <option value="CAA">CAA</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">İçerik</label>
                        <input type="text" class="form-control" name="content" required
                               placeholder="192.168.1.1">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">TTL (saniye)</label>
                        <input type="number" class="form-control" name="ttl" value="3600" min="60" max="86400">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">İptal</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-1"></i> Kaydet
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const zoneId = '{{ rtrim($zone["name"] ?? "", ".") }}';
    const addModal = new bootstrap.Modal(document.getElementById('addRecordModal'));

    // Add Record Form
    document.getElementById('addRecordForm').addEventListener('submit', async function(e) {
        e.preventDefault();
        const formData = new FormData(this);
        const data = Object.fromEntries(formData);
        data.ttl = parseInt(data.ttl);

        const btn = this.querySelector('button[type="submit"]');
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> Kaydediliyor...';

        try {
            const response = await fetch(`/api/powerdns/zones/${zoneId}/records`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                },
                body: JSON.stringify(data)
            });

            const result = await response.json();

            if (result.success) {
                addModal.hide();
                location.reload();
            } else {
                alert('Hata: ' + (result.message || 'Kayıt eklenemedi'));
            }
        } catch (error) {
            alert('Bir hata oluştu: ' + error.message);
        }

        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-save me-1"></i> Kaydet';
    });

    // Delete Record
    document.querySelectorAll('.btn-delete-record').forEach(btn => {
        btn.addEventListener('click', async function() {
            const name = this.dataset.name;
            const type = this.dataset.type;

            if (!confirm(`${name} (${type}) kaydını silmek istediğinize emin misiniz?`)) {
                return;
            }

            try {
                const response = await fetch(`/api/powerdns/zones/${zoneId}/records`, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    },
                    body: JSON.stringify({ name, type })
                });

                const result = await response.json();

                if (result.success) {
                    location.reload();
                } else {
                    alert('Hata: ' + (result.message || 'Kayıt silinemedi'));
                }
            } catch (error) {
                alert('Bir hata oluştu: ' + error.message);
            }
        });
    });
});
</script>
