@extends('layouts.admin')

@section('admin-content')
    @push('styles')
        <style>
            .select2-container--default .select2-selection--single {
                height: calc(2.25rem + 2px);
                padding: 0.375rem 0.75rem;
                border: 1px solid #ced4da;
                border-radius: 0.375rem;
                display: flex;
                align-items: center;
            }

            .select2-container--default .select2-selection--single .select2-selection__rendered {
                padding-left: 0;
                line-height: normal;
            }

            .select2-container--default .select2-selection--single .select2-selection__arrow {
                height: 100%;
                right: 10px;
            }

            .select2-container--default .select2-dropdown {
                background-color: #ffffff;
                color: #212529;
            }
        </style>
    @endpush

    <div class="admin-page-header mb-4 d-flex justify-content-between align-items-center">
        <div>
            <h1 class="mb-1">
                <i class="fas fa-globe me-2"></i> Domain Monitor
            </h1>
            <p class="text-muted mb-0">
                Monitor all license domains uptime and availability
            </p>
        </div>

        <a href="{{ route('admin.domain-monitor.assign') }}" class="btn btn-primary">
            <i class="fas fa-plus me-1"></i> Assign Domain
        </a>
    </div>

    {{-- FILTERS --}}
    <div class="card mb-4">
        <div class="card-body">
            <div class="row g-3">

                {{-- PRODUCT --}}
                <div class="col-md-4">
                    <label class="form-label fw-semibold">Select Client</label>
                    <select id="productSelect" class="form-select select2">
                        <option value="">All Clients</option>
                        @foreach ($licenses->pluck('product')->unique('id') as $product)
                            <option value="{{ $product->id }}">{{ $product->name }}</option>
                        @endforeach
                    </select>
                </div>

                {{-- LICENSE --}}
                <div class="col-md-4">
                    <label class="form-label fw-semibold">License</label>
                    <select id="licenseSelect" class="form-select select2" disabled>
                        <option value="">Select License</option>
                    </select>
                </div>

                {{-- DOMAIN --}}
                <div class="col-md-4">
                    <label class="form-label fw-semibold">Domain</label>
                    <select id="domainSelect" class="form-select select2" disabled>
                        <option value="">Select Domain</option>
                    </select>
                </div>

                {{-- SEARCH --}}
                <div class="col-md-12">
                    <label class="form-label fw-semibold">Search Domain</label>
                    <input type="text" id="domainSearch" class="form-control" placeholder="Search by domain name...">
                </div>

            </div>
        </div>
    </div>

    {{-- TABLE --}}
    <div class="card">
        <div class="card-body p-0">
            <div class="table-responsive">

                <table class="table table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>#</th>
                            <th>License</th>
                            <th>Domain</th>
                            <th class="text-center">Status</th>
                            <th class="text-center">Last Checked</th>
                            <th class="text-center">Action</th>
                        </tr>
                    </thead>

                    <tbody id="domainTable">
                        @foreach ($domains as $i => $domain)
                            <tr data-product="{{ $domain['product_id'] }}" data-license="{{ $domain['license_id'] }}"
                                data-domain="{{ $domain['id'] }}">
                                <td>{{ $i + 1 }}</td>

                                <td>
                                    <strong>
                                        {{ $domain['license_key'] ?? 'License #' . $domain['license_id'] }}
                                        ({{ $domain['product_name'] ?? '—' }})
                                    </strong>
                                </td>

                                <td class="domain-text">{{ $domain['domain'] }}</td>

                                <td class="text-center">
                                    <span class="badge bg-{{ $domain['status'] === 'up' ? 'success' : 'danger' }}">
                                        {{ strtoupper($domain['status']) }}
                                    </span>
                                </td>

                                <td class="text-center">{{ $domain['last_checked'] ?? '—' }}</td>

                                <td class="text-center">
                                    <button class="btn btn-sm btn-danger delete-domain" data-id="{{ $domain['id'] }}">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>

                </table>

            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script>
        $(document).ready(function() {

            $('.select2').select2({
                width: '100%'
            });

            function resetSelect($select, placeholder) {
                $select.html(`<option value="">${placeholder}</option>`)
                    .prop('disabled', true)
                    .val('')
                    .trigger('change.select2');
            }

            function renderTable(domains) {
                let html = '';

                if (!domains.length) {
                    html = `<tr><td colspan="6" class="text-center">No records found</td></tr>`;
                } else {
                    domains.forEach((d, i) => {
                        const badge = d.monitor_status === 'up' ? 'success' : 'danger';
                        html += `
                    <tr data-product="${d.product_id}"
                        data-license="${d.license_id}"
                        data-domain="${d.id}">
                        <td>${i + 1}</td>
                        <td><strong>${d.license_key} (${d.product_name})</strong></td>
                        <td class="domain-text">${d.domain}</td>
                        <td class="text-center">
                            <span class="badge bg-${badge}">
                                ${d.monitor_status.toUpperCase()}
                            </span>
                        </td>
                        <td class="text-center">${d.last_checked ?? '—'}</td>
                        <td class="text-center">
                            <button class="btn btn-sm btn-danger delete-domain"
                                    data-id="${d.id}">
                                <i class="fas fa-trash"></i>
                            </button>
                        </td>
                    </tr>`;
                    });
                }

                $('#domainTable').html(html);
            }

            function filterTable() {
                const licenseId = $('#licenseSelect').val();
                const domainId = $('#domainSelect').val();

                $('#domainTable tr').each(function() {
                    let show = true;
                    if (licenseId && $(this).data('license') != licenseId) show = false;
                    if (domainId && $(this).data('domain') != domainId) show = false;
                    $(this).toggle(show);
                });
            }

            $('#productSelect').on('change', function() {
                const productId = $(this).val();

                resetSelect($('#licenseSelect'), 'Select License');
                resetSelect($('#domainSelect'), 'Select Domain');

                if (!productId) return;

                $.get(`/admin/domains-by-product/${productId}`, function(domains) {

                    if (!Array.isArray(domains)) {
                        domains = [domains];
                    }

                    renderTable(domains);

                    let hasLicenses = false;
                    const licenses = {};

                    domains.forEach(d => {
                        if (d.license_id && d.license_key) {
                            licenses[d.license_id] = d.license_key;
                            hasLicenses = true;
                        }
                    });

                    if (hasLicenses) {
                        Object.entries(licenses).forEach(([id, key]) => {
                            $('#licenseSelect').append(
                                `<option value="${id}">${key}</option>`);
                        });

                        $('#licenseSelect').prop('disabled', false).trigger('change.select2');
                    }
                });

            });

            $('#licenseSelect').on('change', function() {
                resetSelect($('#domainSelect'), 'Select Domain');
                filterTable();

                $('#domainTable tr:visible').each(function() {
                    $('#domainSelect').append(
                        `<option value="${$(this).data('domain')}">${$(this).find('.domain-text').text()}</option>`
                    );
                });

                $('#domainSelect').prop('disabled', false).trigger('change.select2');
            });

            $('#domainSelect').on('change', filterTable);

            $('#domainSearch').on('keyup', function() {
                const value = $(this).val().toLowerCase();
                $('#domainTable tr').each(function() {
                    $(this).toggle($(this).find('.domain-text').text().toLowerCase().includes(
                        value));
                });
            });

            $(document).on('click', '.delete-domain', function() {
                const domainId = $(this).data('id');
                if (!confirm('Delete this domain?')) return;

                $.ajax({
                    url: `/admin/domain-monitor/${domainId}`,
                    type: 'DELETE',
                    data: {
                        _token: $('meta[name="csrf-token"]').attr('content')
                    },
                    success: () => $(`button[data-id="${domainId}"]`).closest('tr').remove(),
                    error: () => alert('Delete failed')
                });
            });

        });
    </script>
@endpush
