@extends('backoffice.layouts.app')

@section('title', 'Banka HesaplarÄ±')

@section('content')
<div class="container-fluid">
    <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-bank me-2"></i>Banka Hesapları</h2>
                    <p class="text-muted">Finans gruplarına ait banka hesaplarını yönetin</p>
                </div>
                @if(can_access('bank_accounts', 'create'))
                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createAccountModal">
                    <i class="bi bi-plus-circle me-2"></i>Yeni Hesap Ekle
                </button>
                @endif
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="card border-0 shadow-sm mb-4">
        <div class="card-body">
            <form id="filterForm" class="row g-3">
                <div class="col-md-8">
                    <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-4">
                    <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>
            </form>
        </div>
    </div>

    <!-- Table -->
    <div class="card border-0 shadow-sm">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table id="accountsTable" class="table table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>Hesap AdÄ±</th>
                            <th>Banka</th>
                            <th>Hesap Sahibi</th>
                            <th>IBAN</th>
                            <th>Finans Grubu</th>
                            <th>Durum</th>
                            <th width="150" class="text-center">Ä°ÅŸlemler</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Create Modal -->
<div class="modal fade" id="createAccountModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-plus-circle me-2"></i>Yeni Banka HesabÄ±</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="createAccountForm">
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Finans Grubu <span class="text-danger">*</span></label>
                            <select name="finance_group_id" class="form-select" required>
                                <option value="">SeÃ§iniz</option>
                                @foreach($financeGroups as $group)
                                    <option value="{{ $group->id }}">{{ $group->name }} ({{ number_format($group->min_amount, 0) }}-{{ number_format($group->max_amount, 0) }} â‚º)</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Hesap AdÄ± <span class="text-danger">*</span></label>
                            <input type="text" name="account_name" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Banka AdÄ± <span class="text-danger">*</span></label>
                            <input type="text" name="bank_name" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Hesap Sahibi <span class="text-danger">*</span></label>
                            <input type="text" name="account_holder" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">IBAN <span class="text-danger">*</span></label>
                            <input type="text" name="iban" class="form-control" required maxlength="34">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Hesap NumarasÄ±</label>
                            <input type="text" name="account_number" class="form-control">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Åžube AdÄ±</label>
                            <input type="text" name="branch_name" class="form-control">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Åžube Kodu</label>
                            <input type="text" name="branch_code" class="form-control">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">GÃ¼nlÃ¼k Limit (â‚º)</label>
                            <input type="number" name="daily_limit" class="form-control" step="0.01" min="0">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label d-block">Durum</label>
                            <div class="form-check form-switch mt-2">
                                <input class="form-check-input" type="checkbox" name="is_active" checked>
                                <label class="form-check-label">Aktif</label>
                            </div>
                        </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-primary"><i class="bi bi-check-circle me-2"></i>OluÅŸtur</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Modal (similar structure) -->
