@extends('finance.layouts.app')

@section('title', 'Banka Hesaplari')

@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 Hesaplari</h2>
                    <p class="text-muted">Finans grubuna ait banka hesaplarini yonetin</p>
                </div>
                <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>
            </div>
        </div>
    </div>

    <div class="card border-0 shadow-sm mb-3">
        <div class="card-body py-2">
            <ul class="nav nav-tabs card-header-tabs" id="accountTabs">
                <li class="nav-item">
                    <button class="nav-link active" type="button" data-tab="active">
                        <i class="bi bi-credit-card me-1"></i>Hesaplar
                        <span class="badge bg-secondary ms-1" id="activeAccountsCount">0</span>
                    </button>
                </li>
                <li class="nav-item">
                    <button class="nav-link" type="button" data-tab="blocked">
                        <i class="bi bi-slash-circle me-1"></i>Bloke Hesaplar
                        <span class="badge bg-danger ms-1" id="blockedAccountsCount">0</span>
                    </button>
                </li>
            </ul>
        </div>
    </div>

    <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>Banka Adi</th>
                            <th>Hesap Adi Soyadi</th>
                            <th>IBAN</th>
                            <th>Islem Sayisi</th>
                            <th>Min / Max</th>
                            <th>Durum</th>
                            <th width="150" class="text-center">Islemler</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<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 Hesabi</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="createAccountForm">
                <input type="hidden" name="finance_group_id" value="{{ $financeGroup->id }}">
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Banka Adi <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 Adi Soyadi <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">Aciklama</label>
                            <input type="text" name="description" class="form-control" placeholder="Aciklama">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Min Tutar (TL) <span class="text-danger">*</span></label>
                            <input type="text" name="min_amount" class="form-control number-input" inputmode="numeric" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Max Tutar (TL) <span class="text-danger">*</span></label>
                            <input type="text" name="max_amount" class="form-control number-input" inputmode="numeric" required>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Iptal</button>
                    <button type="submit" class="btn btn-primary"><i class="bi bi-check-circle me-2"></i>Olustur</button>
                </div>
            </form>
        </div>
    </div>
</div>

<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>Hesabi Duzenle</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="editAccountForm">
                <input type="hidden" id="editAccountId">
                <input type="hidden" name="finance_group_id" value="{{ $financeGroup->id }}">
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Banka Adi</label>
                            <input type="text" name="bank_name" id="editBankName" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Hesap Adi Soyadi</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">Aciklama</label>
                            <input type="text" name="description" id="editDescription" class="form-control" placeholder="Aciklama">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Min Tutar (TL)</label>
                            <input type="text" name="min_amount" id="editMinAmount" class="form-control number-input" inputmode="numeric" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Max Tutar (TL)</label>
                            <input type="text" name="max_amount" id="editMaxAmount" class="form-control number-input" inputmode="numeric" required>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Iptal</button>
                    <button type="submit" class="btn btn-primary"><i class="bi bi-check-circle me-2"></i>Guncelle</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="siteStatusesModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-globe2 me-2"></i>Site Bazli Durum</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="siteStatusesForm">
                <input type="hidden" id="siteStatusesAccountId">
                <div class="modal-body">
                    <div class="alert alert-info py-2 small">
                        Varsayilan secenegi, hesabin genel Aktif/Pasif durumunu kullanir.
                    </div>
                    <div id="siteStatusesAccountLabel" class="fw-semibold mb-2"></div>
                    <div class="table-responsive">
                        <table class="table table-sm table-bordered align-middle mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>Site</th>
                                    <th width="200">Durum</th>
                                </tr>
                            </thead>
                            <tbody id="siteStatusesRows">
                                <tr>
                                    <td colspan="2" class="text-center text-muted py-3">Yukleniyor...</td>
                                </tr>
                            </tbody>
                        </table>
                    </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-primary"><i class="bi bi-check-circle me-2"></i>Kaydet</button>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection

