@extends('layouts.app')
@section('title', 'New Journal Entry')
@section('page_title', 'New Journal Entry')
@section('breadcrumbs')
    <li class="breadcrumb-item"><a href="{{ route('journals.index') }}">Journals</a></li><li class="breadcrumb-item active">New</li>
@endsection

@section('content')
    <div class="card"><div class="card-body">
        <form method="POST" action="{{ route('journals.store') }}">
            @csrf
            @if($errors->any())<div class="alert alert-danger small">{{ $errors->first() }}</div>@endif
            <div class="row g-3 mb-3">
                <div class="col-md-3"><label class="form-label">Date</label>
                    <input type="date" name="date" value="{{ now()->format('Y-m-d') }}" class="form-control" required></div>
                <div class="col-md-6"><label class="form-label">Description</label>
                    <input type="text" name="description" class="form-control" required></div>
                <div class="col-md-3"><label class="form-label">Reference</label>
                    <input type="text" name="reference" class="form-control"></div>
            </div>

            <table class="table align-middle" id="linesTable">
                <thead><tr><th style="width:50%">Account</th><th class="text-end">Debit</th><th class="text-end">Credit</th><th></th></tr></thead>
                <tbody>
                    @for($i = 0; $i < 2; $i++)
                        <tr>
                            <td><select name="lines[{{ $i }}][account_id]" class="form-select form-select-sm js-account">
                                <option value="">— Select account —</option>
                                @foreach($accounts as $a)<option value="{{ $a->id }}">{{ $a->label }}</option>@endforeach
                            </select></td>
                            <td><input type="number" step="0.01" name="lines[{{ $i }}][debit]" class="form-control form-control-sm text-end js-debit"></td>
                            <td><input type="number" step="0.01" name="lines[{{ $i }}][credit]" class="form-control form-control-sm text-end js-credit"></td>
                            <td><button type="button" class="btn btn-sm btn-light border js-remove"><i class="bi bi-x"></i></button></td>
                        </tr>
                    @endfor
                </tbody>
                <tfoot class="table-light">
                    <tr><th>Totals</th><th class="text-end" id="totDebit">0</th><th class="text-end" id="totCredit">0</th><th></th></tr>
                </tfoot>
            </table>
            <button type="button" class="btn btn-sm btn-light border" id="addLine"><i class="bi bi-plus me-1"></i>Add Line</button>
            <span id="balanceMsg" class="ms-2 small"></span>

            <div class="mt-3"><button class="btn btn-primary"><i class="bi bi-check-lg me-1"></i>Post Entry</button>
                <a href="{{ route('journals.index') }}" class="btn btn-light border">Cancel</a></div>
        </form>
    </div></div>

    @push('scripts')
    <script>
        const tbody = document.querySelector('#linesTable tbody');
        const accountsHtml = tbody.querySelector('select').innerHTML;
        let idx = tbody.children.length;

        function recalc() {
            let d = 0, c = 0;
            tbody.querySelectorAll('.js-debit').forEach(i => d += parseFloat(i.value || 0));
            tbody.querySelectorAll('.js-credit').forEach(i => c += parseFloat(i.value || 0));
            document.getElementById('totDebit').textContent = d.toFixed(2);
            document.getElementById('totCredit').textContent = c.toFixed(2);
            const msg = document.getElementById('balanceMsg');
            if (d === c && d > 0) { msg.textContent = '✓ Balanced'; msg.className = 'ms-2 small text-success'; }
            else { msg.textContent = 'Not balanced (Dr − Cr = ' + (d - c).toFixed(2) + ')'; msg.className = 'ms-2 small text-danger'; }
        }
        document.getElementById('addLine').addEventListener('click', () => {
            const tr = document.createElement('tr');
            tr.innerHTML = `<td><select name="lines[${idx}][account_id]" class="form-select form-select-sm">${accountsHtml}</select></td>
                <td><input type="number" step="0.01" name="lines[${idx}][debit]" class="form-control form-control-sm text-end js-debit"></td>
                <td><input type="number" step="0.01" name="lines[${idx}][credit]" class="form-control form-control-sm text-end js-credit"></td>
                <td><button type="button" class="btn btn-sm btn-light border js-remove"><i class="bi bi-x"></i></button></td>`;
            tbody.appendChild(tr); idx++;
        });
        tbody.addEventListener('input', recalc);
        document.addEventListener('click', e => { if (e.target.closest('.js-remove')) { e.target.closest('tr').remove(); recalc(); } });
        recalc();
    </script>
    @endpush
@endsection
