@extends('backoffice.layouts.app')

@section('title', 'Finans Grupları')

@section('content')
<div class="container-fluid">
    <!-- Page Header -->
    <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-diagram-3 me-2"></i>
                        Finans Grupları
                    </h2>
                    <p class="text-muted">Tutar bazlı yönlendirme gruplarını yönetin</p>
                </div>
                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createGroupModal">
                    <i class="bi bi-plus-circle me-2"></i>
                    Yeni Grup Oluştur
                </button>
            </div>
        </div>
    </div>

    <!-- Finance Groups Table -->
    <div class="card border-0 shadow-sm">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table id="financeGroupsTable" class="table table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>Grup Adı</th>
                            <th>Açıklama</th>
                            <th>Finans Kullanıcıları</th>
                            <th>Hesaplar</th>
                            <th>Durum</th>
                            <th>Oluşturan</th>
                            <th width="150" class="text-center">İşlemler</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Data will be loaded via AJAX -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Create Group Modal -->
<div class="modal fade" id="createGroupModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-plus-circle me-2"></i>
                    Yeni Finans Grubu
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="createGroupForm">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Grup Adı <span class="text-danger">*</span></label>
                        <input type="text" name="name" class="form-control" required placeholder="Örn: Küçük İşlemler">
                        <div class="invalid-feedback"></div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Açıklama</label>
                        <textarea name="description" class="form-control" rows="3" placeholder="Grup hakkında açıklama"></textarea>
                    </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="bi bi-check-circle me-2"></i>
                        Oluştur
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Group Modal -->
<div class="modal fade" id="editGroupModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-pencil me-2"></i>
                    Finans Grubunu Düzenle
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="editGroupForm">
                <input type="hidden" id="editGroupId">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Grup Adı <span class="text-danger">*</span></label>
                        <input type="text" name="name" id="editName" class="form-control" required>
                        <div class="invalid-feedback"></div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Açıklama</label>
                        <textarea name="description" id="editDescription" class="form-control" rows="3"></textarea>
                    </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="bi bi-check-circle me-2"></i>
                        Güncelle
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Site Statuses Modal -->
<div class="modal fade" id="siteStatusesModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-globe2 me-2"></i>
                    Site Bazli Durum
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="siteStatusesForm">
                <input type="hidden" id="siteStatusesGroupId">
                <div class="modal-body">
                    <div id="siteStatusesGroupLabel" class="fw-semibold text-center mb-2"></div>
                    <div class="table-responsive">
                        <table class="table table-sm table-bordered align-middle mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>Site</th>
                                    <th width="220">Durum</th>
                                    <th width="190">Site Min Tutar</th>
                                    <th width="190">Site Max Tutar</th>
                                </tr>
                            </thead>
                            <tbody id="siteStatusesRows">
                                <tr>
                                    <td colspan="4" class="text-center text-muted py-3">Yukleniyor...</td>
                                </tr>
                            </tbody>
                        </table>
                    </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>
                        Kaydet
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- View Group Details Modal -->
<div class="modal fade" id="viewGroupModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-info-circle me-2"></i>
                    Grup Detayları
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="groupDetailContent">
                <div class="text-center py-5">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Yükleniyor...</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@endsection

