@extends('backoffice.layouts.app')

@section('title', 'Yatırımlar')

@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-down-circle text-success me-2"></i>
                        Yatırımlar
                    </h2>
                    <p class="text-muted">Tüm yatırım işlemlerini görüntüleyin ve yönetin</p>
                </div>
                @if(can_access('deposits', 'create'))
                <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#createDepositModal">
                    <i class="bi bi-plus-circle me-2"></i>Yeni Yatırım Oluştur
                </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 class="dash-quick-range mt-2">
                            <button type="button" onclick="setDateRange('yesterday')">Dun</button>
                            <span class="text-muted mx-1">|</span>
                            <button type="button" onclick="setDateRange('today')">Bugun</button>
                            <span class="text-muted mx-1">|</span>
                            <button type="button" onclick="setDateRange('week')">Bu Hafta</button>
                            <span class="text-muted mx-1">|</span>
                            <button type="button" onclick="setDateRange('month')">Bu Ay</button>
                        </div>
                    </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">Yatırım 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, Üye ID, 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>Müşteri</th>
                            <th width="120">Tutar</th>
                            <th width="130">Odeme Tipi</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-success fw-bold">0,00 TRY</th>
                            <th colspan="7"></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 Deposit Modal -->
<div class="modal fade" id="createDepositModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title"><i class="bi bi-plus-circle me-2"></i>Yeni Manuel Yatirim Olustur</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form id="createDepositForm">
                <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="depositSiteId" 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="depositSiteId" 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="depositFinanceGroup" 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">Uye ID <span class="text-danger">*</span></label>
                            <input type="text" name="customer_player_id" id="depositCustomerPlayerId" class="form-control" required>
                        </div>
                    </div>
                    <div class="row">
                        <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="depositCustomerName" 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="depositAmount" class="form-control number-input" required>
                            <small class="text-muted">Orn: 10.000</small>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Aciklama</label>
                        <textarea name="description" class="form-control" rows="3"></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-success"><i class="bi bi-check-circle me-2"></i>Yatirim 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;
    }
    .dash-quick-range {
        font-size: 0.85rem;
        white-space: nowrap;
    }
    .dash-quick-range button {
        border: 0;
        background: transparent;
        color: #0d6efd;
        padding: 0;
    }
    .dash-quick-range button:hover {
        text-decoration: underline;
    }
