@extends('backoffice.layouts.app')

@section('title', 'İşlemler')

@section('content')
<div class="container-fluid">
    <!-- Page Header -->
    <div class="row mb-4">
        <div class="col-12">
            <h2 class="mb-1">
                <i class="bi bi-arrow-left-right me-2"></i>
                İşlemler
            </h2>
            <p class="text-muted">Tüm yatırım ve çekim işlemlerini görüntüleyin ve yönetin</p>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="row g-3 mb-4">
        <div class="col-md-2">
            <div class="card border-0 shadow-sm">
                <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">
                <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">
                <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">
                <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">
                <div class="row g-3">
                    <div class="col-md-2">
                        <label class="form-label small">İşlem Tipi</label>
                        <select name="type" class="form-select form-select-sm">
                            <option value="">Tümü</option>
                            <option value="deposit">Yatırım</option>
                            <option value="withdrawal">Çekim</option>
                        </select>
                    </div>
                    <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>
                    <div class="col-md-2">
                        <label class="form-label small">Başlangıç Tarihi</label>
                        <input type="date" name="date_from" class="form-control form-control-sm">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label small">Bitiş Tarihi</label>
                        <input type="date" name="date_to" class="form-control form-control-sm">
                    </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, 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="120">İşlem ID</th>
                            <th width="80">Tip</th>
                            <th>Müşteri</th>
                            <th width="120">Tutar</th>
                            <th>Finans Grubu</th>
                            <th>Banka Hesabı</th>
                            <th width="100">Durum</th>
                            <th width="120">Tarih</th>
                            <th width="120" class="text-center">İşlemler</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Data will be loaded via AJAX -->
                    </tbody>
                </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">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>

@endsection

@push('scripts')
<script>
$(document).ready(function() {
    let table;

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

        table = $('#transactionsTable').DataTable({
            processing: true,
            serverSide: false,
            ajax: {
                url: '{{ route("backoffice.transactions.index") }}',
                data: filters
            },
            columns: [
                {
                    data: 'transaction_id',
                    render: function(data) {
                        return '<code class="small">' + data + '</code>';
                    }
                },
                {
                    data: 'type',
                    render: function(data) {
                        if (data === 'deposit') {
                            return '<span class="badge bg-success"><i class="bi bi-arrow-down"></i> Yatırım</span>';
                        } else {
                            return '<span class="badge bg-danger"><i class="bi bi-arrow-up"></i> Çekim</span>';
                        }
                    }
                },
                { data: 'customer_name' },
                {
                    data: null,
                    render: function(data) {
                        let colorClass = data.type === 'deposit' ? 'text-success' : 'text-danger';
                        let prefix = data.type === 'deposit' ? '+' : '-';
                        return '<span class="fw-bold ' + colorClass + '">' + prefix + data.amount + ' ' + data.currency + '</span>';
                    }
                },
                {
                    data: 'finance_group',
                    render: function(data) {
                        return data !== '-' ? '<span class="badge bg-info">' + data + '</span>' : '<span class="text-muted">-</span>';
                    }
                },
                {
                    data: 'bank_account',
                    render: function(data) {
                        return data !== '-' ? data : '<span class="text-muted">-</span>';
                    }
                },
                {
                    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="badge bg-' + config.class + '">' + config.label + '</span>';
                    }
                },
                { data: 'created_at' },
                {
                    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') {
                            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: [[7, 'desc']],
            pageLength: 25,
            language: {
                url: '//cdn.datatables.net/plug-ins/1.13.6/i18n/tr.json'
            }
        });
    }

    // Initialize table
    initTable();

    // Filter form submit
    $('#filterForm').on('submit', function(e) {
        e.preventDefault();
        const filters = $(this).serialize();
        initTable(filters);
    });

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

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

        $.ajax({
            url: '{{ route("backoffice.transactions.show", ":id") }}'.replace(':id', id),
            success: function(response) {
                const t = response.transaction;
                let html = `
                    <div class="row g-3">
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">İşlem ID</p>
                            <p class="fw-semibold"><code>${t.transaction_id}</code></p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">Dış İşlem ID</p>
                            <p class="fw-semibold">${t.external_transaction_id || '-'}</p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">İşlem Tipi</p>
                            <p class="fw-semibold">${t.type === 'deposit' ? '<span class="badge bg-success">Yatırım</span>' : '<span class="badge bg-danger">Çekim</span>'}</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' : 'Onaylandı'}</span></p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">Tutar</p>
                            <p class="fw-semibold fs-5 ${t.type === 'deposit' ? 'text-success' : 'text-danger'}">${t.type === 'deposit' ? '+' : '-'}${parseFloat(t.amount).toFixed(2)} ${t.currency}</p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">Müşteri Adı</p>
                            <p class="fw-semibold">${t.customer_name} ${t.customer_surname || ''}</p>
                        </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">Banka</p>
                            <p class="fw-semibold">${t.bank_account ? t.bank_account.bank_name : (t.customer_bank_name || '-')}</p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">Finans Grubu</p>
                            <p class="fw-semibold">${t.finance_group ? t.finance_group.name : '-'}</p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1 small text-muted">Banka Hesabı</p>
                            <p class="fw-semibold">${t.bank_account ? `${t.bank_account.account_name} (${t.bank_account.bank_name} - ${t.bank_account.iban})` : '-'}</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-md-6">
                            <p class="mb-1 small text-muted">Onaylayan</p>
                            <p class="fw-semibold">${t.approved_by ? t.approved_by.full_name : '-'}</p>
                        </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.transactions.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();
                    },
                    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');
    });

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

        $.ajax({
            url: '{{ route("backoffice.transactions.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();
                $('#declineForm')[0].reset();
            },
            error: function(xhr) {
                Swal.fire('Hata!', xhr.responseJSON.message, 'error');
            }
        });
    });

});
</script>
@endpush
