@extends('layout')

@section('title', __('store.clientarea_domains_manage_dns') . ' - ' . $domain->domain)

@section('content')
<div class="container py-5">
    <div class="row">
        <div class="col-md-12">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ route('store.auth.dashboard') }}">{{ __('store.clientarea_nav_dashboard') }}</a></li>
                    <li class="breadcrumb-item"><a href="{{ route('store.auth.domains') }}">{{ __('store.clientarea_nav_domains') }}</a></li>
                    <li class="breadcrumb-item active">{{ $domain->domain }}</li>
                    <li class="breadcrumb-item active">{{ __('store.clientarea_domains_dns_management') }}</li>
                </ol>
            </nav>

            <x-clientarea.page-header
                icon="fas fa-network-wired"
                :title="__('store.clientarea_domains_manage_dns')"
                :subtitle="$domain->domain"
            >
                <a href="{{ route('store.auth.domains') }}" class="btn btn-outline-secondary">
                    <i class="fas fa-arrow-left me-2"></i>{{ __('store.common_back') }}
                </a>
            </x-clientarea.page-header>

            {{-- PRC-299 — DNS provider source badge (DnsZone or Registrar) --}}
            @if(($dnsSource ?? null) && $dnsSource !== 'registrar')
                <div class="alert alert-success py-2 px-3 d-flex align-items-center gap-2 mb-3">
                    <i class="fas fa-check-circle"></i>
                    <span>
                        <strong>{{ __('store.clientarea_dns_managed_by') }}:</strong>
                        @if($dnsSource === 'cloudflare')
                            Cloudflare
                        @elseif($dnsSource === 'powerdns')
                            PowerDNS
                        @else
                            {{ ucfirst($dnsSource) }}
                        @endif
                        @if(isset($dnsZone) && $dnsZone?->last_synced_at)
                            <span class="text-muted small ms-2">
                                ({{ __('store.clientarea_dns_last_synced') }}: {{ $dnsZone->last_synced_at->diffForHumans() }})
                            </span>
                        @endif
                    </span>
                </div>
            @elseif(($dnsSource ?? null) === 'registrar')
                <div class="alert alert-info py-2 px-3 d-flex align-items-center gap-2 mb-3">
                    <i class="fas fa-info-circle"></i>
                    <span>{{ __('store.clientarea_dns_managed_by_registrar') }}</span>
                </div>
            @endif

            @if($domain->status !== 'active')
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    {{ __('store.clientarea_domains_dns_not_available_inactive') }}
                </div>
            @else
                <div class="card">
                    <div class="card-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">{{ __('store.clientarea_domains_dns_records') }}</h5>
                            <button class="btn btn-primary btn-sm" onclick="addDNSRecord()">
                                <i class="fas fa-plus me-2"></i>{{ __('store.clientarea_domains_add_record') }}
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            {{ __('store.clientarea_domains_dns_help_text') }}
                        </div>

                        <div id="dnsRecordsContainer">
                            <div class="text-center py-4">
                                <i class="fas fa-spinner fa-spin fa-2x text-muted mb-3"></i>
                                <p class="text-muted">{{ __('store.common_loading') }}</p>
                            </div>
                        </div>
                    </div>
                </div>
            @endif
        </div>
    </div>
</div>

<!-- DNS Record Modal -->
<div class="modal fade" id="dnsRecordModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="dnsRecordForm">
                <div class="modal-header">
                    <h5 class="modal-title" id="dnsRecordModalTitle">{{ __('store.clientarea_domains_add_record') }}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="recordId" name="record_id">

                    <div class="mb-3">
                        <label for="recordType" class="form-label">{{ __('store.clientarea_domains_record_type') }} <span class="text-danger">*</span></label>
                        <select class="form-select" id="recordType" name="type" required>
                            <option value="">{{ __('store.common_select') }}</option>
                            <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>
                        </select>
                        @error('type') <div class="invalid-feedback">{{ $message }}</div> @enderror
                    </div>

                    <div class="mb-3">
                        <label for="recordName" class="form-label">{{ __('store.clientarea_domains_record_name') }}</label>
                        <input type="text" class="form-control" id="recordName" name="name" placeholder="@, www, mail, etc.">
                        <div class="form-text">{{ __('store.clientarea_domains_record_name_help') }}</div>
                    </div>

                    <div class="mb-3">
                        <label for="recordValue" class="form-label">{{ __('store.clientarea_domains_record_value') }} <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="recordValue" name="value" required>
                        @error('value') <div class="invalid-feedback">{{ $message }}</div> @enderror
                        <div class="form-text" id="recordValueHelp">{{ __('store.clientarea_domains_record_value_help') }}</div>
                    </div>

                    <div class="mb-3" id="priorityField" style="display: none;">
                        <label for="recordPriority" class="form-label">{{ __('store.clientarea_domains_priority') }}</label>
                        <input type="number" class="form-control" id="recordPriority" name="priority" min="0" max="65535">
                    </div>

                    <div class="mb-3">
                        <label for="recordTTL" class="form-label">{{ __('store.clientarea_domains_ttl') }}</label>
                        <select class="form-select" id="recordTTL" name="ttl">
                            <option value="300">5 {{ __('store.common_minutes') }}</option>
                            <option value="1800">30 {{ __('store.common_minutes') }}</option>
                            <option value="3600" selected>1 {{ __('store.common_hour') }}</option>
                            <option value="14400">4 {{ __('store.common_hours') }}</option>
                            <option value="86400">1 {{ __('store.common_day') }}</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{{ __('store.common_cancel') }}</button>
                    <button type="submit" class="btn btn-primary">{{ __('store.common_save') }}</button>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
