@extends('backoffice.layouts.app')

@section('title', 'Cekimler')

@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-arrow-up-circle text-danger me-2"></i>
                        Cekimler
                    </h2>
                    <p class="text-muted">Tum cekim islemlerini goruntuleyin ve yonetin</p>
                </div>
                @if(can_access('withdrawals', 'create'))
                <button class="btn btn-danger" id="btnCreateManualWithdrawal">
                    <i class="bi bi-plus-circle me-2"></i>Yeni Manuel Cekim Olustur
                </button>
                @endif
            </div>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="row g-3 mb-4">
        <div class="col-md-2">
            <div class="card border-0 shadow-sm status-card active" data-status="">
                <div class="card-body text-center">
                    <h3 class="mb-1">{{ $stats['total'] }}</h3>
                    <small class="text-muted">Toplam İşlem</small>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="card border-0 shadow-sm status-card" data-status="pending">
                <div class="card-body text-center">
                    <h3 class="mb-1 text-warning">{{ $stats['pending'] }}</h3>
                    <small class="text-muted">Bekleyen</small>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="card border-0 shadow-sm status-card" data-status="approved">
                <div class="card-body text-center">
                    <h3 class="mb-1 text-info">{{ $stats['approved'] }}</h3>
                    <small class="text-muted">Onaylandı</small>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="card border-0 shadow-sm status-card" data-status="declined">
                <div class="card-body text-center">
                    <h3 class="mb-1 text-danger">{{ $stats['declined'] }}</h3>
                    <small class="text-muted">Reddedildi</small>
                </div>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="card border-0 shadow-sm mb-4">
        <div class="card-body">
            <form id="filterForm">
                @if(!empty($isSiteScoped) && !empty($forcedSiteId))
                    <input type="hidden" name="site_id" value="{{ $forcedSiteId }}">
                @endif
                <div class="row g-3">
                    <div class="col-md-2">
                        <label class="form-label small">Durum</label>
                        <select name="status" class="form-select form-select-sm">
                            <option value="">Tümü</option>
                            <option value="pending">Bekleyen</option>
                            <option value="approved">Onaylandı</option>
                            <option value="declined">Reddedildi</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label small">Finans Grubu</label>
                        <select name="finance_group_id" class="form-select form-select-sm">
                            <option value="">Tümü</option>
                            @foreach($financeGroups as $group)
                                <option value="{{ $group->id }}">{{ $group->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    @if(empty($isSiteScoped))
                        <div class="col-md-2">
                            <label class="form-label small">Site</label>
                            <select name="site_id" class="form-select form-select-sm">
                                <option value="">Tümü</option>
                                @foreach($sites as $site)
                                    <option value="{{ $site->id }}">{{ $site->name }}</option>
                                @endforeach
                            </select>
                        </div>
                    @endif
                    <div class="col-md-2">
                        <label class="form-label small">Tarih Modu</label>
                        <select name="date_mode" class="form-select form-select-sm">
                            <option value="gaming" {{ request('date_mode', 'gaming') === 'gaming' ? 'selected' : '' }}>Gaming</option>
                            <option value="actual" {{ request('date_mode') === 'actual' ? 'selected' : '' }}>Actual</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label small">Başlangıç Tarihi</label>
                        <input type="text" name="date_from" class="form-control form-control-sm datetimepicker" placeholder="dd/mm/yyyy hh:mm">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label small">Bitiş Tarihi</label>
                        <input type="text" name="date_to" class="form-control form-control-sm datetimepicker" placeholder="dd/mm/yyyy hh:mm">
                    </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>
                </div>
            </form>
        </div>
    </div>

    <!-- Transactions Table -->
    <div class="card border-0 shadow-sm">
        <div class="card-header bg-white border-bottom">
            <div class="d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Cekim Listesi</h5>
                <div class="d-flex align-items-center gap-2">
                    <div id="transactionsTableExportButtons"></div>
                    <div class="input-group" style="width: 300px;">
                        <span class="input-group-text bg-white">
                            <i class="bi bi-search"></i>
                        </span>
                        <input type="text" id="searchInput" class="form-control" placeholder="İşlem ID, Site, Müşteri, TC, IBAN...">
                    </div>
                </div>
            </div>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table id="transactionsTable" class="table table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th width="90">Kaynak</th>
                            <th class="d-none">Personel</th>
                            <th>Site</th>
                            <th>Hesap Adi</th>
                            <th width="120">Tutar</th>
                            <th>Finans Grubu</th>
                            <th>Banka Hesabı</th>
                            <th width="100">Durum</th>
                            <th width="120">Tarih</th>
                            <th width="120" class="text-center">İşlemler</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Data will be loaded via AJAX -->
                    </tbody>
                    <tfoot class="table-light">
                        <tr>
                            <th colspan="3" class="text-end">Sayfada Onayli Toplam:</th>
                            <th class="text-danger fw-bold">0,00 TRY</th>
                            <th colspan="6"></th>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Transaction Detail Modal -->
<div class="modal fade" id="transactionDetailModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-receipt"></i>
                    İşlem Detayı
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="transactionDetailContent">
                <!-- Content will be loaded via AJAX -->
                <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>

<!-- Decline Modal -->
<div class="modal fade" id="declineModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">
                    <i class="bi bi-x-circle"></i>
                    Islemi Reddet
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form id="declineForm">
                <div class="modal-body">
                    <input type="hidden" id="declineTransactionId">
                    <div class="mb-3">
                        <label class="form-label">Hazir Cevaplar</label>
                        <select id="declinePreset" class="form-select">
                            <option value="">Seciniz</option>
                            @foreach($cannedResponses as $response)
                                <option value="{{ $response->content }}">{{ $response->content }}</option>
                            @endforeach
                        </select>
                        <small class="text-muted">Secince red nedeni otomatik doldurulur.</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Red Nedeni <span class="text-danger">*</span></label>
                        <textarea name="notes" class="form-control" rows="3" required></textarea>
                    </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-danger"><i class="bi bi-x-circle me-2"></i>Reddet</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Create Withdrawal Modal -->
<div class="modal fade" id="createWithdrawalModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title" id="createWithdrawalTitle"><i class="bi bi-plus-circle me-2"></i>Yeni Manuel Cekim Olustur</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form id="createWithdrawalForm">
                <input type="hidden" id="assignWithdrawalId">
                <input type="hidden" id="assignWithdrawalSource" value="">
                <div class="modal-body">
                    <div class="row">
                        @if(empty($isSiteScoped))
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Site <span class="text-danger">*</span></label>
                                <select name="site_id" id="withdrawalSiteId" class="form-select" required>
                                    <option value="">Site secin</option>
                                    @foreach($sites as $site)
                                        <option value="{{ $site->id }}">{{ $site->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                        @else
                            <input type="hidden" name="site_id" id="withdrawalSiteId" value="{{ $forcedSiteId }}">
                        @endif
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Finans Grubu <span class="text-danger">*</span></label>
                            <select name="finance_group_id" id="withdrawalFinanceGroup" class="form-select" required>
                                <option value="">Finans grubu secin</option>
                                @foreach($financeGroups as $group)
                                    <option value="{{ $group->id }}">
                                        {{ $group->name }} ({{ number_format($group->min_amount, 0, ',', '.') }}-{{ number_format($group->max_amount, 0, ',', '.') }} TL)
                                    </option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">IBAN <span class="text-danger">*</span></label>
                            <input type="text" name="iban" id="withdrawalIban" class="form-control" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3 assign-account-holder-wrap">
                            <label class="form-label">Uye Adi <span class="text-danger">*</span></label>
                            <input type="text" name="customer_account_holder" id="withdrawalAccountHolder" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Tutar (TL) <span class="text-danger">*</span></label>
                            <input type="text" name="amount" id="withdrawalAmount" class="form-control number-input" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12 mb-3">
                            <label class="form-label">Aciklama</label>
                            <textarea name="notes" id="withdrawalNotes" class="form-control" rows="3" placeholder="Orn: 10.000"></textarea>
                        </div>
                    </div>
                    <div class="row assign-only">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Uye ID <span class="text-danger">*</span></label>
                            <input type="text" name="customer_player_id" id="withdrawalCustomerPlayerId" class="form-control">
                            <small class="text-muted">API tarafindan gonderilir.</small>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Uye Adi Soyadi <span class="text-danger">*</span></label>
                            <input type="text" name="customer_name" id="withdrawalCustomerName" class="form-control">
                            <small class="text-muted">API tarafindan gonderilir.</small>
                        </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-danger"><i class="bi bi-check-circle me-2"></i>Cekim Olustur</button>
                </div>
            </form>
        </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>
    .status-card { cursor: pointer; transition: transform 0.15s, box-shadow 0.15s, border-color 0.15s; border: 1px dashed #e5e7eb; }
    .status-card:hover { transform: translateY(-2px); border-color: #93c5fd; }
    .status-card.active { box-shadow: 0 0 0 2px rgba(13, 110, 253, 0.25); border: 2px solid #4f8df7 !important; outline: 2px solid #4f8df7; outline-offset: -2px; }
    .status-card .card-body { position: relative; }
    .status-card .card-body::after {
        content: 'Filtrele';
        position: absolute;
        right: 10px;
        bottom: 8px;
        font-size: 10px;
        color: #9ca3af;
        letter-spacing: 0.2px;
    }
    .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;
    }
    .source-pill {
        display: block;
        width: 100%;
        text-align: center;
        font-size: 0.9rem;
        font-weight: 600;
        padding: 5px 8px;
        border-radius: 8px;
        color: #fff;
    }
</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 canUpdateWithdrawals = {!! can_access('withdrawals', 'update') ? 'true' : 'false' !!};
    const canExportExcel = {!! can_access('export_excel', 'read') ? 'true' : 'false' !!};
    const forcedSiteId = @json($forcedSiteId ?? null);
    const transactionsIndexUrl = @json(!empty($isSiteScoped) && !empty($forcedSiteId) ? route('backoffice.sites.withdrawals.index', $forcedSiteId) : route('backoffice.withdrawals.index'));
    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 $dateMode = $('select[name="date_mode"]');
    const defaultGamingDateFrom = @json(\App\Support\BusinessTime::startOfBusinessDay(\App\Support\BusinessTime::currentBusinessDate()->format('Y-m-d'))->format('d/m/Y H:i'));
    const defaultGamingDateTo = @json(\App\Support\BusinessTime::endOfBusinessDay(\App\Support\BusinessTime::currentBusinessDate()->format('Y-m-d'))->format('d/m/Y H:i'));
    const defaultActualDateFrom = @json(now('Europe/Istanbul')->subHours(24)->format('d/m/Y H:i'));
    const defaultActualDateTo = @json(now('Europe/Istanbul')->format('d/m/Y H:i'));

    function applyDefaultDates(mode) {
        const useActual = mode === 'actual';
        const start = useActual ? defaultActualDateFrom : defaultGamingDateFrom;
        const end = useActual ? defaultActualDateTo : defaultGamingDateTo;
        if (datePickers[0]) {
            datePickers[0].setDate(start, true, 'd/m/Y H:i');
        }
        if (datePickers[1]) {
            datePickers[1].setDate(end, true, 'd/m/Y H:i');
        }
    }

    if (!$dateFromInput.val() && !$dateToInput.val()) {
        applyDefaultDates($dateMode.val() || 'gaming');
    }

    $dateMode.on('change', function() {
        applyDefaultDates(this.value);
    });

    let table;
    let lastCheckTimestamp = Math.floor(Date.now() / 1000);
    let pollingInterval = null;
    const autoRefreshEnabled = true;
    const autoRefreshIntervalMs = 5000;
    let statsRefreshTimer = null;

    // Notification sound function
    const notificationSound = new Audio('{{ asset('audio/withdrawal.mp3') }}');
    notificationSound.preload = 'auto';
    notificationSound.volume = 0.7;
    notificationSound.addEventListener('error', function() {
        console.warn('Notification sound failed to load:', notificationSound.src);
    });
    let soundUnlocked = false;

    function unlockSound() {
        if (soundUnlocked) return;
        notificationSound.play().then(function() {
            notificationSound.pause();
            notificationSound.currentTime = 0;
            soundUnlocked = true;
        }).catch(function() {});
    }

    document.addEventListener('click', unlockSound, { once: true });
    document.addEventListener('keydown', unlockSound, { once: true });
    document.addEventListener('touchstart', unlockSound, { once: true });

    function playNotificationSound() {
        if (!soundUnlocked) {
            unlockSound();
        }
        notificationSound.currentTime = 0;
        notificationSound.play().catch(() => {});
    }

    const notificationToast = Swal.mixin({
        toast: true,
        position: 'top-end',
        showConfirmButton: false,
        timer: 3000,
        timerProgressBar: true,
        didOpen: (toast) => {
            toast.addEventListener('mouseenter', Swal.stopTimer);
            toast.addEventListener('mouseleave', Swal.resumeTimer);
        }
    });

    function showNotificationToast(options) {
        const fire = () => notificationToast.fire(options);
        if (Swal.isVisible()) {
            const interval = setInterval(function() {
                if (!Swal.isVisible()) {
                    clearInterval(interval);
                    fire();
                }
            }, 250);
            return;
        }
        fire();
    }

    // Check for new withdrawals
    function checkNewDeposits() {
        $.ajax({
            url: '{{ route("backoffice.withdrawals.check-new") }}',
            method: 'GET',
            data: {
                since: lastCheckTimestamp,
                site_id: forcedSiteId || ''
            },
            success: function(response) {
                if (!response || !response.success) {
                    return;
                }

                const latestFromServer = response.latest_timestamp ? Number(response.latest_timestamp) : lastCheckTimestamp;
                if (response.data && response.data.length > 0) {
                    const latestCreated = Math.max(...response.data.map(d => d.created_at_timestamp));
                    lastCheckTimestamp = Math.max(lastCheckTimestamp, latestFromServer, latestCreated);
                } else {
                    lastCheckTimestamp = Math.max(lastCheckTimestamp, latestFromServer);
                }

                if (response.count > 0) {
                    // Play notification sound
                    playNotificationSound();

                    // Show notification message
                    showNotificationToast({
                        title: 'Yeni Cekim!',
                        html: `<strong>${response.count}</strong> yeni cekim islemi alindi.`,
                        icon: 'info'
                    });
                }

                if (response.updated_count > 0) {
                    table.ajax.reload(null, false);
                    refreshStats();
                }
            },
            error: function(xhr) {
                console.error('Error checking for new withdrawals:', xhr);
            }
        });
    }

    // Start polling
    function startPolling() {
        if (pollingInterval) {
            return;
        }
        pollingInterval = setInterval(checkNewDeposits, autoRefreshIntervalMs);
    }

    // Stop polling (useful for cleanup)
    function stopPolling() {
        if (pollingInterval) {
            clearInterval(pollingInterval);
            pollingInterval = null;
        }
    }

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

    function getFilters() {
        const filters = {};
        $('#filterForm').serializeArray().forEach(function(item) {
            if (item.value !== '') {
                filters[item.name] = item.value;
            }
        });
        if (forcedSiteId) {
            filters.site_id = String(forcedSiteId);
        }
        if (filters.date_from) {
            filters.date_from = normalizeDateTime(filters.date_from);
        }
        if (filters.date_to) {
            filters.date_to = normalizeDateTime(filters.date_to);
        }
        return filters;
    }

    function getStatsFilters() {
        const filters = getFilters();
        const searchValue = $('#searchInput').val();
        if (searchValue) {
            filters.search = searchValue;
        }
        return filters;
    }

    function refreshStats() {
        $.ajax({
            url: '{{ route("backoffice.withdrawals.stats") }}',
            method: 'GET',
            data: getStatsFilters(),
            success: function(response) {
                if (!response) return;
                $('.status-card[data-status=""] h3').text(response.total ?? 0);
                $('.status-card[data-status="pending"] h3').text(response.pending ?? 0);
                $('.status-card[data-status="approved"] h3').text(response.approved ?? 0);
                $('.status-card[data-status="declined"] h3').text(response.declined ?? 0);
            }
        });
    }

    function scheduleStatsRefresh() {
        if (statsRefreshTimer) {
            clearTimeout(statsRefreshTimer);
        }
        statsRefreshTimer = setTimeout(refreshStats, 250);
    }

    const financeGroupPalette = [
        'hsl(210, 70%, 82%)',
        'hsl(20, 80%, 82%)',
        'hsl(140, 55%, 80%)',
        'hsl(285, 55%, 84%)',
        'hsl(35, 85%, 82%)',
        'hsl(190, 60%, 82%)',
        'hsl(320, 55%, 84%)',
        'hsl(95, 60%, 80%)',
        'hsl(255, 60%, 84%)',
        'hsl(5, 80%, 82%)'
    ];

    function colorForFinanceGroup(row, label) {
        if (row && row.finance_group_color) {
            return row.finance_group_color;
        }
        if (row && row.finance_group_id) {
            const index = Math.abs(Number(row.finance_group_id)) % financeGroupPalette.length;
            return financeGroupPalette[index];
        }
        let hash = 5381;
        const value = String(label || '').toLowerCase();
        for (let i = 0; i < value.length; i++) {
            hash = ((hash << 5) + hash) + value.charCodeAt(i);
            hash |= 0;
        }
        const index = Math.abs(hash) % financeGroupPalette.length;
        return financeGroupPalette[index];
    }

    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.isNaN(parsed) ? 0 : parsed;
    }

    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()}`;
    }

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

        table = $('#transactionsTable').DataTable({
            processing: true,
            serverSide: false,
            ajax: {
                url: transactionsIndexUrl,
                data: function(d) {
                    return Object.assign(d, getFilters());
                }
            },
            columns: [
                
                {
                    data: 'source',
                    render: function(data, type, row) {
                        const isManual = (data || 'auto') === 'manual';
                        const label = isManual ? 'Manuel' : 'Auto';
                        if (type === 'export') {
                            return label;
                        }
                        const icon = isManual ? 'bi-hand-index' : 'bi-robot';
                        const cls = isManual ? 'secondary' : 'primary';
                        const nameLine = (isManual && row.created_by_name)
                            ? `<div class="small text-muted mt-1">${row.created_by_name}</div>`
                            : '';
                        return `<span class="source-pill bg-${cls}"><i class="bi ${icon} me-1"></i>${label}</span>${nameLine}`;
                    }
                },
                {
                    data: 'created_by_name',
                    visible: false,
                    searchable: false,
                    render: function(data, type, row) {
                        const isManual = (row.source || 'auto') === 'manual';
                        const personel = isManual ? (data || '-') : '-';
                        return personel;
                    }
                },
                {
                    data: 'site_name',
                    render: function(data) {
                        if (!data || data === '-') {
                            return '<span class="text-muted">-</span>';
                        }
                        return '<span class="badge bg-light text-dark border">' + data + '</span>';
                    }
                },
                {
                    data: 'customer_account_holder',
                    render: function(data, type, row) {
                        if (data) {
                            return data;
                        }
                        if (row.customer_name) {
                            return row.customer_name;
                        }
                        if (row.bank_account && row.bank_account !== '-') {
                            return row.bank_account;
                        }
                        return '-';
                    }
                },
                {
                    data: null,
                    render: function(data, type) {
                        const rawAmount = (data.amount || '').toString().replace(/,/g, '');
                        const parsedAmount = parseFloat(rawAmount);
                        if (type === 'sort' || type === 'type') {
                            return isNaN(parsedAmount) ? 0 : parsedAmount;
                        }
                        const amountLabel = isNaN(parsedAmount)
                            ? (data.amount || '')
                            : parsedAmount.toLocaleString('tr-TR', {minimumFractionDigits: 2, maximumFractionDigits: 2});
                        if (type === 'export') {
                            return isNaN(parsedAmount) ? '' : parsedAmount.toFixed(2);
                        }
                        return '<span class="fw-bold text-danger">' + amountLabel + ' ' + data.currency + '</span>';
                    }
                },
                {
                    data: 'finance_group',
                    render: function(data, type, row) {
                        if (data === '-' || !data) {
                            return '<span class="text-muted">-</span>';
                        }
                        const bg = colorForFinanceGroup(row, data);
                        return '<span class="finance-group-badge" style="background:' + bg + ';">' + data + '</span>';
                    }
                },
                {
                    data: 'bank_account',
                    render: function(data, type, row) {
                        const bankName = row.customer_bank_name || '';
                        const iban = row.bank_account_iban || row.customer_iban || '';
                        const mainLine = (data && data !== '-') ? data : (bankName || '-');
                        const ibanLine = iban ? `<br><small class="text-muted">${iban}</small>` : '';
                        return `${mainLine}${ibanLine}`;
                    }
                },
                {
                    data: 'status',
                    render: function(data) {
                        const statusConfig = {
                            'pending': { class: 'warning', label: 'Beklemede' },
                            'approved': { class: 'info', label: 'Onaylandı' },
                            'completed': { class: 'info', label: 'Onaylandı' },
                            '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: 'created_at',
                    render: function(data, type, row) {
                        if (type === 'sort' || type === 'type') {
                            return row.created_at_timestamp || 0;
                        }
                        return data;
                    }
                },
                {
                    data: null,
                    orderable: false,
                    render: function(data) {
                        let buttons = '<div class="btn-group btn-group-sm">';
                        buttons += '<button class="btn btn-outline-primary btn-view" data-id="' + data.id + '" title="Detay"><i class="bi bi-eye"></i></button>';

                        const needsAssign = data.status === 'pending' && !data.finance_group_id;

                        if (data.status === 'pending' && canUpdateWithdrawals) {
                            if (needsAssign) {
                                buttons += '<button class="btn btn-outline-warning btn-assign" data-id="' + data.id + '" title="Finans Ata"><i class="bi bi-ui-checks"></i></button>';
                            } else {
                                buttons += '<button class="btn btn-outline-success btn-approve" data-id="' + data.id + '" title="Onayla"><i class="bi bi-check-circle"></i></button>';
                            }
                            buttons += '<button class="btn btn-outline-danger btn-decline" data-id="' + data.id + '" title="Reddet"><i class="bi bi-x-circle"></i></button>';
                        }

                        buttons += '</div>';
                        return buttons;
                    }
                }
            ],
            order: [[8, 'desc']],
            pageLength: 25,
            footerCallback: function() {
                const api = this.api();
                const visibleRows = api.rows({ page: 'current', search: 'applied' }).data().toArray();
                const approvedRows = visibleRows.filter(function(row) {
                    const status = String(row.status || '').toLowerCase();
                    return status === 'approved' || status === 'completed';
                });
                const totalAmount = approvedRows.reduce(function(sum, row) {
                    return sum + parseAmountValue(row.amount);
                }, 0);
                const currency = (approvedRows[0] && approvedRows[0].currency)
                    ? approvedRows[0].currency
                    : ((visibleRows[0] && visibleRows[0].currency) ? visibleRows[0].currency : 'TRY');

                $(api.column(4).footer()).html(
                    '<span class="text-danger fw-bold">' + formatAmountTotal(totalAmount, currency) + '</span>'
                );
            },
            language: {
                url: '//cdn.datatables.net/plug-ins/1.13.6/i18n/tr.json'
            }
        });

        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: 'Cekim Listesi',
                        filename: function() {
                            return buildExportFilename('cekimler_');
                        },
                        exportOptions: {
                            columns: [0, 1, 2, 3, 4, 5, 6, 7, 8],
                            orthogonal: 'export',
                            modifier: {
                                search: 'applied',
                                order: 'applied',
                                page: 'all'
                            },
                            format: {
                                body: function(innerHtml) {
                                    return stripHtmlForExport(innerHtml);
                                }
                            }
                        }
                    }
                ]
            });

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

    // Initialize table
    initTable();
    refreshStats();

    // Start polling for new withdrawals
    if (autoRefreshEnabled) {
        startPolling();
    }

    document.addEventListener('visibilitychange', function() {
        if (!autoRefreshEnabled) return;
        if (document.hidden) {
            stopPolling();
            return;
        }
        checkNewDeposits();
        startPolling();
    });

    // Stop polling when leaving page
    $(window).on('beforeunload', function() {
        stopPolling();
    });

    // Filter form submit
    $('#filterForm').on('submit', function(e) {
        e.preventDefault();
        table.ajax.reload();
        setActiveStatusCard($('select[name="status"]').val() || '');
        refreshStats();
    });

    function setActiveStatusCard(status) {
        $('.status-card').removeClass('active');
        const target = status ? `.status-card[data-status="${status}"]` : '.status-card[data-status=""]';
        $(target).addClass('active');
    }

    $('.status-card').on('click', function() {
        const status = $(this).data('status') || '';
        $('select[name="status"]').val(status);
        table.ajax.reload();
        setActiveStatusCard(status);
        refreshStats();
    });

    setActiveStatusCard($('select[name="status"]').val() || '');

    // Search input
    $('#searchInput').on('keyup', function() {
        table.search(this.value).draw();
        scheduleStatsRefresh();
    });

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

        $.ajax({
            url: '{{ route("backoffice.withdrawals.show", ":id") }}'.replace(':id', id),
            success: function(response) {
                const t = response.transaction;
                const sourceValue = t.source || 'auto';
                const sourceLabel = sourceValue === 'manual' ? 'Manuel' : 'Auto';
                const sourceIcon = sourceValue === 'manual' ? 'bi-hand-index' : 'bi-robot';
                const sourceBadge = `<span class="badge bg-${sourceValue === 'manual' ? 'secondary' : 'primary'}"><i class="bi ${sourceIcon} me-1"></i>${sourceLabel}</span>`;
                const statusMeta = t.status === 'pending' ? '' : `<div class="small text-muted mt-1"><i class="bi bi-person-check me-1"></i>${(t.approved_by && t.approved_by.full_name) ? t.approved_by.full_name : (t.approved_by_name || '-')} ${t.approved_at ? ' - ' + new Date(t.approved_at).toLocaleString('tr-TR') : ''}</div>`;
                let html = `
                    <div class="row g-3">
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">İşlem ID</p>
                            <p class="fw-semibold"><code>${t.transaction_id}</code></p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">Dış İşlem ID</p>
                            <p class="fw-semibold">${t.external_transaction_id || '-'}</p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">İşlem Tipi</p>
                            <p class="fw-semibold">${t.type === 'deposit' ? '<span class=\"badge bg-success\">Yatirim</span>' : '<span class=\"badge bg-danger\">Cekim</span>'}</p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">Kaynak</p>
                            <p class="fw-semibold">${sourceBadge}</p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">Site</p>
                            <p class="fw-semibold">${t.site_name || (t.site ? t.site.name : '-') }</p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">Durum</p>
                            <p class="fw-semibold"><span class="badge bg-${(t.status === 'pending') ? 'warning' : (t.status === 'declined' || t.status === 'failed') ? 'danger' : 'info'}">${(t.status === 'declined' || t.status === 'failed') ? 'Reddedildi' : (t.status === 'pending') ? 'Beklemede' : 'Onaylandi'}</span>${statusMeta}</p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">Tutar</p>
                            <p class="fw-semibold fs-5 text-danger">${parseFloat(t.amount).toFixed(2)} ${t.currency}</p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">Uye Adi Soyadi</p>
                            <p class="fw-semibold mb-1">${t.customer_name} ${t.customer_surname || ''}</p>
                            <div class="small text-muted">Uye ID: ${t.customer_player_id || '-'}</div>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">TC Kimlik No</p>
                            <p class="fw-semibold">${t.customer_tc || '-'}</p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">IBAN</p>
                            <p class="fw-semibold">${t.bank_account ? t.bank_account.iban : (t.customer_iban || '-')}</p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">Hesap Adi</p>
                            <p class="fw-semibold">${t.customer_account_holder || (t.bank_account ? t.bank_account.account_name : '-') }</p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">Finans Grubu</p>
                            <p class="fw-semibold">${t.finance_group ? t.finance_group.name : '-'}</p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">IP Adresi</p>
                            <p class="fw-semibold">${t.ip_address || '-'}</p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">Tarih</p>
                            <p class="fw-semibold">${t.created_at_display || new Date(t.created_at).toLocaleString('tr-TR')}</p>
                        </div>
<div class="col-12">
                            <p class="mb-1 small text-muted">Aciklama</p>
                            <div class="alert alert-light border mb-0">${t.description ? t.description : '-'}</div>
                        </div>
                        ${t.notes ? `
                        <div class="col-12">
                            <p class="mb-1 small text-muted">Notlar</p>
                            <div class="alert alert-info mb-0">${t.notes}</div>
                        </div>
                        ` : ''}
                    </div>
                `;
                $('#transactionDetailContent').html(html);
            }
        });
    });

    function resetAssignModal() {
        $('#assignWithdrawalId').val('');
        $('#assignWithdrawalSource').val('');
        $('#createWithdrawalForm')[0].reset();
        if (forcedSiteId) {
            $('#withdrawalSiteId').val(forcedSiteId);
        } else {
            $('#withdrawalSiteId').val('');
        }
        $('#withdrawalCustomerPlayerId').val('');
        $('#withdrawalCustomerName').val('');
        $('#withdrawalAmount').val('');
        $('#withdrawalAccountHolder').val('');
        $('#withdrawalIban').val('');
        $('#withdrawalFinanceGroup').val('');
        $('#withdrawalNotes').val('');
        $('.assign-account-holder-wrap').show();
        $('#withdrawalAccountHolder').prop('required', true);
    }

    function setWithdrawalMode(isAssign, sourceValue = '') {
        const isApiAssign = isAssign && String(sourceValue || '').toLowerCase() === 'api';
        $('#withdrawalCustomerPlayerId').prop('readonly', isAssign);
        $('#withdrawalCustomerName').prop('readonly', isAssign);
        $('#withdrawalAmount').prop('readonly', isAssign);
        $('#withdrawalCustomerPlayerId').prop('required', isAssign);
        $('#withdrawalCustomerName').prop('required', isAssign);
        $('#withdrawalSiteId').prop('disabled', isAssign);
        $('#withdrawalSiteId').prop('required', !isAssign);
        $('#withdrawalAccountHolder').prop('required', !isApiAssign);
        $('.assign-account-holder-wrap').toggle(!isApiAssign);
        $('#createWithdrawalTitle').html(
            isAssign
                ? '<i class="bi bi-ui-checks me-2"></i>Finans Grubu Ata'
                : '<i class="bi bi-plus-circle me-2"></i>Yeni Manuel Cekim Olustur'
        );
        if (isAssign) {
            $('.assign-only').show();
        } else {
            $('.assign-only').hide();
        }
    }

    $('#createWithdrawalModal').on('hidden.bs.modal', function() {
        resetAssignModal();
    });

    $('#btnCreateManualWithdrawal').on('click', function() {
        resetAssignModal();
        setWithdrawalMode(false);
        $('#createWithdrawalModal').modal('show');
    });

    // Assign withdrawal to finance group
    $(document).on('click', '.btn-assign', function() {
        const id = $(this).data('id');
        $('#assignWithdrawalId').val(id);
        $('#assignWithdrawalSource').val('');
        setWithdrawalMode(true);
        $('#createWithdrawalModal').modal('show');

        $.ajax({
            url: '{{ route("backoffice.withdrawals.show", ":id") }}'.replace(':id', id),
            success: function(response) {
                const t = response.transaction;
                const amountValue = parseFloat(t.amount || 0);
                const amountLabel = isNaN(amountValue)
                    ? ''
                    : amountValue.toLocaleString('tr-TR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
                const sourceValue = String(t.source || 'auto').toLowerCase();
                $('#assignWithdrawalSource').val(sourceValue);
                setWithdrawalMode(true, sourceValue);
                $('#withdrawalCustomerPlayerId').val(t.customer_player_id || '');
                $('#withdrawalCustomerName').val(t.customer_name || '');
                $('#withdrawalAmount').val(amountLabel);
                $('#withdrawalAccountHolder').val(t.customer_account_holder || t.customer_name || '');
                $('#withdrawalIban').val(t.customer_iban || '');
                $('#withdrawalFinanceGroup').val(t.finance_group_id || '');
                $('#withdrawalSiteId').val(t.site_id || '');
            }
        });
    });

    
// Approve transaction
    $(document).on('click', '.btn-approve', function() {
        const id = $(this).data('id');

        Swal.fire({
            title: 'Islemi Onayla',
            text: 'Bu islemi onaylamak istediginizden emin misiniz?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Evet, Onayla',
            cancelButtonText: 'Iptal',
            confirmButtonColor: '#28a745'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '{{ route("backoffice.withdrawals.approve", ":id") }}'.replace(':id', id),
                    method: 'POST',
                    data: {
                        _token: '{{ csrf_token() }}'
                    },
                    success: function(response) {
                        Swal.fire('Ba?ar?l?!', response.message, 'success');
                        table.ajax.reload();
                        refreshStats();
                    },
                    error: function(xhr) {
                        Swal.fire('Hata!', xhr.responseJSON.message, 'error');
                    }
                });
            }
        });
    });

    // Decline transaction
    $(document).on('click', '.btn-decline', function() {
        const id = $(this).data('id');
        $('#declineTransactionId').val(id);
        $('#declineModal').modal('show');
    });

    $('#declinePreset').on('change', function() {
        const val = $(this).val();
        if (val) {
            $('#declineForm textarea[name="notes"]').val(val);
        }
    });

    $('#declineForm').on('submit', function(e) {
        e.preventDefault();
        const id = $('#declineTransactionId').val();
        const notes = $(this).find('[name="notes"]').val();

        $.ajax({
            url: '{{ route("backoffice.withdrawals.decline", ":id") }}'.replace(':id', id),
            method: 'POST',
            data: {
                _token: '{{ csrf_token() }}',
                notes: notes
            },
            success: function(response) {
                $('#declineModal').modal('hide');
                Swal.fire('Ba?ar?l?!', response.message, 'success');
                table.ajax.reload();
                refreshStats();
                $('#declineForm')[0].reset();
            },
            error: function(xhr) {
                Swal.fire('Hata!', xhr.responseJSON.message, 'error');
            }
        });
    });

    // Create withdrawal form submission
    $('#createWithdrawalForm').on('submit', function(e) {
        e.preventDefault();

        const $form = $(this);
        const $submitBtn = $form.find('button[type="submit"]');
        if ($submitBtn.data('submitting')) {
            return;
        }
        $submitBtn.data('submitting', true).prop('disabled', true);

        const assignId = $('#assignWithdrawalId').val();
        const assignSource = ($('#assignWithdrawalSource').val() || '').toLowerCase();
        const isApiAssign = !!assignId && assignSource === 'api';
        const formData = {
            amount: parseFormattedNumber($(this).find('[name="amount"]').val()),
            site_id: $(this).find('[name="site_id"]').val() || (forcedSiteId ? String(forcedSiteId) : ''),
            finance_group_id: $(this).find('[name="finance_group_id"]').val(),
            customer_player_id: $(this).find('[name="customer_player_id"]').val(),
            customer_name: $(this).find('[name="customer_name"]').val(),
            customer_account_holder: $(this).find('[name="customer_account_holder"]').val(),
            iban: $(this).find('[name="iban"]').val(),
            notes: $(this).find('[name="notes"]').val(),
            _token: '{{ csrf_token() }}'
        };

        if (isApiAssign && !formData.customer_account_holder) {
            formData.customer_account_holder = formData.customer_name || '';
        }

        const requiresPlayer = !!assignId;
        if (!formData.finance_group_id || (!isApiAssign && !formData.customer_account_holder) || !formData.iban || !formData.amount || (!assignId && !formData.site_id)) {
            Swal.fire('Hata!', 'Lutfen tum zorunlu alanlari doldurun.', 'error');
            $submitBtn.data('submitting', false).prop('disabled', false);
            return;
        }
        if (requiresPlayer && (!formData.customer_player_id || !formData.customer_name)) {
            Swal.fire('Hata!', 'Uye bilgileri eksik.', 'error');
            $submitBtn.data('submitting', false).prop('disabled', false);
            return;
        }

        $.ajax({
            url: assignId
                ? '{{ route("backoffice.withdrawals.assign", ":id") }}'.replace(':id', assignId)
                : '{{ route("backoffice.withdrawals.store") }}',
            method: 'POST',
            data: formData,
            success: function(response) {
                $('#createWithdrawalModal').modal('hide');
                resetAssignModal();
                Swal.fire({
                    title: 'Basarili!',
                    html: response.message,
                    icon: 'success'
                });
                table.ajax.reload();
                refreshStats();
            },
            error: function(xhr) {
                if (xhr.status === 422 && xhr.responseJSON.errors) {
                    let errorMsg = '<ul class="text-start">';
                    Object.keys(xhr.responseJSON.errors).forEach(function(key) {
                        errorMsg += '<li>' + xhr.responseJSON.errors[key][0] + '</li>';
                    });
                    errorMsg += '</ul>';
                    Swal.fire('Dogrulama Hatasi!', errorMsg, 'error');
                } else {
                    Swal.fire('Hata!', xhr.responseJSON?.message || 'Bir hata olustu', 'error');
                }
            },
            complete: function() {
                $submitBtn.data('submitting', false).prop('disabled', false);
            }
        });
    });
});
</script>
@endpush






