
@extends('backoffice.layouts.app')

@section('title', 'Islem Loglari')

@section('content')
<div class="container-fluid transaction-logs-page">
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
                <div>
                    <h2 class="mb-1 d-flex align-items-center gap-2">
                        <i class="bi bi-table"></i>
                        <span>Islem Loglari</span>
                    </h2>
                    <p class="text-muted mb-0">Tarih ve durum bazli filtreleyin, kolonlari secin, tabloyu tam ekran kullanin.</p>
                </div>
            </div>
        </div>
    </div>

    <div class="card border-0 shadow-sm mb-4 filter-sheet-card">
        <div class="card-body">
            <form id="filterForm" autocomplete="off">
                <div class="row g-3 align-items-end">
                    <div class="col-xl-2 col-lg-3 col-md-4">
                        <label class="form-label small text-uppercase text-muted">Baslangic Tarihi</label>
                        <input type="text" name="date_from" class="form-control form-control-sm datetimepicker" placeholder="dd/mm/yyyy hh:mm" value="{{ request()->filled('date_from') ? $dateFromDisplay->format('d/m/Y H:i') : '' }}">
                    </div>
                    <div class="col-xl-2 col-lg-3 col-md-4">
                        <label class="form-label small text-uppercase text-muted">Bitis Tarihi</label>
                        <input type="text" name="date_to" class="form-control form-control-sm datetimepicker" placeholder="dd/mm/yyyy hh:mm" value="{{ request()->filled('date_to') ? $dateToDisplay->format('d/m/Y H:i') : '' }}">
                    </div>
                    <div class="col-xl-2 col-lg-2 col-md-4">
                        <label class="form-label small text-uppercase text-muted">Tip</label>
                        <select name="type" class="form-select form-select-sm">
                            <option value="">Tumu</option>
                            <option value="deposit" {{ request('type') === 'deposit' ? 'selected' : '' }}>Yatirim</option>
                            <option value="withdrawal" {{ request('type') === 'withdrawal' ? 'selected' : '' }}>Cekim</option>
                        </select>
                    </div>
                    <div class="col-xl-2 col-lg-2 col-md-4">
                        <label class="form-label small text-uppercase text-muted">Durum</label>
                        <select name="status" class="form-select form-select-sm">
                            <option value="">Tumu</option>
                            <option value="pending" {{ request('status') === 'pending' ? 'selected' : '' }}>Bekleyen</option>
                            <option value="approved" {{ request('status') === 'approved' ? 'selected' : '' }}>Onaylandi</option>
                            <option value="declined" {{ request('status') === 'declined' ? 'selected' : '' }}>Reddedildi</option>
                        </select>
                    </div>
                    <div class="col-xl-2 col-lg-2 col-md-4">
                        <label class="form-label small text-uppercase text-muted">Kaynak</label>
                        <select name="source" class="form-select form-select-sm">
                            <option value="">Tumu</option>
                            <option value="auto" {{ request('source') === 'auto' ? 'selected' : '' }}>Auto</option>
                            <option value="manual" {{ request('source') === 'manual' ? 'selected' : '' }}>Manuel</option>
                        </select>
                    </div>
                    <div class="col-xl-2 col-lg-3 col-md-4">
                        <label class="form-label small text-uppercase text-muted">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 }}" {{ (string) request('finance_group_id') === (string) $group->id ? 'selected' : '' }}>{{ $group->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-xl-2 col-lg-3 col-md-4">
                        <label class="form-label small text-uppercase text-muted">Site</label>
                        <select name="site_id" class="form-select form-select-sm">
                            <option value="">Tumu</option>
                            @foreach($sites as $site)
                                <option value="{{ $site->id }}" {{ (string) request('site_id') === (string) $site->id ? 'selected' : '' }}>{{ $site->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-xl-4 col-lg-6 col-md-8">
                        <label class="form-label small text-uppercase text-muted d-block">Metin Filtreleri</label>
                        <div class="filter-builder-actions d-flex flex-wrap gap-2">
                            <div class="dropdown" data-bs-auto-close="outside">
                                <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                                    <i class="bi bi-plus-square me-1"></i>Filtre Ekle
                                </button>
                                <div class="dropdown-menu dropdown-menu-start filter-menu" id="textFilterMenu"></div>
                            </div>
                            <button type="button" class="btn btn-sm btn-outline-secondary" id="clearTextFiltersBtn">
                                <i class="bi bi-x-circle me-1"></i>Metin Filtrelerini Temizle
                            </button>
                        </div>
                    </div>
                    <div class="col-xl-3 col-lg-6 col-md-4">
                        <label class="form-label small text-uppercase text-muted d-block">Islem</label>
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary btn-sm flex-fill">
                                <i class="bi bi-funnel me-1"></i>Uygula
                            </button>
                            <button type="button" class="btn btn-light btn-sm border flex-fill" id="resetFiltersBtn">
                                <i class="bi bi-arrow-counterclockwise me-1"></i>Sifirla
                            </button>
                        </div>
                    </div>
                </div>

                <div class="dynamic-filter-shell mt-4">
                    <div class="d-flex align-items-center justify-content-between flex-wrap gap-2 mb-3">
                        <div>
                            <div class="small text-uppercase text-muted mb-1">Aktif Metin Filtreleri</div>
                            <div class="small text-muted">Kolon secin, deger yazin, istemediginiz filtreyi kaldirin.</div>
                        </div>
                        <span class="badge text-bg-light border" id="activeFilterCount">0 filtre</span>
                    </div>
                    <div id="dynamicTextFilters" class="dynamic-filters-grid"></div>
                    <div id="emptyDynamicFilters" class="empty-filter-state">
                        <i class="bi bi-sliders2-vertical"></i>
                        <span>Metin filtresi eklenmedi.</span>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <div class="card border-0 shadow-sm excel-sheet-card" id="transactionLogsTableShell">
        <div class="card-header bg-white border-0 pb-0">
            <div class="table-toolbar d-flex justify-content-between align-items-center flex-wrap gap-3">
                <div>
                    <h5 class="mb-1">Islem Tablosu</h5>
                    <p class="text-muted mb-0 small">Excel benzeri gorunum, kolon secimi ve tam ekran destekli.</p>
                </div>
                <div class="d-flex align-items-center flex-wrap gap-2">
                    <div id="transactionLogsTableExportButtons"></div>
                    <div class="dropdown" data-bs-auto-close="outside">
                        <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="bi bi-layout-three-columns me-1"></i>Kolonlar
                        </button>
                        <div class="dropdown-menu dropdown-menu-end column-menu" id="columnSelectorMenu"></div>
                    </div>
                    <button type="button" class="btn btn-sm btn-outline-secondary" id="toggleFullscreenBtn">
                        <i class="bi bi-arrows-fullscreen me-1"></i>Tam Ekran
                    </button>
                </div>
            </div>
        </div>
        <div class="card-body pt-3">
            <div class="excel-table-wrap">
                <table id="transactionLogsTable" class="table excel-table align-middle mb-0 w-100">
                    <thead>
                        <tr>
                            <th>Islem ID</th>
                            <th>Tip</th>
                            <th>Durum</th>
                            <th>Kaynak</th>
                            <th>Site</th>
                            <th>Tutar</th>
                            <th>Musteri</th>
                            <th>Uye ID</th>
                            <th>IP Adresi</th>
                            <th>IBAN</th>
                            <th>Hesap Adi</th>
                            <th>Finans Grubu</th>
                            <th>Banka Hesabi</th>
                            <th>Olusturan</th>
                            <th>Onaylayan</th>
                            <th>Tarih</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                    <tfoot>
                        <tr>
                            <th colspan="5" class="text-end">Sayfa Toplami</th>
                            <th class="text-primary fw-bold">0,00 TRY</th>
                            <th colspan="10"></th>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>
</div>
@endsection

@push('styles')
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.bootstrap5.min.css">
<style>
    .filter-sheet-card,
    .excel-sheet-card {
        border-radius: 18px;
    }

    .filter-sheet-card .card-body,
    .excel-sheet-card .card-body {
        padding: 1.25rem;
    }

    .filter-menu,
    .column-menu {
        min-width: 260px;
        max-height: 320px;
        overflow: auto;
        padding: 0.5rem;
    }

    .filter-menu .dropdown-item,
    .column-menu .dropdown-item {
        border-radius: 10px;
        padding: 0.55rem 0.75rem;
        font-size: 0.92rem;
    }

    .filter-menu .dropdown-item.disabled {
        opacity: 0.45;
    }

    .dynamic-filter-shell {
        border-top: 1px solid #e9edf3;
        padding-top: 1rem;
    }
    .dynamic-filters-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
        gap: 12px;
    }

    .dynamic-filter-card {
        border: 1px solid #dbe3ef;
        background: #fbfcfe;
        border-radius: 14px;
        padding: 0.85rem;
        box-shadow: inset 0 1px 0 rgba(255,255,255,0.75);
    }

    .dynamic-filter-card .filter-meta {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 12px;
        margin-bottom: 0.55rem;
    }

    .dynamic-filter-card .filter-label {
        font-size: 0.78rem;
        font-weight: 700;
        letter-spacing: 0.04em;
        text-transform: uppercase;
        color: #64748b;
    }

    .dynamic-filter-card .filter-remove {
        border: 0;
        background: transparent;
        color: #94a3b8;
        padding: 0;
        line-height: 1;
    }

    .dynamic-filter-card .filter-remove:hover {
        color: #dc2626;
    }

    .empty-filter-state {
        min-height: 74px;
        border: 1px dashed #cbd5e1;
        border-radius: 14px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
        color: #94a3b8;
        background: #f8fafc;
    }

    .table-toolbar {
        padding: 0.25rem 0 0.5rem;
    }

    .excel-table-wrap {
        overflow: auto;
        border: 1px solid #d9e1ea;
        border-radius: 14px;
        background: #fff;
    }

    .excel-table {
        --bs-table-bg: #fff;
        --bs-table-striped-bg: #fff;
        --bs-table-hover-bg: #f7fbff;
        margin-bottom: 0;
        min-width: 1500px;
    }

    .excel-table thead th,
    .excel-table tfoot th {
        position: sticky;
        top: 0;
        z-index: 2;
        background: linear-gradient(180deg, #f8fafc 0%, #eef2f7 100%);
        color: #334155;
        font-size: 0.78rem;
        text-transform: uppercase;
        letter-spacing: 0.04em;
        border-bottom: 1px solid #cfd8e3;
    }

    .excel-table tfoot th {
        position: static;
        top: auto;
        background: #f8fafc;
    }

    .excel-table th,
    .excel-table td {
        white-space: nowrap;
        border-right: 1px solid #e5ebf3;
        border-bottom: 1px solid #e5ebf3;
        padding: 0.62rem 0.75rem;
        vertical-align: middle;
        font-size: 0.92rem;
    }

    .excel-table th:last-child,
    .excel-table td:last-child {
        border-right: 0;
    }

    .excel-table tbody tr:hover {
        background: #f7fbff;
    }

    .finance-group-badge {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        min-width: 96px;
        text-align: center;
        font-size: 0.82rem;
        font-weight: 600;
        padding: 0.38rem 0.55rem;
        border-radius: 999px;
        color: #0f172a;
        background: #e2e8f0;
        border: 1px solid rgba(15, 23, 42, 0.08);
    }

    .status-pill,
    .source-pill {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        min-width: 98px;
        text-align: center;
        font-size: 0.8rem;
        font-weight: 700;
        padding: 0.38rem 0.55rem;
        border-radius: 999px;
        color: #fff;
    }

    .table-shell-fullscreen {
        position: fixed;
        inset: 14px;
        z-index: 1080;
        margin: 0;
        display: flex;
        flex-direction: column;
        background: #ffffff;
        box-shadow: 0 24px 60px rgba(15, 23, 42, 0.28);
    }

    .table-shell-fullscreen .card-body {
        flex: 1 1 auto;
        min-height: 0;
    }

    .table-shell-fullscreen .excel-table-wrap {
        height: 100%;
    }

    body.table-fullscreen-open {
        overflow: hidden;
    }

    .dt-buttons .btn {
        border-radius: 10px;
    }

    .dataTables_wrapper .dataTables_length,
    .dataTables_wrapper .dataTables_info,
    .dataTables_wrapper .dataTables_paginate {
        padding-top: 0.85rem;
    }

    .dataTables_wrapper .dataTables_paginate .paginate_button {
        padding: 0 !important;
        border: 0 !important;
        background: transparent !important;
    }

    .dataTables_wrapper .dataTables_paginate .page-link {
        border-radius: 10px !important;
    }

    @media (max-width: 991.98px) {
        .dynamic-filters-grid {
            grid-template-columns: 1fr;
        }

        .table-shell-fullscreen {
            inset: 6px;
        }
    }
</style>
@endpush

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
<script>
$(document).ready(function() {
    const canExportExcel = {!! can_access('export_excel', 'read') ? 'true' : 'false' !!};
    const $tableShell = $('#transactionLogsTableShell');
    const $columnSelectorMenu = $('#columnSelectorMenu');
    const $textFilterMenu = $('#textFilterMenu');
    const $dynamicTextFilters = $('#dynamicTextFilters');
    const $emptyDynamicFilters = $('#emptyDynamicFilters');
    const $activeFilterCount = $('#activeFilterCount');
    const $toggleFullscreenBtn = $('#toggleFullscreenBtn');

    const textFilterDefinitions = [
        { key: 'transaction_id', label: 'Islem ID', placeholder: 'TXN...' },
        { key: 'external_transaction_id', label: 'Dis Islem ID', placeholder: 'EXT...' },
        { key: 'merchant_trx_id', label: 'Merchant TRX ID', placeholder: 'TRX...' },
        { key: 'customer_name', label: 'Musteri', placeholder: 'Ad Soyad' },
        { key: 'customer_player_id', label: 'Uye ID', placeholder: 'Player ID' },
        { key: 'customer_iban', label: 'IBAN', placeholder: 'TR...' },
        { key: 'customer_account_holder', label: 'Hesap Adi', placeholder: 'Hesap sahibi' },
        { key: 'currency', label: 'Para Birimi', placeholder: 'TRY' },
        { key: 'bank_account', label: 'Banka Hesabi', placeholder: 'Hesap / IBAN' },
        { key: 'created_by_name', label: 'Olusturan', placeholder: 'Kullanici adi' },
        { key: 'approved_by_name', label: 'Onaylayan', placeholder: 'Kullanici adi' },
        { key: 'ip_address', label: 'IP Adresi', placeholder: '127.0.0.1' },
        { key: 'min_amount', label: 'Min Tutar', placeholder: '0.00', inputType: 'number' },
        { key: 'max_amount', label: 'Max Tutar', placeholder: '0.00', inputType: 'number' }
    ];

    const tableColumnDefinitions = [
        { data: 'transaction_id', title: 'Islem ID' },
        { data: 'type', title: 'Tip' },
        { data: 'status', title: 'Durum' },
        { data: 'source', title: 'Kaynak' },
        { data: 'site_name', title: 'Site' },
        { data: null, title: 'Tutar' },
        { data: 'customer_name', title: 'Musteri' },
        { data: 'customer_player_id', title: 'Uye ID' },
        { data: 'ip_address', title: 'IP Adresi' },
        { data: 'customer_iban', title: 'IBAN' },
        { data: 'customer_account_holder', title: 'Hesap Adi' },
        { data: 'finance_group', title: 'Finans Grubu' },
        { data: 'bank_account', title: 'Banka Hesabi' },
        { data: 'created_by_name', title: 'Olusturan' },
        { data: 'approved_by_name', title: 'Onaylayan' },
        { data: 'created_at', title: 'Tarih' }
    ];
    const datePickers = flatpickr('.datetimepicker', {
        enableTime: true,
        time_24hr: true,
        dateFormat: 'd/m/Y H:i',
        minuteIncrement: 1,
        allowInput: true
    });

    const $dateFromInput = $('input[name="date_from"]');
    const $dateToInput = $('input[name="date_to"]');
    const defaultDateFrom = @json(now('Europe/Istanbul')->subHours(24)->format('d/m/Y H:i'));
    const defaultDateTo = @json(now('Europe/Istanbul')->format('d/m/Y H:i'));

    if (!$dateFromInput.val() && !$dateToInput.val()) {
        if (datePickers[0]) {
            datePickers[0].setDate(defaultDateFrom, true, 'd/m/Y H:i');
        }
        if (datePickers[1]) {
            datePickers[1].setDate(defaultDateTo, true, 'd/m/Y H:i');
        }
    }

    function normalizeDateTime(value) {
        if (!value) return '';
        const parts = String(value).trim().split(' ');
        const datePart = parts[0] || '';
        const timePart = parts[1] || '00:00';
        const dateBits = datePart.split('/');
        if (dateBits.length !== 3) return value;
        return `${dateBits[2]}-${dateBits[1]}-${dateBits[0]} ${timePart}`;
    }

    function parseAmountValue(value) {
        if (typeof value === 'number') {
            return value;
        }

        let normalized = String(value ?? '').trim();
        if (!normalized) {
            return 0;
        }

        normalized = normalized.replace(/[^\d,.-]/g, '');

        if (normalized.includes(',') && normalized.includes('.')) {
            normalized = normalized.replace(/,/g, '');
        } else if (normalized.includes(',')) {
            normalized = normalized.replace(/\./g, '').replace(',', '.');
        } else {
            normalized = normalized.replace(/,/g, '');
        }

        const parsed = parseFloat(normalized);
        return Number.isFinite(parsed) ? parsed : 0;
    }

    function formatAmountTotal(amount, currency) {
        return amount.toLocaleString('tr-TR', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        }) + ' ' + currency;
    }

    function stripHtmlForExport(value) {
        return $('<div>')
            .html(String(value ?? '').replace(/<br\s*\/?>/gi, ' '))
            .text()
            .replace(/\s+/g, ' ')
            .trim();
    }

    function buildExportFilename(prefix) {
        const now = new Date();
        const pad = (num) => String(num).padStart(2, '0');
        return `${prefix}${pad(now.getDate())}-${pad(now.getMonth() + 1)}-${now.getFullYear()}`;
    }

    function renderTextFilterMenu() {
        const html = textFilterDefinitions.map(function(filter) {
            return `<button type="button" class="dropdown-item text-filter-option" data-filter-key="${filter.key}">${filter.label}</button>`;
        }).join('');
        $textFilterMenu.html(html);
        updateTextFilterMenuState();
    }

    function updateTextFilterMenuState() {
        const activeKeys = getActiveTextFilterKeys();
        $textFilterMenu.find('.text-filter-option').each(function() {
            const key = $(this).data('filter-key');
            const isActive = activeKeys.includes(String(key));
            $(this)
                .toggleClass('disabled', isActive)
                .attr('aria-disabled', isActive ? 'true' : 'false');
        });
    }

    function getActiveTextFilterKeys() {
        return $dynamicTextFilters.find('.dynamic-filter-card').map(function() {
            return String($(this).data('filter-key'));
        }).get();
    }

    function updateDynamicFilterState() {
        const count = $dynamicTextFilters.find('.dynamic-filter-card').length;
        $emptyDynamicFilters.toggle(count === 0);
        $activeFilterCount.text(`${count} filtre`);
        updateTextFilterMenuState();
    }

    function buildDynamicFilterCard(definition, value) {
        const safeValue = String(value || '').replace(/"/g, '&quot;');
        const inputType = definition.inputType || 'text';
        const inputMode = definition.inputType === 'number' ? 'decimal' : 'text';

        return `
            <div class="dynamic-filter-card" data-filter-key="${definition.key}">
                <div class="filter-meta">
                    <span class="filter-label">${definition.label}</span>
                    <button type="button" class="filter-remove" title="Filtreyi kaldir">
                        <i class="bi bi-x-lg"></i>
                    </button>
                </div>
                <input
                    type="${inputType}"
                    inputmode="${inputMode}"
                    class="form-control form-control-sm dynamic-filter-input"
                    data-filter-key="${definition.key}"
                    placeholder="${definition.placeholder || ''}"
                    value="${safeValue}"
                >
            </div>
        `;
    }

    function addTextFilter(key, value) {
        const definition = textFilterDefinitions.find(function(filter) {
            return filter.key === key;
        });
        if (!definition) {
            return;
        }

        const existing = $dynamicTextFilters.find(`.dynamic-filter-card[data-filter-key="${key}"]`);
        if (existing.length) {
            existing.find('.dynamic-filter-input').focus();
            return;
        }

        $dynamicTextFilters.append(buildDynamicFilterCard(definition, value));
        updateDynamicFilterState();
        $dynamicTextFilters.find(`.dynamic-filter-card[data-filter-key="${key}"] .dynamic-filter-input`).focus();
    }

    function clearTextFilters() {
        $dynamicTextFilters.empty();
        updateDynamicFilterState();
    }

    function getFilters() {
        const filters = {};
        $('#filterForm').serializeArray().forEach(function(item) {
            if (!item.value || item.name === 'date_from' || item.name === 'date_to') {
                return;
            }
            if (item.name === 'type' || item.name === 'status' || item.name === 'source' || item.name === 'finance_group_id' || item.name === 'site_id') {
                filters[item.name] = item.value;
            }
        });

        const dateFromValue = normalizeDateTime($dateFromInput.val());
        const dateToValue = normalizeDateTime($dateToInput.val());
        if (dateFromValue) {
            filters.date_from = dateFromValue;
        }
        if (dateToValue) {
            filters.date_to = dateToValue;
        }

        const textFilters = {};
        $dynamicTextFilters.find('.dynamic-filter-input').each(function() {
            const key = String($(this).data('filter-key'));
            const value = String($(this).val() || '').trim();
            if (value !== '') {
                textFilters[key] = value;
            }
        });

        filters.text_filters = textFilters;
        return filters;
    }

    function resetFilters() {
        $('#filterForm')[0].reset();
        clearTextFilters();

        if (datePickers[0]) {
            datePickers[0].setDate(defaultDateFrom, true, 'd/m/Y H:i');
        } else {
            $dateFromInput.val(defaultDateFrom);
        }

        if (datePickers[1]) {
            datePickers[1].setDate(defaultDateTo, true, 'd/m/Y H:i');
        } else {
            $dateToInput.val(defaultDateTo);
        }
    }
    const table = $('#transactionLogsTable').DataTable({
        processing: true,
        serverSide: false,
        autoWidth: false,
        deferRender: true,
        ajax: {
            url: '{{ route("backoffice.transaction-logs.index") }}',
            data: function(d) {
                return Object.assign(d, getFilters());
            }
        },
        columns: [
            { data: 'transaction_id' },
            {
                data: 'type',
                render: function(data) {
                    const label = data === 'deposit' ? 'Yatirim' : 'Cekim';
                    const cls = data === 'deposit' ? 'success' : 'danger';
                    return '<span class="badge bg-' + cls + '">' + label + '</span>';
                }
            },
            {
                data: 'status',
                render: function(data) {
                    const statusConfig = {
                        pending: { class: 'warning', label: 'Beklemede' },
                        approved: { class: 'info', label: 'Onaylandi' },
                        completed: { class: 'info', label: 'Onaylandi' },
                        declined: { class: 'danger', label: 'Reddedildi' },
                        failed: { class: 'danger', label: 'Reddedildi' }
                    };
                    const config = statusConfig[data] || { class: 'secondary', label: data || '-' };
                    return '<span class="status-pill bg-' + config.class + '">' + config.label + '</span>';
                }
            },
            {
                data: 'source',
                render: function(data) {
                    const isManual = (data || 'auto') === 'manual';
                    const label = isManual ? 'Manuel' : 'Auto';
                    const icon = isManual ? 'bi-hand-index' : 'bi-robot';
                    const cls = isManual ? 'secondary' : 'primary';
                    return '<span class="source-pill bg-' + cls + '"><i class="bi ' + icon + ' me-1"></i>' + label + '</span>';
                }
            },
            {
                data: 'site_name',
                render: function(data, type) {
                    if (type === 'filter' || type === 'sort' || type === 'type') {
                        return data || '';
                    }
                    if (!data || data === '-') {
                        return '<span class="text-muted">-</span>';
                    }
                    return '<span class="badge bg-light text-dark border">' + data + '</span>';
                }
            },
            {
                data: null,
                render: function(row, type) {
                    const rawAmount = String(row.amount || '').replace(/,/g, '');
                    const parsedAmount = parseFloat(rawAmount);
                    if (type === 'sort' || type === 'type') {
                        return isNaN(parsedAmount) ? 0 : parsedAmount;
                    }
                    if (type === 'export') {
                        const signedAmount = (row.type === 'withdrawal' ? -1 : 1) * (isNaN(parsedAmount) ? 0 : parsedAmount);
                        return signedAmount.toFixed(2);
                    }
                    const label = isNaN(parsedAmount)
                        ? (row.amount || '')
                        : parsedAmount.toLocaleString('tr-TR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
                    const cls = row.type === 'withdrawal' ? 'danger' : 'success';
                    const sign = row.type === 'withdrawal' ? '-' : '+';
                    return '<span class="fw-bold text-' + cls + '">' + sign + label + ' ' + row.currency + '</span>';
                }
            },
            { data: 'customer_name' },
            { data: 'customer_player_id' },
            { data: 'ip_address' },
            { data: 'customer_iban' },
            { data: 'customer_account_holder' },
            {
                data: 'finance_group',
                render: function(data, type, row) {
                    if (type === 'filter' || type === 'sort' || type === 'type') {
                        return data || '';
                    }
                    if (!data || data === '-') {
                        return '<span class="text-muted">-</span>';
                    }
                    const bg = row.finance_group_color || '#e2e8f0';
                    return '<span class="finance-group-badge" style="background:' + bg + ';">' + data + '</span>';
                }
            },
            {
                data: 'bank_account',
                render: function(data, type, row) {
                    const iban = row.bank_account_iban || '';
                    if (type === 'filter' || type === 'sort' || type === 'type') {
                        return [data || '', iban || ''].join(' ').trim();
                    }
                    const ibanLine = iban ? '<br><small class="text-muted">' + iban + '</small>' : '';
                    return (data || '-') + ibanLine;
                }
            },
            { data: 'created_by_name' },
            { data: 'approved_by_name' },
            {
                data: 'created_at',
                render: function(data, type, row) {
                    if (type === 'sort' || type === 'type') {
                        return row.created_at_timestamp || 0;
                    }
                    return data;
                }
            }
        ],
        order: [[15, 'desc']],
        pageLength: 50,
        footerCallback: function() {
            const api = this.api();
            const visibleRows = api.rows({ page: 'current', search: 'applied' }).data().toArray();
            const totalAmount = visibleRows.reduce(function(sum, row) {
                const amount = parseAmountValue(row.amount);
                const signedAmount = String(row.type || '').toLowerCase() === 'withdrawal' ? -amount : amount;
                return sum + signedAmount;
            }, 0);

            const currency = (visibleRows[0] && visibleRows[0].currency) ? visibleRows[0].currency : 'TRY';
            $(api.column(5).footer()).html('<span class="text-primary fw-bold">' + formatAmountTotal(totalAmount, currency) + '</span>');
        },
        language: {
            url: '//cdn.datatables.net/plug-ins/1.13.6/i18n/tr.json'
        }
    });

    function buildColumnSelector() {
        const html = tableColumnDefinitions.map(function(column, index) {
            return `
                <label class="dropdown-item d-flex align-items-center gap-2 mb-1">
                    <input type="checkbox" class="form-check-input mt-0 column-toggle" data-column-index="${index}" ${table.column(index).visible() ? 'checked' : ''}>
                    <span>${column.title}</span>
                </label>
            `;
        }).join('');
        $columnSelectorMenu.html(html);
    }

    function syncColumnSelector() {
        $columnSelectorMenu.find('.column-toggle').each(function() {
            const index = Number($(this).data('column-index'));
            $(this).prop('checked', table.column(index).visible());
        });
    }

    function toggleFullscreen(forceState) {
        const nextState = typeof forceState === 'boolean'
            ? forceState
            : !$tableShell.hasClass('table-shell-fullscreen');

        $tableShell.toggleClass('table-shell-fullscreen', nextState);
        $('body').toggleClass('table-fullscreen-open', nextState);
        $toggleFullscreenBtn.html(nextState
            ? '<i class="bi bi-fullscreen-exit me-1"></i>Cikis'
            : '<i class="bi bi-arrows-fullscreen me-1"></i>Tam Ekran'
        );

        setTimeout(function() {
            table.columns.adjust().draw(false);
        }, 150);
    }
    if (canExportExcel) {
        const exportButtons = new $.fn.dataTable.Buttons(table, {
            buttons: [
                {
                    extend: 'excelHtml5',
                    text: '<i class="bi bi-file-earmark-excel me-1"></i>Excel',
                    className: 'btn btn-success text-light btn-sm',
                    title: 'Islem Loglari',
                    filename: function() {
                        return buildExportFilename('islem_loglari_');
                    },
                    exportOptions: {
                        columns: ':visible',
                        orthogonal: 'export',
                        modifier: {
                            search: 'applied',
                            order: 'applied',
                            page: 'all'
                        },
                        format: {
                            body: function(innerHtml) {
                                return stripHtmlForExport(innerHtml);
                            }
                        }
                    }
                }
            ]
        });

        $('#transactionLogsTableExportButtons').empty().append(exportButtons.container());
    } else {
        $('#transactionLogsTableExportButtons').empty();
    }

    renderTextFilterMenu();
    updateDynamicFilterState();
    buildColumnSelector();

    $textFilterMenu.on('click', '.text-filter-option', function() {
        if ($(this).hasClass('disabled')) {
            return;
        }
        addTextFilter(String($(this).data('filter-key')), '');
    });

    $dynamicTextFilters.on('click', '.filter-remove', function() {
        $(this).closest('.dynamic-filter-card').remove();
        updateDynamicFilterState();
    });

    $('#clearTextFiltersBtn').on('click', function() {
        clearTextFilters();
    });

    $('#resetFiltersBtn').on('click', function() {
        resetFilters();
        table.ajax.reload();
    });

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

    $columnSelectorMenu.on('change', '.column-toggle', function() {
        const index = Number($(this).data('column-index'));
        table.column(index).visible($(this).is(':checked'), false);
        table.columns.adjust().draw(false);
    });

    $toggleFullscreenBtn.on('click', function() {
        toggleFullscreen();
    });

    $(document).on('keydown', function(event) {
        if (event.key === 'Escape' && $tableShell.hasClass('table-shell-fullscreen')) {
            toggleFullscreen(false);
        }
    });

    table.on('draw.dt', function() {
        syncColumnSelector();
    });
});
</script>
@endpush