window.routes = window.routes || {};
window.routes.dnsRecords = '{{ route("store.auth.domains.manage.dns", $domain) }}/records';
window.routes.dnsRecordStore = '{{ route("store.auth.domains.manage.dns", $domain) }}/records';
window.routes.dnsRecordUpdate = '{{ route("store.auth.domains.manage.dns", $domain) }}/records/:id';
window.routes.dnsRecordDelete = '{{ route("store.auth.domains.manage.dns", $domain) }}/records/:id';

window.translations = window.translations || {};
window.translations.loading = '{{ __("store.common_loading") }}';
window.translations.error = '{{ __("store.common_error") }}';
window.translations.success = '{{ __("store.common_success") }}';
window.translations.confirmDelete = '{{ __("store.common_confirm_delete") }}';
window.translations.addRecord = '{{ __("store.clientarea_domains_add_record") }}';
window.translations.editRecord = '{{ __("store.clientarea_domains_edit_record") }}';

let dnsModal;

document.addEventListener('DOMContentLoaded', function() {
    dnsModal = new bootstrap.Modal(document.getElementById('dnsRecordModal'));
    loadDNSRecords();

    // Record type change handler
    document.getElementById('recordType').addEventListener('change', function() {
        const priorityField = document.getElementById('priorityField');
        const recordValueHelp = document.getElementById('recordValueHelp');

        if (this.value === 'MX') {
            priorityField.style.display = 'block';
            recordValueHelp.textContent = '{{ __("store.clientarea_domains_mx_value_help") }}';
        } else {
            priorityField.style.display = 'none';
            recordValueHelp.textContent = '{{ __("store.clientarea_domains_record_value_help") }}';
        }
    });

    // Form submission
    document.getElementById('dnsRecordForm').addEventListener('submit', function(e) {
        e.preventDefault();
        saveDNSRecord();
    });
});

function loadDNSRecords() {
    const container = document.getElementById('dnsRecordsContainer');

    fetch(window.routes.dnsRecords)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                container.innerHTML = data.html;
            } else {
                container.innerHTML = '<div class="alert alert-danger">' + (data.message || window.translations.error) + '</div>';
            }
        })
        .catch(error => {
            container.innerHTML = '<div class="alert alert-danger">' + window.translations.error + '</div>';
        });
}

function addDNSRecord() {
    document.getElementById('dnsRecordModalTitle').textContent = window.translations.addRecord;
    document.getElementById('dnsRecordForm').reset();
    document.getElementById('recordId').value = '';
    document.getElementById('priorityField').style.display = 'none';
    dnsModal.show();
}

function editDNSRecord(id, type, name, value, priority, ttl) {
    document.getElementById('dnsRecordModalTitle').textContent = window.translations.editRecord;
    document.getElementById('recordId').value = id;
    document.getElementById('recordType').value = type;
    document.getElementById('recordName').value = name;
    document.getElementById('recordValue').value = value;
    document.getElementById('recordPriority').value = priority || '';
    document.getElementById('recordTTL').value = ttl;

    if (type === 'MX') {
        document.getElementById('priorityField').style.display = 'block';
    }

    dnsModal.show();
}

function deleteDNSRecord(id) {
    if (!confirm(window.translations.confirmDelete)) {
        return;
    }

    fetch(window.routes.dnsRecordDelete.replace(':id', id), {
        method: 'DELETE',
        headers: {
            'X-CSRF-TOKEN': '{{ csrf_token() }}'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            loadDNSRecords();
        } else {
            alert(data.message || window.translations.error);
        }
    })
    .catch(error => {
        alert(window.translations.error);
    });
}

function saveDNSRecord() {
    const form = document.getElementById('dnsRecordForm');
    const formData = new FormData(form);
    const recordId = document.getElementById('recordId').value;

    const url = recordId ?
        window.routes.dnsRecordUpdate.replace(':id', recordId) :
        window.routes.dnsRecordStore;

    const method = recordId ? 'PUT' : 'POST';

    fetch(url, {
        method: method,
        headers: {
            'X-CSRF-TOKEN': '{{ csrf_token() }}'
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            dnsModal.hide();
            loadDNSRecords();
        } else {
            alert(data.message || window.translations.error);
        }
    })
    .catch(error => {
        alert(window.translations.error);
    });
}
</script>
@endpush