<div class="modal fade" id="editAccountModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-pencil me-2"></i>HesabÄ± DÃ¼zenle</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="editAccountForm">
                <input type="hidden" id="editAccountId">
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Finans Grubu</label>
                            <select name="finance_group_id" id="editFinanceGroupId" class="form-select" required>
                                @foreach($financeGroups as $group)
                                    <option value="{{ $group->id }}">{{ $group->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Hesap AdÄ±</label>
                            <input type="text" name="account_name" id="editAccountName" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Banka AdÄ±</label>
                            <input type="text" name="bank_name" id="editBankName" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Hesap Sahibi</label>
                            <input type="text" name="account_holder" id="editAccountHolder" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">IBAN</label>
                            <input type="text" name="iban" id="editIban" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Hesap NumarasÄ±</label>
                            <input type="text" name="account_number" id="editAccountNumber" class="form-control">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Åžube AdÄ±</label>
                            <input type="text" name="branch_name" id="editBranchName" class="form-control">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Åžube Kodu</label>
                            <input type="text" name="branch_code" id="editBranchCode" class="form-control">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">GÃ¼nlÃ¼k Limit (â‚º)</label>
                            <input type="number" name="daily_limit" id="editDailyLimit" class="form-control" step="0.01">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label d-block">Durum</label>
                            <div class="form-check form-switch mt-2">
                                <input class="form-check-input" type="checkbox" name="is_active" id="editIsActive">
                                <label class="form-check-label">Aktif</label>
                            </div>
                        </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-primary"><i class="bi bi-check-circle me-2"></i>GÃ¼ncelle</button>
                </div>
            </form>
        </div>
    </div>
</div>

@endsection

@push('styles')
<style>
    .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;
    }
</style>
@endpush

@push('scripts')
<script>
$(document).ready(function() {
    const canUpdateBankAccounts = {!! can_access('bank_accounts', 'update') ? 'true' : 'false' !!};
    const canDeleteBankAccounts = {!! can_access('bank_accounts', 'delete') ? 'true' : 'false' !!};
    let table;

    function getFilters() {
        const filters = {};
        const financeGroupId = $('select[name="finance_group_id"]').val();
        if (financeGroupId) {
            filters.finance_group_id = financeGroupId;
        }
        if ($('#activeOnly').is(':checked')) {
            filters.is_active = '1';
        }
        return filters;
    }

    function initTable() {
        if (table) {
            table.destroy();
        }
        table = $('#accountsTable').DataTable({
            processing: true,
            serverSide: false,
            ajax: {
                url: '{{ route("backoffice.bank-accounts.index") }}',
                data: function(d) {
                    return Object.assign(d, getFilters());
                }
            },
            columns: [
                { data: 'account_name' },
                { data: 'bank_name' },
                { data: 'account_holder' },
                { data: 'iban' },
                {
                    data: null,
                    render: function(data) {
                        const bg = data.finance_group_color || '#e2e8f0';
                        return '<span class="finance-group-badge" style="background:' + bg + ';">' + data.finance_group_name + '</span>';
                    }
                },
                {
                    data: 'is_active',
                    render: function(data) {
                        return data ? '<span class="status-pill bg-success">Aktif</span>' : '<span class="status-pill bg-danger">Pasif</span>';
                    }
                },
                {
                    data: null,
                    orderable: false,
                    render: function(data) {
                        let btns = '<div class="btn-group btn-group-sm">';
                        if (canUpdateBankAccounts) {
                            btns += '<button class="btn btn-outline-primary btn-edit" data-id="' + data.id + '"><i class="bi bi-pencil"></i></button>';
                            btns += '<button class="btn btn-outline-' + (data.is_active ? 'warning' : 'success') + ' btn-toggle" data-id="' + data.id + '"><i class="bi bi-' + (data.is_active ? 'pause' : 'play') + '-circle"></i></button>';
                        }
                        if (canDeleteBankAccounts) {
                            btns += '<button class="btn btn-outline-danger btn-delete" data-id="' + data.id + '"><i class="bi bi-trash"></i></button>';
                        }
                        return btns + '</div>';
                    }
                }
            ],
            order: [[0, 'asc']],
            pageLength: 25,
            language: { url: '//cdn.datatables.net/plug-ins/1.13.6/i18n/tr.json' }
        });
    }

    initTable();

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

    // Create
    $('#createAccountForm').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            url: '{{ route("backoffice.bank-accounts.store") }}',
            method: 'POST',
            data: $(this).serialize() + '&_token={{ csrf_token() }}',
            success: function(response) {
                $('#createAccountModal').modal('hide');
                $('#createAccountForm')[0].reset();
                Swal.fire('BaÅŸarÄ±lÄ±!', response.message, 'success');
                table.ajax.reload();
            },
            error: function(xhr) {
                Swal.fire('Hata!', xhr.responseJSON.message, 'error');
            }
        });
    });

    // Edit
    $(document).on('click', '.btn-edit', function() {
        const id = $(this).data('id');
        $.ajax({
            url: '{{ route("backoffice.bank-accounts.show", ":id") }}'.replace(':id', id),
            success: function(response) {
                const a = response.account;
                $('#editAccountId').val(a.id);
                $('#editFinanceGroupId').val(a.finance_group_id);
                $('#editAccountName').val(a.account_name);
                $('#editBankName').val(a.bank_name);
                $('#editAccountHolder').val(a.account_holder);
                $('#editIban').val(a.iban);
                $('#editAccountNumber').val(a.account_number);
                $('#editBranchName').val(a.branch_name);
                $('#editBranchCode').val(a.branch_code);
                $('#editDailyLimit').val(a.daily_limit);
                $('#editIsActive').prop('checked', a.is_active);
                $('#editAccountModal').modal('show');
            }
        });
    });

    $('#editAccountForm').on('submit', function(e) {
        e.preventDefault();
        const id = $('#editAccountId').val();
        $.ajax({
            url: '{{ route("backoffice.bank-accounts.update", ":id") }}'.replace(':id', id),
            method: 'POST',
            data: $(this).serialize() + '&_token={{ csrf_token() }}&_method=PUT',
            success: function(response) {
                $('#editAccountModal').modal('hide');
                Swal.fire('BaÅŸarÄ±lÄ±!', response.message, 'success');
                table.ajax.reload();
            },
            error: function(xhr) {
                Swal.fire('Hata!', xhr.responseJSON.message, 'error');
            }
        });
    });

    // Toggle
    $(document).on('click', '.btn-toggle', function() {
        const id = $(this).data('id');
        $.ajax({
            url: '{{ route("backoffice.bank-accounts.toggle-status", ":id") }}'.replace(':id', id),
            method: 'POST',
            data: { _token: '{{ csrf_token() }}' },
            success: function(response) {
                Swal.fire('BaÅŸarÄ±lÄ±!', response.message, 'success');
                table.ajax.reload();
            }
        });
    });

    // Delete
    $(document).on('click', '.btn-delete', function() {
        const id = $(this).data('id');
        Swal.fire({
            title: 'Emin misiniz?',
            text: 'Bu hesabÄ± silmek istediÄŸinizden emin misiniz?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Evet, Sil',
            cancelButtonText: 'Ä°ptal',
            confirmButtonColor: '#dc3545'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '{{ route("backoffice.bank-accounts.destroy", ":id") }}'.replace(':id', id),
                    method: 'POST',
                    data: { _token: '{{ csrf_token() }}', _method: 'DELETE' },
                    success: function(response) {
                        Swal.fire('BaÅŸarÄ±lÄ±!', response.message, 'success');
                        table.ajax.reload();
                    },
                    error: function(xhr) {
                        Swal.fire('Hata!', xhr.responseJSON.message, 'error');
                    }
                });
            }
        });
    });
});
</script>
@endpush