@push('styles')
<style>
    .status-pill {
        display: block;
        width: 100%;
        text-align: center;
        font-size: 0.9rem;
        font-weight: 600;
        padding: 6px 8px;
        border-radius: 8px;
        color: #fff;
    }
    .site-status-list {
        display: flex;
        flex-direction: column;
        gap: 4px;
        min-width: 180px;
    }
    .site-status-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 8px;
        padding: 4px 8px;
        border: 1px solid #e2e8f0;
        border-radius: 8px;
        background: #f8fafc;
    }
    .site-status-name {
        font-size: 0.82rem;
        font-weight: 600;
        color: #334155;
        max-width: 120px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    .site-status-badge {
        font-size: 0.75rem;
        font-weight: 700;
        padding: 3px 8px;
        border-radius: 999px;
        color: #fff;
        white-space: nowrap;
    }
    .site-status-badge.active {
        background: #198754;
    }
    .site-status-badge.passive {
        background: #dc3545;
    }
    .site-status-badge.default::before {
        content: "D ";
        font-weight: 800;
    }
    .site-toggle-wrap {
        display: inline-flex;
        align-items: center;
        gap: 10px;
    }
    .site-toggle-chip {
        min-width: 56px;
        text-align: center;
        font-size: 0.82rem;
        font-weight: 700;
        padding: 3px 10px;
        border-radius: 8px;
    }
    .site-toggle-chip.active {
        background: #c8e6d7;
        color: #0f5132;
    }
    .site-toggle-chip.passive {
        background: #e2e3e5;
        color: #495057;
    }
    .site-toggle-control {
        position: relative;
        display: inline-block;
        width: 54px;
        height: 30px;
        margin: 0;
    }
    .site-toggle-control input {
        opacity: 0;
        width: 0;
        height: 0;
    }
    .site-toggle-slider {
        position: absolute;
        cursor: pointer;
        inset: 0;
        background-color: #c0c4c9;
        transition: .2s;
        border-radius: 999px;
    }
    .site-toggle-slider:before {
        content: "";
        position: absolute;
        height: 22px;
        width: 22px;
        left: 4px;
        top: 4px;
        background-color: #fff;
        transition: .2s;
        border-radius: 50%;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
    }
    .site-toggle-control input:checked + .site-toggle-slider {
        background-color: #198754;
    }
    .site-toggle-control input:checked + .site-toggle-slider:before {
        transform: translateX(24px);
    }
</style>
@endpush

@push('scripts')
<script>
$(document).ready(function() {
    let table;
    let currentTab = 'active';
    const forcedSiteId = @json($forcedSiteId ?? null);
    const bankAccountsIndexUrl = @json(!empty($isSiteScoped) && !empty($forcedSiteId) ? route('finance.sites.bank-accounts.index', $forcedSiteId) : route('finance.bank-accounts.index'));

    function escapeHtml(value) {
        return String(value ?? '')
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;');
    }

    function initTable() {
        if (table) table.destroy();
        table = $('#accountsTable').DataTable({
            processing: true,
            serverSide: false,
            ajax: {
                url: bankAccountsIndexUrl,
                data: function(d) {
                    d.blocked = currentTab === 'blocked' ? 1 : 0;
                    d.site_id = forcedSiteId || '';
                },
                dataSrc: function(json) {
                    const counts = (json && json.counts) ? json.counts : {};
                    $('#activeAccountsCount').text(Number(counts.active || 0));
                    $('#blockedAccountsCount').text(Number(counts.blocked || 0));
                    return (json && Array.isArray(json.data)) ? json.data : [];
                }
            },
            columns: [
                { data: 'bank_name' },
                { data: 'account_holder' },
                { data: 'iban' },
                { data: 'transactions_count' },
                {
                    data: null,
                    render: function(data) {
                        const minAmount = formatNumber(data.min_amount, 0);
                        const maxAmount = formatNumber(data.max_amount, 0);
                        return minAmount + ' - ' + maxAmount + ' TL';
                    }
                },
                {
                    data: 'site_statuses',
                    render: function(data, type, row) {
                        if (row && row.is_blocked) {
                            if (type !== 'display') {
                                return 'bloke pasif';
                            }
                            return '<span class="badge bg-danger"><i class="bi bi-slash-circle me-1"></i>Bloke (Pasif)</span>';
                        }

                        const statuses = Array.isArray(data) ? data : [];
                        if (type !== 'display') {
                            return statuses.map(function(item) {
                                return (item.site_name || '') + ' ' + (item.is_active ? 'aktif' : 'pasif');
                            }).join(' ');
                        }
                        if (!statuses.length) {
                            return '<span class="text-muted">-</span>';
                        }

                        const html = statuses.map(function(item) {
                            const name = escapeHtml(item.site_name || '-');
                            const stateClass = item.is_active ? 'active' : 'passive';
                            const stateLabel = item.is_active ? 'Aktif' : 'Pasif';
                            const sourceClass = item.source === 'override' ? '' : ' default';
                            const sitePassive = item.site_is_active ? '' : ' <i class="bi bi-moon-stars-fill text-secondary" title="Pasif Site"></i>';
                            return '' +
                                '<div class="site-status-item">' +
                                    '<span class="site-status-name" title="' + name + '">' + name + sitePassive + '</span>' +
                                    '<span class="site-status-badge ' + stateClass + sourceClass + '">' + stateLabel + '</span>' +
                                '</div>';
                        }).join('');

                        return '<div class="site-status-list">' + html + '</div>';
                    }
                },
                {
                    data: null,
                    orderable: false,
                    render: function(data) {
                        let btns = '<div class="btn-group btn-group-sm">';
                        btns += '<button class="btn btn-outline-primary btn-edit" data-id="' + data.id + '"><i class="bi bi-pencil"></i></button>';
                        if (!data.is_blocked) {
                            btns += '<button class="btn btn-outline-info btn-site-statuses" data-id="' + data.id + '" title="Site Bazli Durum"><i class="bi bi-globe2"></i></button>';
                            btns += '<button class="btn btn-outline-warning btn-block-account" data-id="' + data.id + '" title="Hesabi Bloke Et"><i class="bi bi-slash-circle"></i></button>';
                        }
                        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();

    $('#accountTabs .nav-link').on('click', function() {
        const selected = String($(this).data('tab') || 'active');
        if (selected === currentTab) {
            return;
        }
        currentTab = selected;
        $('#accountTabs .nav-link').removeClass('active');
        $(this).addClass('active');
        table.ajax.reload();
    });

    $('#createAccountForm').on('submit', function(e) {
        e.preventDefault();
        const minAmount = parseFormattedNumber($(this).find('[name="min_amount"]').val());
        const maxAmount = parseFormattedNumber($(this).find('[name="max_amount"]').val());
        let formData = $(this).serializeArray().filter(function(item) {
            return item.name !== 'min_amount' && item.name !== 'max_amount';
        });
        formData.push({ name: 'min_amount', value: minAmount });
        formData.push({ name: 'max_amount', value: maxAmount });
        formData.push({ name: '_token', value: '{{ csrf_token() }}' });

        $.ajax({
            url: '{{ route("finance.bank-accounts.store") }}',
            method: 'POST',
            data: $.param(formData),
            success: function(response) {
                $('#createAccountModal').modal('hide');
                $('#createAccountForm')[0].reset();
                Swal.fire('Basarili!', response.message, 'success');
                table.ajax.reload(null, false);
            },
            error: function(xhr) {
                Swal.fire('Hata!', xhr.responseJSON?.message || 'Bir hata olustu', 'error');
            }
        });
    });

    $(document).on('click', '.btn-edit', function() {
        const id = $(this).data('id');
        $.ajax({
            url: '{{ route("finance.bank-accounts.show", ":id") }}'.replace(':id', id),
            success: function(response) {
                const a = response.account;
                $('#editAccountId').val(a.id);
                $('#editBankName').val(a.bank_name);
                $('#editAccountHolder').val(a.account_holder);
                $('#editIban').val(a.iban);
                $('#editDescription').val(a.description || '');
                $('#editMinAmount').val(formatNumber(a.min_amount, 0));
                $('#editMaxAmount').val(formatNumber(a.max_amount, 0));
                $('#editAccountModal').modal('show');
            }
        });
    });

    $('#editAccountForm').on('submit', function(e) {
        e.preventDefault();
        const id = $('#editAccountId').val();
        const minAmount = parseFormattedNumber($(this).find('[name="min_amount"]').val());
        const maxAmount = parseFormattedNumber($(this).find('[name="max_amount"]').val());
        let formData = $(this).serializeArray().filter(function(item) {
            return item.name !== 'min_amount' && item.name !== 'max_amount';
        });
        formData.push({ name: 'min_amount', value: minAmount });
        formData.push({ name: 'max_amount', value: maxAmount });
        formData.push({ name: '_token', value: '{{ csrf_token() }}' });
        formData.push({ name: '_method', value: 'PUT' });

        $.ajax({
            url: '{{ route("finance.bank-accounts.update", ":id") }}'.replace(':id', id),
            method: 'POST',
            data: $.param(formData),
            success: function(response) {
                $('#editAccountModal').modal('hide');
                Swal.fire('Basarili!', response.message, 'success');
                table.ajax.reload(null, false);
            },
            error: function(xhr) {
                Swal.fire('Hata!', xhr.responseJSON?.message || 'Bir hata olustu', 'error');
            }
        });
    });

    $(document).on('click', '.btn-block-account', function() {
        const id = $(this).data('id');
        Swal.fire({
            title: 'Hesap Bloke Edilsin mi?',
            text: 'Bu hesap bloke edilince pasife alinacak ve tekrar aktif edilemeyecek.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Evet, Bloke Et',
            cancelButtonText: 'Iptal',
            confirmButtonColor: '#dc3545'
        }).then((result) => {
            if (!result.isConfirmed) {
                return;
            }

            $.ajax({
                url: '{{ route("finance.bank-accounts.block", ":id") }}'.replace(':id', id),
                method: 'POST',
                data: { _token: '{{ csrf_token() }}' },
                success: function(response) {
                    Swal.fire('Basarili!', response.message, 'success');
                    table.ajax.reload(null, false);
                },
                error: function(xhr) {
                    Swal.fire('Hata!', xhr.responseJSON?.message || 'Bir hata olustu', 'error');
                }
            });
        });
    });

    $(document).on('click', '.btn-site-statuses', function() {
        const id = $(this).data('id');
        $('#siteStatusesAccountId').val(id);
        $('#siteStatusesRows').html('<tr><td colspan="2" class="text-center text-muted py-3">Yukleniyor...</td></tr>');
        $('#siteStatusesAccountLabel').text('');
        $('#siteStatusesModal').modal('show');

        $.ajax({
            url: '{{ route("finance.bank-accounts.site-statuses", ":id") }}'.replace(':id', id),
            method: 'GET',
            success: function(response) {
                const account = response.account || {};
                $('#siteStatusesAccountLabel').text((account.bank_name || '-') + ' - ' + (account.account_holder || '-') + ' (' + (account.iban || '-') + ')');

                const sites = response.sites || [];
                if (!sites.length) {
                    $('#siteStatusesRows').html('<tr><td colspan="2" class="text-center text-muted py-3">Site bulunmuyor.</td></tr>');
                    return;
                }

                const rows = sites.map(function(site) {
                    const selected = site.override_status || 'default';
                    const effectiveActive = selected === 'default'
                        ? !!account.default_is_active
                        : selected === 'active';
                    const siteName = escapeHtml(site.name || '-');
                    const passiveBadge = site.is_active ? '' : ' <span class="badge bg-secondary">Pasif Site</span>';
                    return '' +
                        '<tr>' +
                            '<td>' + siteName + passiveBadge + '</td>' +
                            '<td>' +
                                '<div class="site-toggle-wrap">' +
                                    '<span class="site-toggle-chip ' + (effectiveActive ? 'active' : 'passive') + '" data-status-chip>' + (effectiveActive ? 'Aktif' : 'Pasif') + '</span>' +
                                    '<label class="site-toggle-control">' +
                                        '<input type="checkbox" class="site-status-toggle" data-site-id="' + site.id + '"' + (effectiveActive ? ' checked' : '') + '>' +
                                        '<span class="site-toggle-slider"></span>' +
                                    '</label>' +
                                    '<input type="hidden" name="statuses[' + site.id + ']" value="' + selected + '" class="site-status-hidden">' +
                                '</div>' +
                            '</td>' +
                        '</tr>';
                }).join('');

                $('#siteStatusesRows').html(rows);

                $('#siteStatusesRows .site-status-toggle')
                    .off('change.siteStatusToggle')
                    .on('change.siteStatusToggle', function() {
                        const $toggle = $(this);
                        const isActive = $toggle.is(':checked');
                        const statusValue = isActive ? 'active' : 'passive';
                        const $wrapper = $toggle.closest('.site-toggle-wrap');
                        $wrapper.find('.site-status-hidden').val(statusValue);

                        const $chip = $wrapper.find('[data-status-chip]');
                        $chip
                            .removeClass('active passive')
                            .addClass(isActive ? 'active' : 'passive')
                            .text(isActive ? 'Aktif' : 'Pasif');
                    });
            },
            error: function(xhr) {
                $('#siteStatusesRows').html('<tr><td colspan="2" class="text-center text-danger py-3">Yukleme hatasi.</td></tr>');
                Swal.fire('Hata!', xhr.responseJSON?.message || 'Bir hata olustu', 'error');
            }
        });
    });

    $('#siteStatusesForm').on('submit', function(e) {
        e.preventDefault();
        const id = $('#siteStatusesAccountId').val();
        const payload = $(this).serializeArray();
        payload.push({ name: '_token', value: '{{ csrf_token() }}' });

        $.ajax({
            url: '{{ route("finance.bank-accounts.site-statuses.update", ":id") }}'.replace(':id', id),
            method: 'POST',
            data: $.param(payload),
            success: function(response) {
                $('#siteStatusesModal').modal('hide');
                Swal.fire('Basarili!', response.message, 'success');
                table.ajax.reload(null, false);
            },
            error: function(xhr) {
                if (xhr.status === 422 && xhr.responseJSON?.errors) {
                    let errorMsg = '<ul class="text-start">';
                    Object.keys(xhr.responseJSON.errors).forEach(function(key) {
                        errorMsg += '<li>' + xhr.responseJSON.errors[key][0] + '</li>';
                    });
                    errorMsg += '</ul>';
                    Swal.fire('Dogrulama Hatasi!', errorMsg, 'error');
                } else {
                    Swal.fire('Hata!', xhr.responseJSON?.message || 'Bir hata olustu', 'error');
                }
            }
        });
    });

    $(document).on('click', '.btn-delete', function() {
        const id = $(this).data('id');
        Swal.fire({
            title: 'Emin misiniz?',
            text: 'Bu hesabi silmek istediginizden emin misiniz?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Evet, Sil',
            cancelButtonText: 'Iptal',
            confirmButtonColor: '#dc3545'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '{{ route("finance.bank-accounts.destroy", ":id") }}'.replace(':id', id),
                    method: 'POST',
                    data: { _token: '{{ csrf_token() }}', _method: 'DELETE' },
                    success: function(response) {
                        Swal.fire('Basarili!', response.message, 'success');
                        table.ajax.reload(null, false);
                    },
                    error: function(xhr) {
                        Swal.fire('Hata!', xhr.responseJSON?.message || 'Bir hata olustu', 'error');
                    }
                });
            }
        });
    });
});
</script>
@endpush
