@extends('finance.layouts.app')

@section('title', 'Çekimler')

@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>
                        Çekimler
                    </h2>
                    <p class="text-muted">Tüm çekim işlemlerini görüntüleyin ve yönetin</p>
                </div>
            </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">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">İşlem Listesi</h5>
                <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 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 width="140">Site</th>
                            <th>Hesap Adi</th>
                            <th width="120">Tutar</th>
                            <th>Banka Hesabı</th>
                            <th width="100">Durum</th>
                            <th width="120">Tarih</th>
                            <th width="120" class="text-center">Çekimler</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Data will be loaded via AJAX -->
                    </tbody>
                </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>
                    İşlemi 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="4" required placeholder="İşlemi neden reddediyorsunuz?"></textarea>
                        <div class="invalid-feedback"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">İptal</button>
                    <button type="submit" class="btn btn-danger">
                        <i class="bi bi-x-circle"></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"><i class="bi bi-plus-circle me-2"></i>Yeni Çekim Oluştur</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form id="createWithdrawalForm">
                <input type="hidden" name="finance_group_id" value="{{ $financeGroup->id }}">
                @if(!empty($isSiteScoped) && !empty($forcedSiteId))
                    <input type="hidden" name="site_id" value="{{ $forcedSiteId }}">
                @endif
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Müşteri Adı <span class="text-danger">*</span></label>
                            <input type="text" name="customer_name" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Müşteri E-posta</label>
                            <input type="email" name="customer_email" class="form-control">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Tutar (₺) <span class="text-danger">*</span></label>
                            <input type="text" name="amount" id="withdrawalAmount" class="form-control" required>
                            <small class="text-muted">Örn: 10.000</small>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12 mb-3">
                            <label class="form-label">Banka Hesabı (IBAN) <span class="text-danger">*</span></label>
                            <input type="text" name="iban" class="form-control" placeholder="TR00 0000 0000 0000 0000 0000 00" required>
                            <small class="text-muted">Çekim yapılacak müşteri hesabı</small>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Hesap Sahibi Adı</label>
                            <input type="text" name="account_holder" class="form-control">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Banka Adı</label>
                            <input type="text" name="bank_name" class="form-control">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Aciklama</label>
                        <textarea name="description" class="form-control" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Notlar</label>
                        <textarea name="notes" class="form-control" rows="3"></textarea>
                    </div>
                    <div class="alert alert-info">
                        <i class="bi bi-info-circle me-2"></i>
                        Çekim işlemi oluşturulduğunda otomatik olarak seçilen finans grubuna atanacak ve <strong>Beklemede</strong> durumuna geçecektir.
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">İptal</button>
                    <button type="submit" class="btn btn-danger"><i class="bi bi-check-circle me-2"></i>Çekim Oluştur</button>
                </div>
            </form>
        </div>
    </div>
</div>

@endsection

@push('styles')
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.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;
    }
    .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>
$(document).ready(function() {
    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'));
    const forcedSiteId = @json($forcedSiteId ?? null);
    const transactionsIndexUrl = @json(!empty($isSiteScoped) && !empty($forcedSiteId) ? route('finance.sites.withdrawals.index', $forcedSiteId) : route('finance.withdrawals.index'));

    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;
    let statsRefreshTimer = null;

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

    function resolveSiteLabel(items) {
        if (!Array.isArray(items) || items.length === 0) {
            return 'Site';
        }
        const names = Array.from(new Set(
            items
                .map(function(item) { return String(item.site_name || '').trim(); })
                .filter(function(name) { return name && name !== '-'; })
        ));
        if (!names.length) {
            return 'Site';
        }
        if (names.length === 1) {
            return names[0];
        }
        return names[0] + ' +' + (names.length - 1);
    }

    // Check for new withdrawals
    function checkNewWithdrawals() {
        $.ajax({
            url: '{{ route("finance.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();
                    const siteLabel = resolveSiteLabel(response.data || []);

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

                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() {
        // Check every 5 seconds
        pollingInterval = setInterval(checkNewWithdrawals, 5000);
    }

    // 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 (filters.date_from) {
            filters.date_from = normalizeDateTime(filters.date_from);
        }
        if (filters.date_to) {
            filters.date_to = normalizeDateTime(filters.date_to);
        }
        if (forcedSiteId) {
            filters.site_id = String(forcedSiteId);
        }
        return filters;
    }

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

    function refreshStats() {
        $.ajax({
            url: '{{ route("finance.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);
    }

    // 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';
                        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: 'site_name',
                    render: function(data) {
                        return data || '-';
                    }
                },
                {
                    data: 'customer_account_holder',
                    render: function(data, type, row) {
                        if (data) {
                            return data;
                        }
                        return row.bank_account ? row.bank_account : (row.customer_name || '-');
                    }
                },
                {
                    data: null,
                    render: function(data) {
                        let amount = parseFloat(data.amount.replace(',', '')).toLocaleString('tr-TR', {minimumFractionDigits: 2, maximumFractionDigits: 2});
                        return '<span class="fw-bold text-danger">-' + amount + ' ' + data.currency + '</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>';

                        if (data.status === 'pending') {
                            const rawAmount = (data.amount || '').toString().replace(',', '');
                            const parsedAmount = parseFloat(rawAmount);
                            const amountLabel = isNaN(parsedAmount)
                                ? (data.amount ? (data.amount + ' ' + (data.currency || '')) : '')
                                : parsedAmount.toLocaleString('tr-TR', {minimumFractionDigits: 2, maximumFractionDigits: 2}) + ' ' + (data.currency || '');
                            buttons += '<button class="btn btn-outline-success btn-approve" data-id="' + data.id + '" data-amount-label="' + amountLabel + '" 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: [[6, 'desc']],
            pageLength: 25,
            language: {
                url: '//cdn.datatables.net/plug-ins/1.13.6/i18n/tr.json'
            }
        });
    }

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

    // Start polling for new withdrawals
    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("finance.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">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">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 || '-'}</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">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);
            }
        });
    });

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

        Swal.fire({
            title: 'İşlemi Onayla',
            text: 'Bu işlemi onaylamak istediğinizden emin misiniz?',
            footer: amountLabel ? 'Tutar: ' + amountLabel : '',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Evet, Onayla',
            cancelButtonText: 'İptal',
            confirmButtonColor: '#28a745'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '{{ route("finance.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("finance.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');
            }
        });
    });

    // Number formatting function
    function formatNumber(input) {
        let value = input.value.replace(/[^\d]/g, '');
        if (value) {
            input.value = parseInt(value).toLocaleString('tr-TR');
        }
    }

    // Amount input formatting
    $('#withdrawalAmount').on('input', function() {
        formatNumber(this);
    });

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

        const amount = $('#withdrawalAmount').val().replace(/\./g, '').replace(',', '.');
        let formData = $(this).serialize();
        formData = formData.replace(/amount=[^&]*/, 'amount=' + amount);
        formData += '&_token={{ csrf_token() }}';

        $.ajax({
            url: '{{ route("finance.withdrawals.store") }}',
            method: 'POST',
            data: formData,
            success: function(response) {
                $('#createWithdrawalModal').modal('hide');
                $('#createWithdrawalForm')[0].reset();
                Swal.fire({
                    title: 'Başarılı!',
                    html: response.message + '<br><br><small>İşlem ID: <code>' + response.transaction.transaction_id + '</code></small>',
                    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('Doğrulama Hatası!', errorMsg, 'error');
                } else {
                    Swal.fire('Hata!', xhr.responseJSON?.message || 'Bir hata oluştu', 'error');
                }
            }
        });
    });
});
</script>
@endpush