@push('styles')
<style>
    .finance-group-badge {
        display: block;
        width: 100%;
        text-align: center;
        font-size: 0.95rem;
        font-weight: 600;
        padding: 6px 8px;
        border-radius: 8px;
        color: #0f172a;
        background: #e2e8f0;
        border: 1px solid rgba(15, 23, 42, 0.08);
    }
    .status-pill {
        display: block;
        width: 100%;
        text-align: center;
        font-size: 0.9rem;
        font-weight: 600;
        padding: 6px 8px;
        border-radius: 8px;
        color: #fff;
    }
    .count-text {
        font-size: 0.95rem;
        font-weight: 600;
    }
    .site-status-list {
        display: flex;
        flex-direction: column;
        gap: 4px;
        min-width: 170px;
    }
    .site-status-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 8px;
        padding: 4px 8px;
        border: 1px solid #e2e8f0;
        border-radius: 8px;
        background: #f8fafc;
    }
    .site-status-name {
        font-size: 0.82rem;
        font-weight: 600;
        color: #334155;
        max-width: 120px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    .site-status-badge {
        font-size: 0.75rem;
        font-weight: 700;
        padding: 3px 8px;
        border-radius: 999px;
        color: #fff;
        white-space: nowrap;
    }
    .site-status-badge.active { background: #198754; }
    .site-status-badge.passive { background: #dc3545; }
    .site-toggle-wrap {
        display: inline-flex;
        align-items: center;
        gap: 10px;
    }
    .site-toggle-chip {
        min-width: 56px;
        text-align: center;
        font-size: 0.82rem;
        font-weight: 700;
        padding: 3px 10px;
        border-radius: 8px;
    }
    .site-toggle-chip.active {
        background: #c8e6d7;
        color: #0f5132;
    }
    .site-toggle-chip.passive {
        background: #e2e3e5;
        color: #495057;
    }
    .site-toggle-control {
        position: relative;
        display: inline-block;
        width: 54px;
        height: 30px;
        margin: 0;
    }
    .site-toggle-control input {
        opacity: 0;
        width: 0;
        height: 0;
    }
    .site-toggle-slider {
        position: absolute;
        cursor: pointer;
        inset: 0;
        background-color: #c0c4c9;
        transition: .2s;
        border-radius: 999px;
    }
    .site-toggle-slider:before {
        content: "";
        position: absolute;
        height: 22px;
        width: 22px;
        left: 4px;
        top: 4px;
        background-color: #fff;
        transition: .2s;
        border-radius: 50%;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
    }
    .site-toggle-control input:checked + .site-toggle-slider {
        background-color: #198754;
    }
    .site-toggle-control input:checked + .site-toggle-slider:before {
        transform: translateX(24px);
    }
</style>
@endpush

@push('scripts')
<script>
$(document).ready(function() {
    const canUpdateFinanceGroups = {!! can_access('finance_groups', 'update') ? 'true' : 'false' !!};
    const canDeleteFinanceGroups = {!! can_access('finance_groups', 'delete') ? 'true' : 'false' !!};
    let table;

    if (typeof parseFormattedNumber !== 'function') {
        window.parseFormattedNumber = function(formattedValue) {
            if (!formattedValue) return 0;
            return parseFloat(String(formattedValue).replace(/\./g, '').replace(',', '.')) || 0;
        };
    }

    function escapeHtml(value) {
        return String(value ?? '')
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;');
    }

    function formatLimitInputValue(value) {
        if (value === null || value === undefined || value === '') {
            return '';
        }
        const parsed = Number(value);
        if (!Number.isFinite(parsed)) {
            return '';
        }
        return parsed.toLocaleString('tr-TR', {
            minimumFractionDigits: 0,
            maximumFractionDigits: 0
        });
    }

    function normalizeSiteLimitPayload(payload) {
        return payload.map(function(item) {
            if (!/^limits\[\d+\]\[(min_amount|max_amount)\]$/.test(item.name)) {
                return item;
            }

            const rawValue = String(item.value ?? '').trim();
            if (rawValue === '') {
                return item;
            }

            const parsed = parseFormattedNumber(rawValue);
            if (!Number.isFinite(parsed)) {
                return { name: item.name, value: '' };
            }

            return { name: item.name, value: String(parsed) };
        });
    }

    // Initialize DataTable
    function initTable() {
        if (table) {
            table.destroy();
        }

        table = $('#financeGroupsTable').DataTable({
            processing: true,
            serverSide: false,
            ajax: {
                url: '{{ route("backoffice.finance-groups.index") }}',
            },
            columns: [
                {
                    data: 'name',
                    render: function(data, type, row) {
                        const bg = row.badge_color || '#e2e8f0';
                        return '<span class="finance-group-badge" style="background:' + bg + ';">' + data + '</span>';
                    }
                },
                {
                    data: 'description',
                    render: function(data) {
                        return data || '<span class="text-muted">-</span>';
                    }
                },
                {
                    data: 'finance_users_count',
                    render: function(data) {
                        return '<span class="count-text">' + data + ' kullanici</span>';
                    }
                },
                {
                    data: null,
                    render: function(data) {
                        const active = Number(data.active_bank_accounts_count || 0);
                        const total = Number(data.bank_accounts_count || 0);
                        return '<span class="count-text"><span class="text-success">' + active + '</span> / ' + total + '</span>';
                    }
                },
                {
                    data: 'site_statuses',
                    render: function(data, type) {
                        const statuses = Array.isArray(data) ? data : [];
                        if (type !== 'display') {
                            return statuses.map(function(item) {
                                return (item.site_name || '') + ' ' + (item.is_active ? 'aktif' : 'pasif');
                            }).join(' ');
                        }
                        if (!statuses.length) {
                            return '<span class="text-muted">-</span>';
                        }

                        const html = statuses.map(function(item) {
                            const name = String(item.site_name || '-')
                                .replace(/&/g, '&amp;')
                                .replace(/</g, '&lt;')
                                .replace(/>/g, '&gt;')
                                .replace(/"/g, '&quot;')
                                .replace(/'/g, '&#39;');
                            const stateClass = item.is_active ? 'active' : 'passive';
                            const stateLabel = item.is_active ? 'Aktif' : 'Pasif';
                            const sitePassive = item.site_is_active ? '' : ' <i class="bi bi-moon-stars-fill text-secondary" title="Pasif Site"></i>';
                            return '' +
                                '<div class="site-status-item">' +
                                    '<span class="site-status-name" title="' + name + '">' + name + sitePassive + '</span>' +
                                    '<span class="site-status-badge ' + stateClass + '">' + stateLabel + '</span>' +
                                '</div>';
                        }).join('');

                        return '<div class="site-status-list">' + html + '</div>';
                    }
                },
                { data: 'created_by_name' },
                {
                    data: null,
                    orderable: false,
                    render: function(data) {
                        let buttons = '<div class="btn-group btn-group-sm">';
                        buttons += '<button class="btn btn-outline-info btn-view" data-id="' + data.id + '" title="Detay"><i class="bi bi-eye"></i></button>';
                        if (canUpdateFinanceGroups) {
                            buttons += '<button class="btn btn-outline-primary btn-edit" data-id="' + data.id + '" title="Düzenle"><i class="bi bi-pencil"></i></button>';
                            buttons += '<button class="btn btn-outline-warning btn-site-statuses" data-id="' + data.id + '" title="Site Bazli Durum"><i class="bi bi-sliders2"></i></button>';
                            buttons += '<button class="btn btn-outline-' + (data.is_crypto_enabled ? 'success' : 'secondary') + ' btn-toggle-crypto" data-id="' + data.id + '" title="' + (data.is_crypto_enabled ? 'Kriptoyu Pasif Yap' : 'Kriptoyu Aktif Yap') + '"><i class="bi bi-currency-bitcoin"></i></button>';
                        }

                        if (canDeleteFinanceGroups) {
                            buttons += '<button class="btn btn-outline-danger btn-delete" data-id="' + data.id + '" title="Sil"><i class="bi bi-trash"></i></button>';
                        }
                        buttons += '</div>';
                        return buttons;
                    }
                }
            ],
            order: [[0, 'asc']],
            pageLength: 25,
            language: {
                url: '//cdn.datatables.net/plug-ins/1.13.6/i18n/tr.json'
            }
        });
    }

    initTable();

    // Create Group
    $('#createGroupForm').on('submit', function(e) {
        e.preventDefault();
        $(this).find('.is-invalid').removeClass('is-invalid');
        $(this).find('.invalid-feedback').text('');

        const formData = {
            name: $(this).find('[name="name"]').val(),
            description: $(this).find('[name="description"]').val(),
            _token: '{{ csrf_token() }}'
        };

        $.ajax({
            url: '{{ route("backoffice.finance-groups.store") }}',
            method: 'POST',
            data: formData,
            success: function(response) {
                $('#createGroupModal').modal('hide');
                $('#createGroupForm')[0].reset();
                Swal.fire('Başarılı!', response.message, 'success');
                table.ajax.reload();
            },
            error: function(xhr) {
                if (xhr.status === 422) {
                    const errors = xhr.responseJSON.errors;
                    Object.keys(errors).forEach(function(key) {
                        const input = $('[name="' + key + '"]');
                        input.addClass('is-invalid');
                        input.siblings('.invalid-feedback').text(errors[key][0]);
                    });
                } else {
                    Swal.fire('Hata!', xhr.responseJSON.message, 'error');
                }
            }
        });
    });

    // View Group Details
    $(document).on('click', '.btn-view', function() {
        const id = $(this).data('id');
        $('#viewGroupModal').modal('show');

        $.ajax({
            url: '{{ route("backoffice.finance-groups.show", ":id") }}'.replace(':id', id),
            success: function(response) {
                const g = response.group;
                let html = `
                    <div class="row g-3">
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">Grup Adı</p>
                            <p class="fw-semibold">${g.name}</p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">Durum</p>
                            <p class="fw-semibold">
                                ${g.is_active ? '<span class="badge bg-success">Aktif</span>' : '<span class="badge bg-danger">Pasif</span>'}
                            </p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">Kripto Ödeme</p>
                            <p class="fw-semibold">
                                ${(typeof g.is_crypto_enabled === 'undefined' || g.is_crypto_enabled)
                                    ? '<span class="badge bg-success">Aktif</span>'
                                    : '<span class="badge bg-secondary">Pasif</span>'}
                            </p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">Finans Kullanıcıları</p>
                            <p class="fw-semibold">${g.finance_users.length} kullanıcı</p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">Banka Hesapları</p>
                            <p class="fw-semibold">${g.bank_accounts.length} hesap</p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">Oluşturan</p>
                            <p class="fw-semibold">${g.creator ? g.creator.full_name : '-'}</p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">Oluşturulma Tarihi</p>
                            <p class="fw-semibold">${new Date(g.created_at).toLocaleString('tr-TR')}</p>
                        </div>
                        ${g.description ? `
                        <div class="col-12">
                            <p class="mb-1 small text-muted">Açıklama</p>
                            <div class="alert alert-info mb-0">${g.description}</div>
                        </div>
                        ` : ''}
                    </div>
                `;
                $('#groupDetailContent').html(html);
            }
        });
    });

    // Edit Group
    $(document).on('click', '.btn-edit', function() {
        const id = $(this).data('id');

        $.ajax({
            url: '{{ route("backoffice.finance-groups.show", ":id") }}'.replace(':id', id),
            success: function(response) {
                const g = response.group;
                $('#editGroupId').val(g.id);
                $('#editName').val(g.name);
                $('#editDescription').val(g.description);
                $('#editGroupModal').modal('show');
            }
        });
    });

    $('#editGroupForm').on('submit', function(e) {
        e.preventDefault();
        const id = $('#editGroupId').val();
        $(this).find('.is-invalid').removeClass('is-invalid');
        $(this).find('.invalid-feedback').text('');

        const formData = {
            name: $('#editName').val(),
            description: $('#editDescription').val(),
            _token: '{{ csrf_token() }}',
            _method: 'PUT'
        };

        $.ajax({
            url: '{{ route("backoffice.finance-groups.update", ":id") }}'.replace(':id', id),
            method: 'POST',
            data: formData,
            success: function(response) {
                $('#editGroupModal').modal('hide');
                Swal.fire('Başarılı!', response.message, 'success');
                table.ajax.reload();
            },
            error: function(xhr) {
                if (xhr.status === 422) {
                    const errors = xhr.responseJSON.errors;
                    Object.keys(errors).forEach(function(key) {
                        const input = $('#edit' + key.charAt(0).toUpperCase() + key.slice(1));
                        input.addClass('is-invalid');
                        input.siblings('.invalid-feedback').text(errors[key][0]);
                    });
                } else {
                    Swal.fire('Hata!', xhr.responseJSON.message, 'error');
                }
            }
        });
    });

    // Site-based statuses
    $(document).on('click', '.btn-site-statuses', function() {
        const id = $(this).data('id');
        $('#siteStatusesGroupId').val(id);
        $('#siteStatusesGroupLabel').text('');
        $('#siteStatusesRows').html('<tr><td colspan="4" class="text-center text-muted py-3">Yukleniyor...</td></tr>');
        $('#siteStatusesModal').modal('show');

        $.ajax({
            url: '{{ route("backoffice.finance-groups.site-statuses", ":id") }}'.replace(':id', id),
            method: 'GET',
            success: function(response) {
                const group = response.group || {};
                $('#siteStatusesGroupLabel').text((group.name || '-') + ' - Site Durumlari');

                const sites = response.sites || [];
                if (!sites.length) {
                    $('#siteStatusesRows').html('<tr><td colspan="4" class="text-center text-muted py-3">Site bulunmuyor.</td></tr>');
                    return;
                }

                const rows = sites.map(function(site) {
                    const selected = site.status_value === 'passive' ? 'passive' : 'active';
                    const sourceBadge = site.source === 'override'
                        ? ' <span class="badge bg-info">Ozel</span>'
                        : ' <span class="badge bg-secondary">Varsayilan</span>';
                    const sitePassiveBadge = site.is_active ? '' : ' <span class="badge bg-dark">Pasif Site</span>';
                    const siteName = escapeHtml(site.name || '-');
                    const minValue = formatLimitInputValue(site.override_min_amount);
                    const maxValue = formatLimitInputValue(site.override_max_amount);

                    return '' +
                        '<tr>' +
                            '<td>' + siteName + sourceBadge + sitePassiveBadge + '</td>' +
                            '<td>' +
                                '<div class="site-toggle-wrap">' +
                                    '<span class="site-toggle-chip ' + (selected === 'active' ? 'active' : 'passive') + '" data-status-chip>' + (selected === 'active' ? 'Aktif' : 'Pasif') + '</span>' +
                                    '<label class="site-toggle-control">' +
                                        '<input type="checkbox" class="site-status-toggle" data-site-id="' + site.id + '"' + (selected === 'active' ? ' checked' : '') + '>' +
                                        '<span class="site-toggle-slider"></span>' +
                                    '</label>' +
                                    '<input type="hidden" name="statuses[' + site.id + ']" value="' + selected + '" class="site-status-hidden">' +
                                '</div>' +
                            '</td>' +
                            '<td><input type="text" class="form-control form-control-sm number-input site-limit-input" inputmode="numeric" name="limits[' + site.id + '][min_amount]" value="' + escapeHtml(minValue) + '" placeholder="Orn: 10.000"></td>' +
                            '<td><input type="text" class="form-control form-control-sm number-input site-limit-input" inputmode="numeric" name="limits[' + site.id + '][max_amount]" value="' + escapeHtml(maxValue) + '" placeholder="Orn: 200.000"></td>' +
                        '</tr>';
                }).join('');

                $('#siteStatusesRows').html(rows);
                $('#siteStatusesRows .site-limit-input')
                    .off('input.siteLimitFormat')
                    .on('input.siteLimitFormat', function() {
                        if (typeof formatNumberInput === 'function') {
                            formatNumberInput(this, 0);
                            return;
                        }
                        let value = this.value.replace(/[^\d]/g, '');
                        this.value = value ? parseInt(value, 10).toLocaleString('tr-TR') : '';
                    });

                $('#siteStatusesRows .site-status-toggle')
                    .off('change.siteStatusToggle')
                    .on('change.siteStatusToggle', function() {
                        const $toggle = $(this);
                        const isActive = $toggle.is(':checked');
                        const statusValue = isActive ? 'active' : 'passive';
                        const $wrapper = $toggle.closest('.site-toggle-wrap');
                        $wrapper.find('.site-status-hidden').val(statusValue);
                        const $chip = $wrapper.find('[data-status-chip]');
                        $chip
                            .removeClass('active passive')
                            .addClass(isActive ? 'active' : 'passive')
                            .text(isActive ? 'Aktif' : 'Pasif');
                    });
            },
            error: function(xhr) {
                $('#siteStatusesRows').html('<tr><td colspan="4" class="text-center text-danger py-3">Yukleme hatasi.</td></tr>');
                Swal.fire('Hata!', xhr.responseJSON?.message || 'Bir hata olustu', 'error');
            }
        });
    });

    $('#siteStatusesForm').on('submit', function(e) {
        e.preventDefault();
        const id = $('#siteStatusesGroupId').val();
        const payload = normalizeSiteLimitPayload($(this).serializeArray());
        payload.push({ name: '_token', value: '{{ csrf_token() }}' });

        $.ajax({
            url: '{{ route("backoffice.finance-groups.site-statuses.update", ":id") }}'.replace(':id', id),
            method: 'POST',
            data: $.param(payload),
            success: function(response) {
                $('#siteStatusesModal').modal('hide');
                Swal.fire('Basarili!', response.message, 'success');
                table.ajax.reload(null, false);
            },
            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');
                }
            }
        });
    });

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

    // Delete Group
    $(document).on('click', '.btn-delete', function() {
        const id = $(this).data('id');

        Swal.fire({
            title: 'Emin misiniz?',
            text: 'Bu grubu silmek istediğinizden emin misiniz?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Evet, Sil',
            cancelButtonText: 'İptal',
            confirmButtonColor: '#dc3545'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '{{ route("backoffice.finance-groups.destroy", ":id") }}'.replace(':id', id),
                    method: 'POST',
                    data: {
                        _token: '{{ csrf_token() }}',
                        _method: 'DELETE'
                    },
                    success: function(response) {
                        Swal.fire('Başarılı!', response.message, 'success');
                        table.ajax.reload();
                    },
                    error: function(xhr) {
                        Swal.fire('Hata!', xhr.responseJSON.message, 'error');
                    }
                });
            }
        });
    });

    // Clear validation on modal close
    $('.modal').on('hidden.bs.modal', function() {
        $(this).find('.is-invalid').removeClass('is-invalid');
        $(this).find('.invalid-feedback').text('');
    });
});
</script>
@endpush


