@extends('backoffice.layouts.app')

@section('title', 'Payment Popups')

@section('content')
<div class="container-fluid payment-popups-page">
    <div class="hero-block mb-4">
        <div>
            <h2 class="mb-1"><i class="bi bi-images me-2"></i>Yatırım Popup Yönetimi</h2>
            <p class="mb-0">Site bazli masaüstü ve mobil popup görsellerini yönetin.</p>
        </div>
        <div class="hero-dimensions">
            <span class="dim-chip"><i class="bi bi-display me-1"></i>{{ $desktopRecommended }}</span>
            <span class="dim-chip"><i class="bi bi-phone me-1"></i>{{ $mobileRecommended }}</span>
        </div>
    </div>

    @if($sites->isEmpty())
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center py-5 text-muted">
                Site bulunamadı.
            </div>
        </div>
    @else
        <div class="card border-0 shadow-sm overflow-hidden">
            <div class="card-body p-0">
                <div class="site-tabs-wrap">
                    <ul class="nav nav-pills popup-site-tabs" role="tablist">
                        @foreach($sites as $site)
                            @php
                                $popup = $site->paymentPopup;
                                $hasDesktop = !empty($popup?->desktop_image_url);
                                $hasMobile = !empty($popup?->mobile_image_url);
                            @endphp
                            <li class="nav-item" role="presentation">
                                <button
                                    class="nav-link {{ $loop->first ? 'active' : '' }}"
                                    data-bs-toggle="tab"
                                    data-bs-target="#popupSiteTab{{ $site->id }}"
                                    type="button"
                                    role="tab"
                                >
                                    <span>{{ $site->name }}</span>
                                </button>
                            </li>
                        @endforeach
                    </ul>
                </div>

                <div class="tab-content p-4">
                    @foreach($sites as $site)
                        @php
                            $popup = $site->paymentPopup;
                            $desktopUrl = $popup?->desktop_image_url;
                            $mobileUrl = $popup?->mobile_image_url;
                            $hasDesktop = !empty($desktopUrl);
                            $hasMobile = !empty($mobileUrl);
                            $desktopEnabled = $hasDesktop && (bool) ($popup?->desktop_enabled ?? false);
                            $mobileEnabled = $hasMobile && (bool) ($popup?->mobile_enabled ?? false);
                            $popupClickUrl = (string) ($popup?->popup_click_url ?? '');
                            $popupFooterText = (string) ($popup?->popup_footer_text ?? '');
                            $popupFooterUrl = (string) ($popup?->popup_footer_url ?? '');
                        @endphp
                        <div class="tab-pane fade {{ $loop->first ? 'show active' : '' }}" id="popupSiteTab{{ $site->id }}" role="tabpanel">
                            <form class="popup-form" data-site-id="{{ $site->id }}">
                                @csrf
                                <input type="hidden" name="desktop_enabled" value="{{ $desktopEnabled ? 1 : 0 }}">
                                <input type="hidden" name="mobile_enabled" value="{{ $mobileEnabled ? 1 : 0 }}">
                                <input type="hidden" name="desktop_delete" value="0">
                                <input type="hidden" name="mobile_delete" value="0">

                                <div class="site-head mb-4">
                                    <h5 class="mb-1">{{ $site->name }}</h5>
                                    <p class="mb-0 text-muted">Her cihaz tipi için tek görsel yüklenir. Yükleme işlemi mevcut görselin yerini alır.</p>
                                </div>

                                <div class="row g-4">
                                    <div class="col-xl-6">
                                        <div class="device-card" data-device="desktop" data-has-image="{{ $hasDesktop ? '1' : '0' }}">
                                            <div class="device-card-head">
                                                <div>
                                                    <h6 class="mb-1"><i class="bi bi-display me-2"></i>Masaüstü Popup</h6>
                                                    <small class="text-muted">Önerilen boyut: {{ $desktopRecommended }}</small>
                                                </div>
                                                <span class="status-pill {{ $desktopEnabled ? 'status-visible' : 'status-hidden' }}">
                                                    {{ $desktopEnabled ? 'Yayinda' : 'Gizli' }}
                                                </span>
                                            </div>

                                            <div class="preview-stage mb-3">
                                                <img
                                                    src="{{ $desktopUrl ?: 'data:image/svg+xml;utf8,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%22640%22 height=%22360%22><rect width=%22100%25%22 height=%22100%25%22 fill=%22%23111827%22/><text x=%2250%25%22 y=%2250%25%22 dominant-baseline=%22middle%22 text-anchor=%22middle%22 fill=%22%239ca3af%22 font-size=%2222%22 font-family=%22Arial%22>Desktop image yok</text></svg>' }}"
                                                    class="device-preview desktop-preview"
                                                    alt="Desktop popup"
                                                >
                                            </div>

                                            <div class="device-actions">
                                                <div class="device-actions-row">
                                                    <div class="form-check form-switch visibility-switch-wrap">
                                                        <input
                                                            class="form-check-input visibility-switch"
                                                            type="checkbox"
                                                            id="desktopVisibility{{ $site->id }}"
                                                            data-target="desktop_enabled"
                                                            {{ $desktopEnabled ? 'checked' : '' }}
                                                            {{ $hasDesktop ? '' : 'disabled' }}
                                                        >
                                                        <label class="form-check-label visibility-switch-label" for="desktopVisibility{{ $site->id }}">
                                                            {{ $desktopEnabled ? 'Masaustu: Gosteriliyor' : 'Masaustu: Gizli' }}
                                                        </label>
                                                    </div>
                                                    <button type="button" class="btn btn-sm btn-outline-danger delete-popup-btn" data-device="desktop" {{ $hasDesktop ? '' : 'disabled' }}>
                                                        <i class="bi bi-trash3 me-1"></i>Sil
                                                    </button>
                                                </div>
                                            </div>

                                            <div class="mt-3">
                                                <input type="file" class="form-control desktop-input" name="desktop_image" accept=".jpg,.jpeg,.png,.webp">
                                                <small class="text-muted d-block mt-2">JPG, PNG, WEBP (max 4MB)</small>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="col-xl-6">
                                        <div class="device-card" data-device="mobile" data-has-image="{{ $hasMobile ? '1' : '0' }}">
                                            <div class="device-card-head">
                                                <div>
                                                    <h6 class="mb-1"><i class="bi bi-phone me-2"></i>Mobil Popup</h6>
                                                    <small class="text-muted">Önerilen boyut: {{ $mobileRecommended }}</small>
                                                </div>
                                                <span class="status-pill {{ $mobileEnabled ? 'status-visible' : 'status-hidden' }}">
                                                    {{ $mobileEnabled ? 'Yayinda' : 'Gizli' }}
                                                </span>
                                            </div>

                                            <div class="preview-stage mobile-stage mb-3">
                                                <img
                                                    src="{{ $mobileUrl ?: 'data:image/svg+xml;utf8,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%22360%22 height=%22640%22><rect width=%22100%25%22 height=%22100%25%22 fill=%22%23111827%22/><text x=%2250%25%22 y=%2250%25%22 dominant-baseline=%22middle%22 text-anchor=%22middle%22 fill=%22%239ca3af%22 font-size=%2222%22 font-family=%22Arial%22>Mobile image yok</text></svg>' }}"
                                                    class="device-preview mobile-preview"
                                                    alt="Mobile popup"
                                                >
                                            </div>

                                            <div class="device-actions">
                                                <div class="device-actions-row">
                                                    <div class="form-check form-switch visibility-switch-wrap">
                                                        <input
                                                            class="form-check-input visibility-switch"
                                                            type="checkbox"
                                                            id="mobileVisibility{{ $site->id }}"
                                                            data-target="mobile_enabled"
                                                            {{ $mobileEnabled ? 'checked' : '' }}
                                                            {{ $hasMobile ? '' : 'disabled' }}
                                                        >
                                                        <label class="form-check-label visibility-switch-label" for="mobileVisibility{{ $site->id }}">
                                                            {{ $mobileEnabled ? 'Mobil: Gosteriliyor' : 'Mobil: Gizli' }}
                                                        </label>
                                                    </div>
                                                    <button type="button" class="btn btn-sm btn-outline-danger delete-popup-btn" data-device="mobile" {{ $hasMobile ? '' : 'disabled' }}>
                                                        <i class="bi bi-trash3 me-1"></i>Sil
                                                    </button>
                                                </div>
                                            </div>

                                            <div class="mt-3">
                                                <input type="file" class="form-control mobile-input" name="mobile_image" accept=".jpg,.jpeg,.png,.webp">
                                                <small class="text-muted d-block mt-2">JPG, PNG, WEBP (max 4MB)</small>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="popup-link-panel mt-4">
                                    <div class="row g-3">
                                        <div class="col-12">
                                            <h6 class="mb-1"><i class="bi bi-box-arrow-up-right me-2"></i>Popup Link Ayarlari</h6>
                                            <p class="mb-0 text-muted">Gorsel tiklaninca yeni sekmede acilacak URL ve gorsel altinda gosterilecek merkez link alani.</p>
                                        </div>
                                        <div class="col-12">
                                            <label class="form-label fw-semibold">Gorsel Tiklama URL</label>
                                            <input
                                                type="url"
                                                class="form-control"
                                                name="popup_click_url"
                                                value="{{ $popupClickUrl }}"
                                                placeholder="https://example.com/kampanya"
                                            >
                                            <small class="text-muted d-block mt-2">Bos birakilirsa popup gorseli tiklanabilir olmaz.</small>
                                        </div>
                                        <div class="col-md-5">
                                            <label class="form-label fw-semibold">Alt Link Metni</label>
                                            <input
                                                type="text"
                                                class="form-control"
                                                name="popup_footer_text"
                                                value="{{ $popupFooterText }}"
                                                maxlength="255"
                                                placeholder="Kampanyayi incele"
                                            >
                                        </div>
                                        <div class="col-md-7">
                                            <label class="form-label fw-semibold">Alt Link URL</label>
                                            <input
                                                type="url"
                                                class="form-control"
                                                name="popup_footer_url"
                                                value="{{ $popupFooterUrl }}"
                                                placeholder="https://example.com/kampanya-detay"
                                            >
                                        </div>
                                    </div>
                                </div>

                                <div class="save-bar mt-4">
                                    <button type="submit" class="btn btn-primary btn-md save-btn">
                                        <i class="bi bi-save me-2"></i>Kaydet
                                    </button>
                                </div>
                            </form>
                        </div>
                    @endforeach
                </div>
            </div>
        </div>
    @endif
