@extends('layouts.app')

@section('content')
    <div class="row mb-4">
        <div class="col-12">
            <h2 class="fw-light">{{ __('New Journal Entry') }}</h2>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">{{ __('Dashboard') }}</a></li>
                    <li class="breadcrumb-item"><a href="{{ route('accounting.journals.index') }}">{{ __('Journal Entries') }}</a></li>
                    <li class="breadcrumb-item active">{{ __('Create') }}</li>
                </ol>
            </nav>
        </div>
    </div>

    <div class="card">
        <div class="card-header bg-dark text-white">
            {{ __('Entry Details') }}
        </div>
        <div class="card-body">
            <form action="{{ route('accounting.journals.store') }}" method="POST" id="journalForm">
                @csrf

                <div class="row mb-4">
                    <div class="col-md-4">
                        <label class="form-label">{{ __('Date') }} <span class="text-danger">*</span></label>
                        <input type="date" name="date" class="form-control" value="{{ date('Y-m-d') }}" required>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">{{ __('Reference') }}</label>
                        <input type="text" name="reference" class="form-control" placeholder="{{ __('e.g. MO-001') }}">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">{{ __('Description') }}</label>
                        <input type="text" name="description" class="form-control"
                            placeholder="{{ __('Brief description of the entry') }}">
                    </div>
                </div>

                <h5 class="mb-3 border-bottom pb-2">{{ __('Journal Lines') }}</h5>

                <div class="table-responsive">
                    <table class="table table-bordered" id="linesTable">
                        <thead class="table-light">
                            <tr>
                                <th width="40%">{{ __('Account') }}</th>
                                <th width="20%">{{ __('Debit') }}</th>
                                <th width="20%">{{ __('Credit') }}</th>
                                <th width="15%">{{ __('Note') }}</th>
                                <th width="5%"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr class="line-row">
                                <td>
                                    <select name="lines[0][account_id]" class="form-select select2" required>
                                        <option value="">{{ __('Select Account') }}</option>
                                        @foreach($accounts as $acc)
                                            <option value="{{ $acc->id }}">{{ $acc->code }} - {{ $acc->name }}</option>
                                        @endforeach
                                    </select>
                                </td>
                                <td>
                                    <input type="number" name="lines[0][debit]" class="form-control debit" step="0.01" min="0"
                                        value="0" onchange="calcTotals()">
                                </td>
                                <td>
                                    <input type="number" name="lines[0][credit]" class="form-control credit" step="0.01" min="0"
                                        value="0" onchange="calcTotals()">
                                </td>
                                <td>
                                    <input type="text" name="lines[0][description]" class="form-control"
                                        placeholder="{{ __('Line note') }}">
                                </td>
                                <td>
                                    <button type="button" class="btn btn-danger btn-sm" onclick="removeLine(this)">x</button>
                                </td>
                            </tr>
                            <tr class="line-row">
                                <td>
                                    <select name="lines[1][account_id]" class="form-select select2" required>
                                        <option value="">{{ __('Select Account') }}</option>
                                        @foreach($accounts as $acc)
                                            <option value="{{ $acc->id }}">{{ $acc->code }} - {{ $acc->name }}</option>
                                        @endforeach
                                    </select>
                                </td>
                                <td>
                                    <input type="number" name="lines[1][debit]" class="form-control debit" step="0.01" min="0"
                                        value="0" onchange="calcTotals()">
                                </td>
                                <td>
                                    <input type="number" name="lines[1][credit]" class="form-control credit" step="0.01" min="0"
                                        value="0" onchange="calcTotals()">
                                </td>
                                <td>
                                    <input type="text" name="lines[1][description]" class="form-control"
                                        placeholder="{{ __('Line note') }}">
                                </td>
                                <td>
                                    <button type="button" class="btn btn-danger btn-sm" onclick="removeLine(this)">x</button>
                                </td>
                            </tr>
                        </tbody>
                        <tfoot class="table-light">
                            <tr>
                                <th class="text-end">{{ __('Totals:') }}</th>
                                <th id="totalDebit">0.00</th>
                                <th id="totalCredit">0.00</th>
                                <th colspan="2" id="balanceStatus" class="text-success text-center">{{ __('Balanced') }}</th>
                            </tr>
                        </tfoot>
                    </table>
                </div>

                <div class="mb-3">
                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="addLine()">+ {{ __('Add Line') }}</button>
                </div>

                <div class="alert alert-warning d-none" id="balanceWarning">
                    {{ __('Entries must be balanced (Debit = Credit) before saving.') }}
                </div>

                <div class="text-end">
                    <button type="submit" class="btn btn-success btn-lg" id="saveBtn">{{ __('Post Entry') }}</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        let lineCount = 2;

        function addLine() {
            const table = document.getElementById('linesTable').getElementsByTagName('tbody')[0];
            const newRow = table.rows[0].cloneNode(true);

            // Reset inputs
            const inputs = newRow.querySelectorAll('input, select');
            inputs.forEach(input => {
                const name = input.getAttribute('name');
                input.setAttribute('name', name.replace(/lines\[\d+\]/, `lines[${lineCount}]`));
                if (input.tagName === 'INPUT') input.value = (input.type === 'number') ? '0' : '';
                if (input.tagName === 'SELECT') input.selectedIndex = 0;
            });

            table.appendChild(newRow);
            lineCount++;
        }

        function removeLine(btn) {
            const row = btn.parentNode.parentNode;
            if (document.querySelectorAll('.line-row').length > 2) {
                row.parentNode.removeChild(row);
                calcTotals();
            } else {
                alert("{{ __('A journal entry must have at least 2 lines.') }}");
            }
        }

        function calcTotals() {
            let debit = 0;
            let credit = 0;

            document.querySelectorAll('.debit').forEach(el => debit += parseFloat(el.value || 0));
            document.querySelectorAll('.credit').forEach(el => credit += parseFloat(el.value || 0));

            document.getElementById('totalDebit').innerText = debit.toFixed(2);
            document.getElementById('totalCredit').innerText = credit.toFixed(2);

            const diff = Math.abs(debit - credit);
            const status = document.getElementById('balanceStatus');
            const btn = document.getElementById('saveBtn');
            const warning = document.getElementById('balanceWarning');

            if (diff < 0.01) {
                status.innerHTML = '<span class="text-success"><i class="fas fa-check-circle"></i> {{ __('Balanced') }}</span>';
                btn.disabled = false;
                warning.classList.add('d-none');
            } else {
                status.innerHTML = `<span class="text-danger"><i class="fas fa-times-circle"></i> {{ __('Off by') }} ${diff.toFixed(2)}</span>`;
                btn.disabled = true;
                warning.classList.remove('d-none');
            }
        }
    </script>
@endsection