@extends('adminlte::page')

@section('content')
<h3>Select Accounts to View Ledger</h3>
<form method="POST" action="{{ route('admin.ledger.generate') }}">
    @csrf

    <div class="row">
        @foreach ($accounts->chunk(ceil($accounts->count() / 3)) as $accountChunk)
            <div class="col-md-4">
                @foreach ($accountChunk as $account)
                    <div style="margin-left: {{ $account->level * 15 }}px;">
                        @if ($account->is_posting)
                            <input
                                type="checkbox"
                                name="accounts[]"
                                value="{{ $account->id }}"
                                id="acc{{ $account->id }}"
                                data-parent="{{ $account->parent_id }}"
                                class="account-checkbox"
                            >
                            <label for="acc{{ $account->id }}">
                                {{ $account->code }} - {{ $account->name }}
                            </label>
                        @else
                            <strong>{{ $account->code }} - {{ $account->name }}</strong>
                        @endif
                    </div>
                @endforeach
            </div>
        @endforeach
    </div>

    <button type="submit" class="btn btn-primary mt-4">Generate Ledger</button>
</form>
@endsection

@section('js')
<script>
    document.addEventListener('DOMContentLoaded', function () {
        const checkboxes = document.querySelectorAll('.account-checkbox');

        checkboxes.forEach(checkbox => {
            checkbox.addEventListener('change', function () {
                const id = this.value;
                const isChecked = this.checked;

                document.querySelectorAll(`.account-checkbox[data-parent="${id}"]`)
                    .forEach(child => {
                        child.checked = isChecked;
                        child.dispatchEvent(new Event('change'));
                    });
            });
        });
    });
</script>
@endsection