</div>
@endsection

@push('styles')
<style>
    .payment-popups-page {
        --ink: #0f172a;
        --muted: #64748b;
        --ring: rgba(56, 189, 248, 0.18);
    }

    .hero-block {
        background: radial-gradient(1200px 300px at 15% -50%, rgba(59,130,246,.35), transparent 60%),
                    radial-gradient(900px 250px at 85% -30%, rgba(16,185,129,.25), transparent 65%),
                    linear-gradient(135deg, #0f172a 0%, #111827 60%, #0b1220 100%);
        color: #e2e8f0;
        border-radius: 16px;
        padding: 22px 24px;
        display: flex;
        justify-content: space-between;
        gap: 14px;
        align-items: center;
        box-shadow: 0 14px 28px rgba(2, 6, 23, 0.25);
    }

    .hero-block p {
        color: #a7b4c8;
    }

    .hero-dimensions {
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
        justify-content: flex-end;
    }

    .dim-chip {
        display: inline-flex;
        align-items: center;
        border: 1px solid rgba(148,163,184,.35);
        border-radius: 999px;
        padding: 6px 10px;
        font-size: 12px;
        font-weight: 600;
        color: #e2e8f0;
        background: rgba(15, 23, 42, .28);
    }

    .site-tabs-wrap {
        border-bottom: 1px solid #e2e8f0;
        padding: 14px 14px 0;
        background: linear-gradient(180deg, #f8fafc 0%, #ffffff 100%);
    }

    .popup-site-tabs {
        display: flex;
        gap: 10px;
        overflow-x: auto;
        flex-wrap: nowrap;
        padding-bottom: 12px;
    }

    .popup-site-tabs .nav-link {
        background: #eef2ff;
        color: #334155;
        border-radius: 12px;
        border: 1px solid transparent;
        font-weight: 700;
        white-space: nowrap;
        padding: 9px 14px;
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        min-width: 150px;
    }

    .popup-site-tabs .nav-link.active {
        background: #0f172a;
        color: #fff;
        border-color: #0f172a;
        box-shadow: 0 10px 20px rgba(15, 23, 42, 0.2);
    }



    .site-head {
        border-left: 4px solid #3b82f6;
        padding-left: 12px;
    }

    .device-card {
        border: 1px solid #dbe4ee;
        border-radius: 16px;
        background: linear-gradient(180deg, #ffffff 0%, #f8fafc 100%);
        padding: 16px;
        height: 100%;
        box-shadow: 0 8px 22px rgba(15, 23, 42, 0.06);
    }

    .device-card-head {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        gap: 10px;
        margin-bottom: 12px;
    }

    .status-pill {
        border-radius: 999px;
        padding: 4px 10px;
        font-size: 11px;
        font-weight: 700;
        letter-spacing: .02em;
        border: 1px solid transparent;
    }

    .status-visible {
        background: rgba(16, 185, 129, .14);
        border-color: rgba(5, 150, 105, .3);
        color: #047857;
    }

    .status-hidden {
        background: rgba(239, 68, 68, .12);
        border-color: rgba(220, 38, 38, .28);
        color: #b91c1c;
    }

    .preview-stage {
        border: 1px dashed #cbd5e1;
        border-radius: 12px;
        padding: 10px;
        min-height: 240px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #0b1220;
        box-shadow: inset 0 0 0 1px var(--ring);
    }

    .mobile-stage {
        min-height: 360px;
    }

    .device-preview {
        max-width: 100%;
        max-height: 310px;
        border-radius: 10px;
        object-fit: contain;
        background: #fff;
    }

    .mobile-stage .device-preview {
        max-height: 350px;
    }

    .device-actions {
        display: flex;
        justify-content: flex-end;
        align-items: center;
    }

    .device-actions-row {
        display: flex;
        align-items: center;
        gap: 8px;
        flex-wrap: wrap;
        justify-content: flex-end;
    }

    .visibility-switch-wrap {
        background: #eef2ff;
        border: 1px solid #c7d2fe;
        border-radius: 999px;
        padding: 8px 12px;
        margin: 0;
        display: inline-flex;
        align-items: center;
        gap: 10px;
    }

    .visibility-switch-wrap .form-check-input {
        margin: 0;
        width: 2.2rem;
        height: 1.2rem;
        cursor: pointer;
    }

    .visibility-switch-wrap .form-check-input:disabled {
        cursor: not-allowed;
    }

    .visibility-switch-label {
        margin: 0;
        font-weight: 700;
        color: #1e293b;
        font-size: 13px;
    }

    .delete-popup-btn {
        font-weight: 700;
        border-radius: 999px;
        padding: 7px 12px;
    }

    .save-bar {
        border-top: 1px solid #e2e8f0;
        padding-top: 16px;
        display: flex;
        justify-content: flex-end;
    }

    .popup-link-panel {
        border: 1px solid #dbe4ee;
        border-radius: 16px;
        background: linear-gradient(180deg, #ffffff 0%, #f8fafc 100%);
        padding: 18px;
        box-shadow: 0 8px 22px rgba(15, 23, 42, 0.04);
    }

    .save-btn {
        min-width: 180px;
        font-weight: 700;
    }

    @media (max-width: 992px) {
        .hero-block {
            flex-direction: column;
            align-items: flex-start;
        }

        .hero-dimensions {
            justify-content: flex-start;
        }
    }

    @media (max-width: 768px) {
        .tab-content.p-4 {
            padding: 1rem !important;
        }

        .save-btn {
            width: 100%;
        }

        .save-bar {
            justify-content: stretch;
        }
    }
</style>
@endpush

@push('scripts')
<script>
$(document).ready(function() {
    const desktopPlaceholder = 'data:image/svg+xml;utf8,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%22640%22 height=%22360%22><rect width=%22100%25%22 height=%22100%25%22 fill=%22%23111827%22/><text x=%2250%25%22 y=%2250%25%22 dominant-baseline=%22middle%22 text-anchor=%22middle%22 fill=%22%239ca3af%22 font-size=%2222%22 font-family=%22Arial%22>Desktop image yok</text></svg>';
    const mobilePlaceholder = 'data:image/svg+xml;utf8,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%22360%22 height=%22640%22><rect width=%22100%25%22 height=%22100%25%22 fill=%22%23111827%22/><text x=%2250%25%22 y=%2250%25%22 dominant-baseline=%22middle%22 text-anchor=%22middle%22 fill=%22%239ca3af%22 font-size=%2222%22 font-family=%22Arial%22>Mobile image yok</text></svg>';
    const maxUploadBytes = 4 * 1024 * 1024;
    const allowedExtensions = ['jpg', 'jpeg', 'png', 'webp'];

    function previewFile(inputEl, $targetImage) {
        const file = inputEl.files && inputEl.files[0] ? inputEl.files[0] : null;
        if (!file) {
            return;
        }

        const reader = new FileReader();
        reader.onload = function(e) {
            $targetImage.attr('src', e.target.result);
        };
        reader.readAsDataURL(file);
    }

    function validateSelectedFile(inputEl, deviceText) {
        const file = inputEl.files && inputEl.files[0] ? inputEl.files[0] : null;
        if (!file) {
            return false;
        }

        const extension = String(file.name || '').split('.').pop().toLowerCase();
        if (!allowedExtensions.includes(extension)) {
            Swal.fire('Gecersiz Dosya!', deviceText + ' icin sadece JPG, PNG veya WEBP yukleyebilirsiniz.', 'error');
            inputEl.value = '';
            return false;
        }

        if (Number(file.size || 0) > maxUploadBytes) {
            Swal.fire('Dosya Buyuk!', deviceText + ' dosyasi en fazla 4MB olabilir.', 'error');
            inputEl.value = '';
            return false;
        }

        return true;
    }

    function toBool(value) {
        return Number(value) === 1;
    }

    function updateVisibilityUI($form, targetName) {
        const isDesktop = targetName === 'desktop_enabled';
        const device = isDesktop ? 'desktop' : 'mobile';
        const $card = $form.find('.device-card[data-device="' + device + '"]');
        const $switch = $card.find('.visibility-switch');
        const $switchLabel = $card.find('.visibility-switch-label');
        const $statusPill = $card.find('.status-pill');
        const hasImage = Number($card.attr('data-has-image')) === 1;
        let enabled = toBool($form.find('input[name="' + targetName + '"]').val());

        if (!hasImage) {
            enabled = false;
            $form.find('input[name="' + targetName + '"]').val(0);
            $switch.prop('disabled', true).prop('checked', false);
        } else {
            $switch.prop('disabled', false).prop('checked', enabled);
        }

        if (enabled) {
            $statusPill.removeClass('status-hidden').addClass('status-visible').text('Yayinda');
            $switchLabel.text(isDesktop ? 'Masaustu: Gosteriliyor' : 'Mobil: Gosteriliyor');
            return;
        }

        $statusPill.removeClass('status-visible').addClass('status-hidden').text('Gizli');
        $switchLabel.text(isDesktop ? 'Masaustu: Gizli' : 'Mobil: Gizli');
    }

    function markHasImage($form, device, hasImage) {
        const targetName = device === 'desktop' ? 'desktop_enabled' : 'mobile_enabled';
        const $card = $form.find('.device-card[data-device="' + device + '"]');
        const $deleteBtn = $card.find('.delete-popup-btn');
        $card.attr('data-has-image', hasImage ? '1' : '0');

        if (!hasImage) {
            $form.find('input[name="' + targetName + '"]').val(0);
        }

        $deleteBtn.prop('disabled', !hasImage);

        updateVisibilityUI($form, targetName);
    }

    $(document).on('change', '.visibility-switch', function() {
        const $switch = $(this);
        const $form = $switch.closest('form');
        const targetName = String($switch.data('target') || '');
        if (!targetName) {
            return;
        }

        const $hidden = $form.find('input[name="' + targetName + '"]');
        $hidden.val($switch.is(':checked') ? 1 : 0);
        updateVisibilityUI($form, targetName);
    });

    $(document).on('change', '.desktop-input', function() {
        const $form = $(this).closest('form');
        if (!validateSelectedFile(this, 'Desktop image')) {
            return;
        }
        previewFile(this, $form.find('.desktop-preview'));
        markHasImage($form, 'desktop', true);
        $form.find('input[name="desktop_enabled"]').val(1);
        $form.find('input[name="desktop_delete"]').val(0);
        updateVisibilityUI($form, 'desktop_enabled');
    });

    $(document).on('change', '.mobile-input', function() {
        const $form = $(this).closest('form');
        if (!validateSelectedFile(this, 'Mobile image')) {
            return;
        }
        previewFile(this, $form.find('.mobile-preview'));
        markHasImage($form, 'mobile', true);
        $form.find('input[name="mobile_enabled"]').val(1);
        $form.find('input[name="mobile_delete"]').val(0);
        updateVisibilityUI($form, 'mobile_enabled');
    });

    $(document).on('click', '.delete-popup-btn', function() {
        const $btn = $(this);
        if ($btn.is(':disabled')) {
            return;
        }

        const device = String($btn.data('device') || '');
        if (device !== 'desktop' && device !== 'mobile') {
            return;
        }

        const $form = $btn.closest('form');
        const deviceText = device === 'desktop' ? 'masaustu' : 'mobil';

        Swal.fire({
            title: 'Emin misiniz?',
            text: 'Secili ' + deviceText + ' popup gorseli silinecek.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Evet, Sil',
            cancelButtonText: 'Vazgec'
        }).then(function(result) {
            if (!result.isConfirmed) {
                return;
            }

            const deleteName = device === 'desktop' ? 'desktop_delete' : 'mobile_delete';
            const enabledName = device === 'desktop' ? 'desktop_enabled' : 'mobile_enabled';
            const inputClass = device === 'desktop' ? '.desktop-input' : '.mobile-input';

            $form.find('input[name="' + deleteName + '"]').val(1);
            $form.find('input[name="' + enabledName + '"]').val(0);
            $form.find(inputClass).val('');
            $form.trigger('submit');
        });
    });

    $(document).on('submit', '.popup-form', function(e) {
        e.preventDefault();
        const $form = $(this);
        const siteId = Number($form.data('site-id'));
        if (!siteId) {
            return;
        }

        const formData = new FormData(this);
        const $saveBtn = $form.find('.save-btn');
        const originalButtonHtml = $saveBtn.html();
        $saveBtn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>Kaydediliyor...');

        $.ajax({
            url: '{{ route("backoffice.payment-popups.update", ":site") }}'.replace(':site', siteId),
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                Swal.fire('Basarili!', response.message, 'success');

                const desktopUrl = response.popup?.desktop_image_url || '';
                const mobileUrl = response.popup?.mobile_image_url || '';
                const desktopEnabled = response.popup?.desktop_enabled ? 1 : 0;
                const mobileEnabled = response.popup?.mobile_enabled ? 1 : 0;

                $form.find('.desktop-preview').attr('src', desktopUrl || desktopPlaceholder);
                $form.find('.mobile-preview').attr('src', mobileUrl || mobilePlaceholder);
                $form.find('input[name="desktop_enabled"]').val(desktopEnabled);
                $form.find('input[name="mobile_enabled"]').val(mobileEnabled);
                $form.find('input[name="popup_click_url"]').val(response.popup?.popup_click_url || '');
                $form.find('input[name="popup_footer_text"]').val(response.popup?.popup_footer_text || '');
                $form.find('input[name="popup_footer_url"]').val(response.popup?.popup_footer_url || '');

                markHasImage($form, 'desktop', !!desktopUrl);
                markHasImage($form, 'mobile', !!mobileUrl);

                updateVisibilityUI($form, 'desktop_enabled');
                updateVisibilityUI($form, 'mobile_enabled');

                $form.find('input[type="file"]').val('');
            },
            error: function(xhr) {
                if (xhr.status === 422 && xhr.responseJSON?.errors) {
                    let errorMsg = '<ul class="text-start">';
                    Object.keys(xhr.responseJSON.errors).forEach(function(key) {
                        errorMsg += '<li>' + xhr.responseJSON.errors[key][0] + '</li>';
                    });
                    errorMsg += '</ul>';
                    Swal.fire('Dogrulama Hatasi!', errorMsg, 'error');
                } else {
                    Swal.fire('Hata!', xhr.responseJSON?.message || 'Bir hata olustu', 'error');
                }
            },
            complete: function() {
                $form.find('input[name="desktop_delete"]').val(0);
                $form.find('input[name="mobile_delete"]').val(0);
                $saveBtn.prop('disabled', false).html(originalButtonHtml);
            }
        });
    });

    $('.popup-form').each(function() {
        const $form = $(this);
        updateVisibilityUI($form, 'desktop_enabled');
        updateVisibilityUI($form, 'mobile_enabled');
    });
});
</script>
@endpush
