<?php
$journal  = $journal ?? [];
$accounts = $accounts ?? [];
$periods  = $periods ?? [];
$lines    = $lines ?? [];
$isEdit   = ! empty($journal['id']);
?>
<div class="enterprise-settings-fields">
    <div class="enterprise-field">
        <label class="enterprise-field-label">Entry Date <span class="text-danger">*</span></label>
        <input type="date" name="entry_date" class="form-control" required
               value="<?= esc(old('entry_date', $journal['entry_date'] ?? date('Y-m-d'))) ?>">
    </div>
    <div class="enterprise-field">
        <label class="enterprise-field-label">Financial Period</label>
        <select name="fiscal_year_id" class="form-select">
            <option value="">— Auto from date —</option>
            <?php foreach ($periods as $p): ?>
                <option value="<?= $p['id'] ?>" <?= (string) old('fiscal_year_id', $journal['fiscal_year_id'] ?? '') === (string) $p['id'] ? 'selected' : '' ?>>
                    <?= esc($p['code'] . ' — ' . $p['name']) ?>
                </option>
            <?php endforeach; ?>
        </select>
    </div>
    <div class="enterprise-field">
        <label class="enterprise-field-label">Reference</label>
        <input type="text" name="reference" class="form-control" maxlength="100"
               value="<?= esc(old('reference', $journal['reference'] ?? '')) ?>">
    </div>
    <div class="enterprise-field" style="grid-column: 1 / -1;">
        <label class="enterprise-field-label">Description</label>
        <textarea name="description" class="form-control" rows="2"><?= esc(old('description', $journal['description'] ?? '')) ?></textarea>
    </div>
</div>

<div class="mt-4">
    <div class="d-flex justify-content-between align-items-center mb-2">
        <h3 class="h6 mb-0">Journal Lines</h3>
        <button type="button" class="btn btn-sm btn-outline-secondary" id="je-add-line"><i class="fa-solid fa-plus me-1"></i>Add Line</button>
    </div>
    <div class="table-responsive">
        <table class="enterprise-data-table" id="je-lines-table">
            <thead>
                <tr>
                    <th style="min-width:220px;">Account</th>
                    <th>Description</th>
                    <th style="width:140px;" class="text-end">Debit</th>
                    <th style="width:140px;" class="text-end">Credit</th>
                    <th style="width:50px;"></th>
                </tr>
            </thead>
            <tbody id="je-lines-body">
                <?php foreach ($lines as $i => $line): ?>
                    <tr class="je-line">
                        <td>
                            <select name="lines[<?= $i ?>][account_id]" class="form-select form-select-sm" required>
                                <option value="">— Select —</option>
                                <?php foreach ($accounts as $a): ?>
                                    <option value="<?= $a['id'] ?>" <?= (string) ($line['account_id'] ?? '') === (string) $a['id'] ? 'selected' : '' ?>>
                                        <?= esc($a['code'] . ' — ' . $a['name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                        <td>
                            <input type="text" name="lines[<?= $i ?>][description]" class="form-control form-control-sm"
                                   value="<?= esc($line['description'] ?? '') ?>">
                        </td>
                        <td>
                            <input type="number" step="0.01" min="0" name="lines[<?= $i ?>][debit]" class="form-control form-control-sm text-end je-debit"
                                   value="<?= esc($line['debit'] ?? '') ?>">
                        </td>
                        <td>
                            <input type="number" step="0.01" min="0" name="lines[<?= $i ?>][credit]" class="form-control form-control-sm text-end je-credit"
                                   value="<?= esc($line['credit'] ?? '') ?>">
                        </td>
                        <td class="text-end">
                            <button type="button" class="btn btn-sm btn-outline-danger je-remove-line"><i class="fa-solid fa-xmark"></i></button>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr>
                    <th colspan="2" class="text-end">Totals</th>
                    <th class="text-end" id="je-total-debit">0.00</th>
                    <th class="text-end" id="je-total-credit">0.00</th>
                    <th></th>
                </tr>
            </tfoot>
        </table>
    </div>
    <p class="small text-muted mt-2 mb-0" id="je-balance-hint">Debits and credits must be equal before saving.</p>
</div>

<template id="je-line-template">
    <tr class="je-line">
        <td>
            <select name="lines[__INDEX__][account_id]" class="form-select form-select-sm">
                <option value="">— Select —</option>
                <?php foreach ($accounts as $a): ?>
                    <option value="<?= $a['id'] ?>"><?= esc($a['code'] . ' — ' . $a['name']) ?></option>
                <?php endforeach; ?>
            </select>
        </td>
        <td><input type="text" name="lines[__INDEX__][description]" class="form-control form-control-sm"></td>
        <td><input type="number" step="0.01" min="0" name="lines[__INDEX__][debit]" class="form-control form-control-sm text-end je-debit"></td>
        <td><input type="number" step="0.01" min="0" name="lines[__INDEX__][credit]" class="form-control form-control-sm text-end je-credit"></td>
        <td class="text-end"><button type="button" class="btn btn-sm btn-outline-danger je-remove-line"><i class="fa-solid fa-xmark"></i></button></td>
    </tr>
</template>

<script>
(() => {
    const body = document.getElementById('je-lines-body');
    const tpl = document.getElementById('je-line-template');
    let index = body.querySelectorAll('.je-line').length;

    const money = (n) => (Math.round(n * 100) / 100).toFixed(2);

    const recalc = () => {
        let debit = 0, credit = 0;
        body.querySelectorAll('.je-debit').forEach(el => { debit += parseFloat(el.value || '0') || 0; });
        body.querySelectorAll('.je-credit').forEach(el => { credit += parseFloat(el.value || '0') || 0; });
        document.getElementById('je-total-debit').textContent = money(debit);
        document.getElementById('je-total-credit').textContent = money(credit);
        const hint = document.getElementById('je-balance-hint');
        if (Math.abs(debit - credit) < 0.005 && debit > 0) {
            hint.textContent = 'Entry is balanced.';
            hint.classList.remove('text-danger');
            hint.classList.add('text-success');
        } else {
            hint.textContent = 'Debits and credits must be equal before saving.';
            hint.classList.add('text-danger');
            hint.classList.remove('text-success');
        }
    };

    document.getElementById('je-add-line')?.addEventListener('click', () => {
        const html = tpl.innerHTML.replaceAll('__INDEX__', String(index++));
        body.insertAdjacentHTML('beforeend', html);
        recalc();
    });

    body.addEventListener('click', (e) => {
        const btn = e.target.closest('.je-remove-line');
        if (!btn) return;
        if (body.querySelectorAll('.je-line').length <= 2) return;
        btn.closest('.je-line')?.remove();
        recalc();
    });

    body.addEventListener('input', (e) => {
        if (e.target.classList.contains('je-debit') || e.target.classList.contains('je-credit')) {
            recalc();
        }
    });

    recalc();
})();
</script>
