@extends('backoffice.layouts.app')

@section('title', 'Kripto Hesablari')

@section('content')
<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h2 class="mb-1"><i class="bi bi-currency-bitcoin me-2"></i>Kripto Hesablari</h2>
                    <p class="text-muted">Finans gruplarina ait coin adreslerini yonetin</p>
                </div>
                @if(can_access('crypto_accounts', 'create'))
                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createCryptoModal">
                    <i class="bi bi-plus-circle me-2"></i>Yeni Kripto Adresi Ekle
                </button>
                @endif
            </div>
        </div>
    </div>

    <div class="card border-0 shadow-sm mb-4">
        <div class="card-body">
            <form id="filterForm" class="row g-3">
                <div class="col-md-4">
                    <label class="form-label small">Finans Grubu</label>
                    <select name="finance_group_id" class="form-select form-select-sm">
                        <option value="">Tumu</option>
                        @foreach($financeGroups as $group)
                            <option value="{{ $group->id }}">{{ $group->name }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label small">Coin</label>
                    <select name="crypto_coin_id" id="filterCoinId" class="form-select form-select-sm">
                        <option value="">Tumu</option>
                        @foreach($coins as $coin)
                            <option value="{{ $coin->id }}" data-icon="{{ $coin->icon }}">{{ $coin->name }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label small">Durum</label>
                    <select name="is_active" class="form-select form-select-sm">
                        <option value="">Tumu</option>
                        <option value="1">Aktif</option>
                        <option value="0">Pasif</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label small">&nbsp;</label>
                    <button type="submit" class="btn btn-primary btn-sm w-100"><i class="bi bi-funnel"></i> Filtrele</button>
                </div>
            </form>
        </div>
    </div>

    <div class="card border-0 shadow-sm">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table id="cryptoAccountsTable" class="table table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>Coin</th>
                            <th>Adres</th>
                            <th>Finans Grubu</th>
                            <th>Durum</th>
                            <th>Olusturan</th>
                            <th>Tarih</th>
                            <th width="170" class="text-center">Islemler</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="createCryptoModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title"><i class="bi bi-plus-circle me-2"></i>Yeni Kripto Adresi</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form id="createCryptoForm">
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Finans Grubu <span class="text-danger">*</span></label>
                            <select name="finance_group_id" class="form-select" required>
                                <option value="">Seciniz</option>
                                @foreach($financeGroups as $group)
                                    <option value="{{ $group->id }}">{{ $group->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Coin Adi <span class="text-danger">*</span></label>
                            <select name="crypto_coin_id" id="createCoinId" class="form-select" required>
                                <option value="">Coin secin</option>
                                @foreach($coins as $coin)
                                    <option value="{{ $coin->id }}" data-icon="{{ $coin->icon }}">{{ $coin->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-8">
                            <label class="form-label">Address <span class="text-danger">*</span></label>
                            <input type="text" name="address" id="createAddress" class="form-control" required>
                            <small class="text-muted">Adres girildiginde QR kod otomatik olusturulur.</small>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label d-block">Durum</label>
                            <div class="form-check form-switch mt-2">
                                <input type="hidden" name="is_active" value="0">
                                <input class="form-check-input" type="checkbox" name="is_active" value="1" checked>
                                <label class="form-check-label">Aktif</label>
                            </div>
                        </div>
                        <div class="col-12">
                            <div class="qr-preview-wrap">
                                <div id="createQrPlaceholder" class="qr-placeholder">
                                    Coin ve adres secildiginde QR kod burada gorunur.
                                </div>
                                <canvas id="createQrCanvas" class="qr-canvas"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Iptal</button>
                    <button type="submit" class="btn btn-primary"><i class="bi bi-check-circle me-2"></i>Ekle</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="editCryptoModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-info text-white">
                <h5 class="modal-title"><i class="bi bi-pencil me-2"></i>Kripto Adresini Duzenle</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form id="editCryptoForm">
                <input type="hidden" id="editCryptoId">
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Finans Grubu <span class="text-danger">*</span></label>
                            <select name="finance_group_id" id="editFinanceGroupId" class="form-select" required>
                                @foreach($financeGroups as $group)
                                    <option value="{{ $group->id }}">{{ $group->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Coin Adi <span class="text-danger">*</span></label>
                            <select name="crypto_coin_id" id="editCoinId" class="form-select" required>
                                @foreach($coins as $coin)
                                    <option value="{{ $coin->id }}" data-icon="{{ $coin->icon }}">{{ $coin->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-8">
                            <label class="form-label">Address <span class="text-danger">*</span></label>
                            <input type="text" name="address" id="editAddress" class="form-control" required>
                            <small class="text-muted">Adres degistiginde QR kod otomatik guncellenir.</small>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label d-block">Durum</label>
                            <div class="form-check form-switch mt-2">
                                <input type="hidden" name="is_active" value="0">
                                <input class="form-check-input" type="checkbox" name="is_active" id="editIsActive" value="1">
                                <label class="form-check-label">Aktif</label>
                            </div>
                        </div>
                        <div class="col-12">
                            <div class="qr-preview-wrap">
                                <div id="editQrPlaceholder" class="qr-placeholder">
                                    Coin ve adres secildiginde QR kod burada gorunur.
                                </div>
                                <canvas id="editQrCanvas" class="qr-canvas"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Iptal</button>
                    <button type="submit" class="btn btn-info text-white"><i class="bi bi-check-circle me-2"></i>Guncelle</button>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection

@push('styles')
<style>
    .coin-cell {
        display: flex;
        align-items: center;
        gap: 8px;
    }
    .coin-icon {
        width: 28px;
        height: 28px;
        border-radius: 999px;
        object-fit: cover;
        border: 1px solid #e2e8f0;
        background: #fff;
    }
    .finance-group-badge {
        display: inline-block;
        min-width: 120px;
        text-align: center;
        font-size: 0.9rem;
        font-weight: 600;
        padding: 6px 10px;
        border-radius: 8px;
        color: #0f172a;
        background: #e2e8f0;
        border: 1px solid rgba(15, 23, 42, 0.08);
    }
    .status-pill {
        display: inline-block;
        min-width: 90px;
        text-align: center;
        font-size: 0.84rem;
        font-weight: 600;
        padding: 6px 10px;
        border-radius: 8px;
        color: #fff;
    }
    .qr-preview-wrap {
        border: 1px dashed #cbd5e1;
        border-radius: 12px;
        background: #f8fafc;
        padding: 12px;
        min-height: 420px;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
    }
    .qr-canvas {
        display: none;
        max-width: 100%;
        border-radius: 8px;
        box-shadow: 0 10px 28px rgba(15, 23, 42, 0.12);
    }
    .qr-placeholder {
        color: #64748b;
        text-align: center;
        font-size: 0.95rem;
        padding: 20px;
    }
    .address-cell {
        max-width: 360px;
        word-break: break-all;
        font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
        font-size: 0.86rem;
    }
    .select2-container .select2-selection--single {
        height: 38px;
        border: 1px solid #ced4da;
        border-radius: 0.375rem;
        padding-top: 4px;
    }
    .select2-container--default .select2-selection--single .select2-selection__arrow {
        height: 36px;
    }
    .coin-option {
        display: flex;
        align-items: center;
        gap: 8px;
    }
    .coin-option-icon {
        width: 20px;
        height: 20px;
        border-radius: 999px;
        object-fit: cover;
        border: 1px solid #e2e8f0;
        background: #fff;
        flex: 0 0 20px;
    }
</style>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css">
@endpush

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(document).ready(function() {
    const canUpdateCryptoAccounts = {!! can_access('crypto_accounts', 'update') ? 'true' : 'false' !!};
    const canDeleteCryptoAccounts = {!! can_access('crypto_accounts', 'delete') ? 'true' : 'false' !!};
    let table = null;

    function formatCoinOption(state) {
        if (!state.id) {
            return state.text;
        }
        const icon = $(state.element).data('icon') || '';
        const label = state.text || '';
        const iconUrl = resolveIconUrl(icon);
        if (!iconUrl) {
            return $('<span class="coin-option"><i class="bi bi-currency-bitcoin"></i><span>' + label + '</span></span>');
        }
        return $('<span class="coin-option"><img src="' + iconUrl + '" class="coin-option-icon" alt="' + label + '"><span>' + label + '</span></span>');
    }

    function initCoinSelect($select, dropdownParentSelector, placeholderText) {
        const options = {
            width: '100%',
            placeholder: placeholderText || 'Coin secin',
            allowClear: true,
            templateResult: formatCoinOption,
            templateSelection: formatCoinOption,
            escapeMarkup: function(markup) { return markup; }
        };

        if (dropdownParentSelector) {
            options.dropdownParent = $(dropdownParentSelector);
        }

        $select.select2(options);
    }

    function getFilters() {
        const filters = {};
        const financeGroupId = $('select[name="finance_group_id"]').val();
        const cryptoCoinId = $('select[name="crypto_coin_id"]').val();
        const isActive = $('select[name="is_active"]').val();

        if (financeGroupId) {
            filters.finance_group_id = financeGroupId;
        }
        if (cryptoCoinId) {
            filters.crypto_coin_id = cryptoCoinId;
        }
        if (isActive !== '') {
            filters.is_active = isActive;
        }

        return filters;
    }

    function renderCoinCell(row) {
        if (row.coin_icon) {
            return '<div class="coin-cell"><img class="coin-icon" src="' + row.coin_icon + '" alt="' + row.coin_name + '"><span>' + row.coin_name + '</span></div>';
        }
        return '<div class="coin-cell"><i class="bi bi-currency-bitcoin"></i><span>' + row.coin_name + '</span></div>';
    }

    function initTable() {
        if (table) {
            table.destroy();
        }

        table = $('#cryptoAccountsTable').DataTable({
            processing: true,
            serverSide: false,
            ajax: {
                url: '{{ route("backoffice.crypto-accounts.index") }}',
                data: function(d) {
                    return Object.assign(d, getFilters());
                }
            },
            columns: [
                {
                    data: null,
                    render: function(data) {
                        return renderCoinCell(data);
                    }
                },
                {
                    data: 'address',
                    render: function(data) {
                        return '<div class="address-cell">' + data + '</div>';
                    }
                },
                {
                    data: null,
                    render: function(data) {
                        const bg = data.finance_group_color || '#e2e8f0';
                        return '<span class="finance-group-badge" style="background:' + bg + ';">' + data.finance_group_name + '</span>';
                    }
                },
                {
                    data: 'is_active',
                    render: function(data) {
                        return data
                            ? '<span class="status-pill bg-success">Aktif</span>'
                            : '<span class="status-pill bg-danger">Pasif</span>';
                    }
                },
                { data: 'created_by_name' },
                { data: 'created_at' },
                {
                    data: null,
                    orderable: false,
                    render: function(data) {
                        let btns = '<div class="btn-group btn-group-sm">';
                        if (canUpdateCryptoAccounts) {
                            btns += '<button class="btn btn-outline-primary btn-edit" data-id="' + data.id + '" title="Duzenle"><i class="bi bi-pencil"></i></button>';
                            btns += '<button class="btn btn-outline-' + (data.is_active ? 'warning' : 'success') + ' btn-toggle" data-id="' + data.id + '" title="' + (data.is_active ? 'Pasif yap' : 'Aktif yap') + '"><i class="bi bi-' + (data.is_active ? 'pause' : 'play') + '-circle"></i></button>';
                        }
                        if (canDeleteCryptoAccounts) {
                            btns += '<button class="btn btn-outline-danger btn-delete" data-id="' + data.id + '" title="Sil"><i class="bi bi-trash"></i></button>';
                        }
                        return btns + '</div>';
                    }
                }
            ],
            order: [[5, 'desc']],
            pageLength: 25,
            language: {
                url: '//cdn.datatables.net/plug-ins/1.13.6/i18n/tr.json'
            }
        });
    }

    function resolveIconUrl(iconPath) {
        const value = String(iconPath || '').trim();
        if (!value) {
            return '';
        }

        if (value.startsWith('http://') || value.startsWith('https://') || value.startsWith('data:')) {
            return value;
        }

        if (value.startsWith('/')) {
            return window.location.origin + value;
        }

        if (!value.includes('/')) {
            return window.location.origin + '/coins/' + value.replace(/^\/+/, '');
        }

        return window.location.origin + '/' + value.replace(/^\/+/, '');
    }

    function drawRoundedRect(ctx, x, y, width, height, radius) {
        const r = Math.min(radius, width / 2, height / 2);
        ctx.beginPath();
        ctx.moveTo(x + r, y);
        ctx.arcTo(x + width, y, x + width, y + height, r);
        ctx.arcTo(x + width, y + height, x, y + height, r);
        ctx.arcTo(x, y + height, x, y, r);
        ctx.arcTo(x, y, x + width, y, r);
        ctx.closePath();
    }

    function renderQr(canvasId, placeholderId, address, coinName, coinIcon) {
        const canvas = document.getElementById(canvasId);
        const placeholder = document.getElementById(placeholderId);
        if (!canvas || !placeholder) {
            return;
        }

        const safeAddress = String(address || '').trim();
        const safeCoinName = String(coinName || '').trim();
        const iconUrl = resolveIconUrl(coinIcon);
        const ctx = canvas.getContext('2d');

        if (!safeAddress || !safeCoinName) {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            canvas.style.display = 'none';
            placeholder.style.display = 'block';
            return;
        }

        const width = 340;
        const height = 410;
        const qrSize = 290;
        const qrX = Math.round((width - qrSize) / 2);
        const qrY = 16;
        const captionY = 365;

        canvas.width = width;
        canvas.height = height;

        const qrImage = new Image();
        qrImage.crossOrigin = 'anonymous';
        qrImage.onload = function() {
            ctx.clearRect(0, 0, width, height);
            ctx.fillStyle = '#ffffff';
            ctx.fillRect(0, 0, width, height);
            ctx.strokeStyle = '#e2e8f0';
            ctx.lineWidth = 1;
            ctx.strokeRect(0.5, 0.5, width - 1, height - 1);
            ctx.drawImage(qrImage, qrX, qrY, qrSize, qrSize);

            const drawCaption = function() {
                ctx.fillStyle = '#111827';
                ctx.textAlign = 'center';
                ctx.font = '700 24px Segoe UI';
                ctx.fillText(safeCoinName, width / 2, captionY);
            };

            const finish = function() {
                drawCaption();
                placeholder.style.display = 'none';
                canvas.style.display = 'block';
            };

            if (!iconUrl) {
                finish();
                return;
            }

            const icon = new Image();
            icon.crossOrigin = 'anonymous';
            icon.onload = function() {
                const iconSize = 64;
                const iconX = Math.round(width / 2 - iconSize / 2);
                const iconY = Math.round(qrY + qrSize / 2 - iconSize / 2);
                const pad = 8;

                ctx.save();
                ctx.fillStyle = '#ffffff';
                drawRoundedRect(ctx, iconX - pad, iconY - pad, iconSize + (pad * 2), iconSize + (pad * 2), 14);
                ctx.fill();
                ctx.restore();

                ctx.save();
                drawRoundedRect(ctx, iconX, iconY, iconSize, iconSize, 10);
                ctx.clip();
                ctx.drawImage(icon, iconX, iconY, iconSize, iconSize);
                ctx.restore();

                finish();
            };
            icon.onerror = function() {
                finish();
            };
            icon.src = iconUrl;
        };
        let qrTry = 0;
        const qrUrls = [
            'https://api.qrserver.com/v1/create-qr-code/?size=' + qrSize + 'x' + qrSize + '&margin=1&format=png&data=' + encodeURIComponent(safeAddress),
            'https://chart.googleapis.com/chart?cht=qr&chs=' + qrSize + 'x' + qrSize + '&chl=' + encodeURIComponent(safeAddress) + '&chld=M|1'
        ];

        qrImage.onerror = function() {
            qrTry += 1;
            if (qrTry < qrUrls.length) {
                qrImage.src = qrUrls[qrTry];
                return;
            }
            console.error('QR image render error');
            canvas.style.display = 'none';
            placeholder.textContent = 'QR kod olusturulamadi. Adresi kontrol edin.';
            placeholder.style.display = 'block';
        };

        qrImage.src = qrUrls[qrTry];
    }

    function getSelectedCoinMeta($select) {
        const selected = $select.find('option:selected');
        return {
            name: selected.text().trim(),
            icon: selected.data('icon') || ''
        };
    }

    function refreshCreateQr() {
        const meta = getSelectedCoinMeta($('#createCoinId'));
        renderQr('createQrCanvas', 'createQrPlaceholder', $('#createAddress').val(), meta.name, meta.icon);
    }

    function refreshEditQr() {
        const meta = getSelectedCoinMeta($('#editCoinId'));
        renderQr('editQrCanvas', 'editQrPlaceholder', $('#editAddress').val(), meta.name, meta.icon);
    }

    initTable();
    initCoinSelect($('#filterCoinId'), null, 'Coin secin');
    initCoinSelect($('#createCoinId'), '#createCryptoModal', 'Coin secin');
    initCoinSelect($('#editCoinId'), '#editCryptoModal', 'Coin secin');

    $('#filterForm').on('submit', function(e) {
        e.preventDefault();
        table.ajax.reload();
    });

    $('#createCoinId, #createAddress').on('change input', function() {
        refreshCreateQr();
    });

    $('#editCoinId, #editAddress').on('change input', function() {
        refreshEditQr();
    });

    $('#createCryptoModal').on('shown.bs.modal', function() {
        refreshCreateQr();
    }).on('hidden.bs.modal', function() {
        $('#createCryptoForm')[0].reset();
        refreshCreateQr();
    });

    $('#editCryptoModal').on('hidden.bs.modal', function() {
        $('#editCryptoForm')[0].reset();
        $('#editCryptoId').val('');
        refreshEditQr();
    });

    $('#createCryptoForm').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            url: '{{ route("backoffice.crypto-accounts.store") }}',
            method: 'POST',
            data: $(this).serialize() + '&_token={{ csrf_token() }}',
            success: function(response) {
                $('#createCryptoModal').modal('hide');
                Swal.fire('Basarili!', response.message, 'success');
                table.ajax.reload();
            },
            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');
                    return;
                }
                Swal.fire('Hata!', xhr.responseJSON?.message || 'Bir hata olustu', 'error');
            }
        });
    });

    $(document).on('click', '.btn-edit', function() {
        const id = $(this).data('id');
        $.ajax({
            url: '{{ route("backoffice.crypto-accounts.show", ":id") }}'.replace(':id', id),
            success: function(response) {
                const account = response.account;
                $('#editCryptoId').val(account.id);
                $('#editFinanceGroupId').val(account.finance_group_id);
                $('#editCoinId').val(account.crypto_coin_id).trigger('change');
                $('#editAddress').val(account.address);
                $('#editIsActive').prop('checked', !!account.is_active);
                $('#editCryptoModal').modal('show');
                setTimeout(refreshEditQr, 50);
            }
        });
    });

    $('#editCryptoForm').on('submit', function(e) {
        e.preventDefault();
        const id = $('#editCryptoId').val();
        $.ajax({
            url: '{{ route("backoffice.crypto-accounts.update", ":id") }}'.replace(':id', id),
            method: 'POST',
            data: $(this).serialize() + '&_token={{ csrf_token() }}&_method=PUT',
            success: function(response) {
                $('#editCryptoModal').modal('hide');
                Swal.fire('Basarili!', response.message, 'success');
                table.ajax.reload();
            },
            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');
                    return;
                }
                Swal.fire('Hata!', xhr.responseJSON?.message || 'Bir hata olustu', 'error');
            }
        });
    });

    $(document).on('click', '.btn-toggle', function() {
        const id = $(this).data('id');
        $.ajax({
            url: '{{ route("backoffice.crypto-accounts.toggle-status", ":id") }}'.replace(':id', id),
            method: 'POST',
            data: { _token: '{{ csrf_token() }}' },
            success: function(response) {
                Swal.fire('Basarili!', response.message, 'success');
                table.ajax.reload();
            },
            error: function(xhr) {
                Swal.fire('Hata!', xhr.responseJSON?.message || 'Bir hata olustu', 'error');
            }
        });
    });

    $(document).on('click', '.btn-delete', function() {
        const id = $(this).data('id');
        Swal.fire({
            title: 'Emin misiniz?',
            text: 'Bu kripto hesabini silmek istediginizden emin misiniz?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Evet, Sil',
            cancelButtonText: 'Iptal',
            confirmButtonColor: '#dc3545'
        }).then((result) => {
            if (!result.isConfirmed) {
                return;
            }
            $.ajax({
                url: '{{ route("backoffice.crypto-accounts.destroy", ":id") }}'.replace(':id', id),
                method: 'POST',
                data: { _token: '{{ csrf_token() }}', _method: 'DELETE' },
                success: function(response) {
                    Swal.fire('Basarili!', response.message, 'success');
                    table.ajax.reload();
                },
                error: function(xhr) {
                    Swal.fire('Hata!', xhr.responseJSON?.message || 'Bir hata olustu', 'error');
                }
            });
        });
    });
});
</script>
@endpush