</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 canUpdateDeposits = {!! can_access('deposits', '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.deposits.index', $forcedSiteId) : route('backoffice.deposits.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);
    });

    window.setDateRange = function(range) {
        const now = new Date();
        const mode = $dateMode.val() || 'gaming';
        const useActual = mode === 'actual';
        let startDate = new Date(now);
        let endDate = new Date(now);

        if (useActual) {
            if (range === 'today') {
                startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
                endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 999);
            } else if (range === 'yesterday') {
                startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1, 0, 0, 0, 0);
                endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1, 23, 59, 59, 999);
            } else if (range === 'week') {
                startDate = new Date(now);
                startDate.setDate(now.getDate() - 7);
                startDate.setHours(0, 0, 0, 0);
                endDate = new Date(now);
            } else if (range === 'month') {
                startDate = new Date(now);
                startDate.setMonth(now.getMonth() - 1);
                startDate.setHours(0, 0, 0, 0);
                endDate = new Date(now);
            }
        } else {
            if (range === 'today') {
                startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 6, 0, 0, 0);
                if (now.getHours() < 6) {
                    startDate.setDate(startDate.getDate() - 1);
                }
                endDate = new Date(now);
            } else if (range === 'yesterday') {
                const businessStart = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 6, 0, 0, 0);
                if (now.getHours() < 6) {
                    businessStart.setDate(businessStart.getDate() - 1);
                }
                endDate = new Date(businessStart);
                endDate.setMilliseconds(endDate.getMilliseconds() - 1);
                startDate = new Date(businessStart);
                startDate.setDate(startDate.getDate() - 1);
            } else if (range === 'week') {
                startDate = new Date(now);
                startDate.setDate(now.getDate() - 7);
                startDate.setHours(6, 0, 0, 0);
                endDate = new Date(now);
            } else if (range === 'month') {
                startDate = new Date(now);
                startDate.setMonth(now.getMonth() - 1);
                startDate.setHours(6, 0, 0, 0);
                endDate = new Date(now);
            }
        }

        if (datePickers[0]) {
            datePickers[0].setDate(startDate, true);
        }
        if (datePickers[1]) {
            datePickers[1].setDate(endDate, true);
        }

        $('#filterForm').trigger('submit');
    };

    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/deposit.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 deposits
    function checkNewDeposits() {
        $.ajax({
            url: '{{ route("backoffice.deposits.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 Yatırım!',
                        html: `<strong>${response.count}</strong> yeni yatırım işlemi alındı.`,
                        icon: 'info'
                    });
                }

                if (response.updated_count > 0) {
                    table.ajax.reload(null, false);
                    refreshStats();
                }
            },
            error: function(xhr) {
                console.error('Error checking for new deposits:', 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.deposits.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_name',
                    render: function(data, type, row) {
                        const customerName = data || '-';
                        if (type === 'display') {
                            return customerName;
                        }
                        if (type !== 'filter') {
                            return customerName;
                        }
                        const playerId = row.customer_player_id || '';
                        return (customerName + ' ' + playerId).trim();
                    }
                },
                {
                    data: null,
                    render: function(data, type) {
                        const currency = data.currency || '';
                        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);
                        }
                        const hasChange = data.amount_changed_from !== null && data.amount_changed_from !== undefined && data.amount_changed_at;
                        if (!hasChange) {
                            return '<span class="fw-bold text-success">' + amountLabel + ' ' + currency + '</span>';
                        }

                        const oldLabel = Number(data.amount_changed_from || 0).toLocaleString('tr-TR', {minimumFractionDigits: 2, maximumFractionDigits: 2});
                        const changeMeta = '<div class="small text-muted mt-1"><i class="bi bi-pencil-square me-1"></i>' +
                            (data.amount_changed_by_name || '-') +
                            (data.amount_changed_at ? ' - ' + new Date(data.amount_changed_at).toLocaleString('tr-TR') : '') +
                            '</div>';
                        return '<div class="text-muted"><s>' + oldLabel + ' ' + currency + '</s></div>' +
                            '<div class="fw-bold text-success">' + amountLabel + ' ' + currency + '</div>' +
                            changeMeta;
                    }
                },
                {
                    data: 'payment_label',
                    render: function(data, type, row) {
                        const isCrypto = row.payment_method === 'crypto' || row.is_crypto;
                        const label = isCrypto ? 'Kripto' : 'Banka';
                        const badgeClass = isCrypto ? 'bg-warning text-dark' : 'bg-primary';
                        if (type === 'export') {
                            const coin = row.crypto_coin_name || '';
                            const address = row.crypto_address || '';
                            return isCrypto ? ('Kripto ' + coin + ' ' + address).trim() : 'Banka';
                        }
                        const cryptoMeta = isCrypto
                            ? '<div class="small text-muted mt-1">' +
                                (row.crypto_coin_name ? row.crypto_coin_name : '-') +
                                (row.crypto_address ? '<br><span class="text-break">' + row.crypto_address + '</span>' : '') +
                              '</div>'
                            : '';
                        return '<span class="badge ' + badgeClass + '">' + label + '</span>' + cryptoMeta;
                    }
                },
                {
                    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) {
                        if (row.payment_method === 'crypto' || row.is_crypto) {
                            return '<span class="text-muted">-</span>';
                        }
                        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' && canUpdateDeposits) {
                            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: [[9, '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-success 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: 'Yatirim Listesi',
                        filename: function() {
                            return buildExportFilename('yatirimlar_');
                        },
                        exportOptions: {
                            columns: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
                            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 deposits
    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.deposits.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>`;
                const bankAccountLabel = t.bank_account ? (t.bank_account.account_name + ' (' + t.bank_account.bank_name + ' - ' + t.bank_account.iban + ')') : '-';
                const isCrypto = t.payment_method === 'crypto' || !!t.is_crypto;
                const paymentMethodLabel = isCrypto ? 'Kripto' : 'Banka';
                const paymentMethodBadge = isCrypto
                    ? '<span class="badge bg-warning text-dark">Kripto</span>'
                    : '<span class="badge bg-primary">Banka</span>';
                const amountChanged = t.amount_changed_from !== null && t.amount_changed_at;
                const newAmountLabel = Number(t.amount || 0).toLocaleString('tr-TR', {minimumFractionDigits: 2, maximumFractionDigits: 2});
                const oldAmountLabel = amountChanged ? Number(t.amount_changed_from || 0).toLocaleString('tr-TR', {minimumFractionDigits: 2, maximumFractionDigits: 2}) : '';
                const amountMeta = amountChanged
                    ? `<div class="small text-muted mt-1"><i class="bi bi-pencil-square me-1"></i>${t.amount_changed_by_name || '-'}${t.amount_changed_at ? ' - ' + new Date(t.amount_changed_at).toLocaleString('tr-TR') : ''}</div>`
                    : '';
                const amountHtml = amountChanged
                    ? `<div class="text-muted"><s>${oldAmountLabel} ${t.currency}</s></div><div class="fw-semibold fs-5 text-success">${newAmountLabel} ${t.currency}</div>${amountMeta}`
                    : `<p class="fw-semibold fs-5 text-success">${newAmountLabel} ${t.currency}</p>`;
                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"><span class="badge bg-success">Yatırım</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">Odeme Yontemi</p>
                            <p class="fw-semibold">${paymentMethodBadge} <span class="ms-1">${paymentMethodLabel}</span></p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">Tutar</p>
                            ${amountHtml}
                        </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>
                        ${isCrypto ? `
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">Kripto Coin</p>
                            <p class="fw-semibold">${t.crypto_coin_name || '-'}</p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">Kripto Adres</p>
                            <p class="fw-semibold text-break">${t.crypto_address || '-'}</p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">Kripto Hesap ID</p>
                            <p class="fw-semibold">${t.crypto_account_id || '-'}</p>
                        </div>
                        ` : ''}
                        ${isCrypto ? '' : `
                        <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 || '-'}</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">Banka Hesabi</p>
                            <p class="fw-semibold">${isCrypto ? '-' : bankAccountLabel}</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');

        Swal.fire({
            title: 'İşlemi Onayla',
            text: 'Bu işlemi onaylamak istediğinizden emin misiniz?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Evet, Onayla',
            cancelButtonText: 'İptal',
            confirmButtonColor: '#28a745'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '{{ route("backoffice.deposits.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.deposits.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 deposit form submission
    $('#createDepositForm').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 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(),
            description: $(this).find('[name=\"description\"]').val(),
            _token: '{{ csrf_token() }}'
        };

        if (!formData.site_id || !formData.finance_group_id || !formData.customer_player_id || !formData.customer_name) {
            Swal.fire('Hata!', 'Lutfen site, finans grubu, uye ID ve uye adi soyadi girin.', 'error');
            $submitBtn.data('submitting', false).prop('disabled', false);
            return;
        }

        $.ajax({
            url: '{{ route("backoffice.deposits.store") }}',
            method: 'POST',
            data: formData,
            success: function(response) {
                $('#createDepositModal').modal('hide');
                $('#createDepositForm')[0].reset();
                $('#depositCustomerPlayerId').val('');
                $('#depositCustomerName').val('');
                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');
                }
            },
            complete: function() {
                $submitBtn.data('submitting', false).prop('disabled', false);
            }
        });
    });
});
</script>
@endpush





