@extends('layouts.app')
@section('title', isset($voucher) ? 'Edit '.$label : 'New '.$label)

@section('breadcrumb')
    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
    <li class="breadcrumb-item"><a href="{{ route('vouchers.index', $voucherType) }}">{{ $label }}</a></li>
    <li class="breadcrumb-item active">{{ isset($voucher) ? 'Edit' : 'New' }}</li>
@endsection

@push('styles')
<style>
.debit-input  { border-left:3px solid #198754 !important; }
.credit-input { border-left:3px solid #dc3545 !important; }
.debit-input:focus  { box-shadow:0 0 0 .2rem rgba(25,135,84,.15) !important; }
.credit-input:focus { box-shadow:0 0 0 .2rem rgba(220,53,69,.15) !important; }
</style>
@endpush

@section('content')
<div class="page-header">
    <div>
        <h1 class="page-title">{{ isset($voucher) ? 'Edit '.$label : 'New '.$label }}</h1>
        @if(isset($voucher))
            <p class="page-subtitle text-muted"><code>{{ $voucher->voucher_number }}</code></p>
        @endif
    </div>
    <a href="{{ route('vouchers.index', $voucherType) }}" class="btn btn-outline-secondary">
        <i class="bi bi-arrow-left me-1"></i>Back
    </a>
</div>

@if($errors->any())
<div class="alert alert-danger d-flex gap-2 align-items-start mb-3">
    <i class="bi bi-exclamation-triangle fs-5 flex-shrink-0 mt-1"></i>
    <div>
        <strong>Please fix the errors below:</strong>
        @foreach($errors->all() as $err)<div style="font-size:13.5px">{{ $err }}</div>@endforeach
    </div>
</div>
@endif

<script type="application/json" id="voucherDimensionTreesData">@json($dimensionTrees ?? [])</script>
<script type="application/json" id="voucherPartyTreeData">@json($partyTree ?? [])</script>
<script type="application/json" id="voucherAccountTreeData">@json($accountTree ?? [])</script>

<form method="POST"
      action="{{ isset($voucher) ? route('vouchers.update',[$voucherType,$voucher]) : route('vouchers.store',$voucherType) }}"
      id="voucherForm"
      enctype="multipart/form-data">
@csrf
@if(isset($voucher)) @method('PUT') @endif

{{-- ── Voucher Header ────────────────────────────────────────────────────────── --}}
<div class="card mb-4">
    <div class="card-header fw-semibold d-flex align-items-center justify-content-between">
        <span><i class="bi bi-receipt me-2 text-primary"></i>Voucher Header</span>
        @if(!isset($voucher))
        <span class="text-muted" style="font-size:12px">
            Auto No: <code class="text-primary fw-semibold">{{ $preview }}</code>
        </span>
        @endif
    </div>
    <div class="card-body">
        <div class="row g-3">

            {{-- Voucher Date --}}
            <div class="col-12 col-sm-6 col-md-2">
                <label class="form-label fw-semibold">Voucher Date <span class="text-danger">*</span></label>
                <input type="date" name="voucher_date" required
                       class="form-control @error('voucher_date') is-invalid @enderror"
                       value="{{ old('voucher_date', isset($voucher) ? $voucher->voucher_date->format('Y-m-d') : date('Y-m-d')) }}">
                @error('voucher_date')<div class="invalid-feedback">{{ $message }}</div>@enderror
            </div>

            {{-- Voucher No (manual override) --}}
            <div class="col-12 col-sm-6 col-md-2">
                <label class="form-label fw-semibold">Voucher No</label>
                <input type="text" name="manual_number"
                       class="form-control"
                       value="{{ old('manual_number', $voucher->voucher_number ?? '') }}"
                       placeholder="{{ $preview ?? 'Auto-generated' }}"
                       style="font-family:monospace">
                <div class="form-text" style="font-size:11px">Leave blank for auto number</div>
            </div>

            {{-- Reference --}}
            <div class="col-12 col-sm-6 col-md-2">
                <label class="form-label fw-semibold">Reference</label>
                <input type="text" name="reference"
                       class="form-control"
                       value="{{ old('reference', $voucher->reference ?? '') }}"
                       placeholder="Invoice no, PO no…">
            </div>

            @include('accounting.vouchers._payment_method_field')

            @include('accounting.vouchers._cheque_fields', ['voucher' => $voucher ?? null])

            {{-- Currency --}}
            @if(count($currencies) > 1)
            <div class="col-12 col-sm-6 col-md-2">
                <label class="form-label fw-semibold">Currency</label>
                <select name="currency_id" id="currencyId" class="form-select">
                    <option value="">Base Currency</option>
                    @foreach($currencies as $cur)
                        <option value="{{ $cur->id }}"
                            {{ old('currency_id', $voucher->currency_id ?? '') == $cur->id ? 'selected':'' }}>
                            {{ $cur->code }}
                        </option>
                    @endforeach
                </select>
            </div>
            <div class="col-12 col-sm-6 col-md-2" id="exchangeRateRow" style="display:none">
                <label class="form-label fw-semibold">Exchange Rate</label>
                <input type="number" name="exchange_rate" id="exchangeRate"
                       class="form-control"
                       value="{{ old('exchange_rate', $voucher->exchange_rate ?? 1) }}"
                       step="0.000001" min="0.000001">
            </div>
            @endif

            {{-- Paid To / Received From (payment/receipt vouchers only) --}}
            @php
                $partyLabel = match($voucherType) {
                    'cash_payment','bank_payment' => 'Paid To',
                    'cash_receipt','bank_receipt' => 'Received From',
                    default => null,
                };
                $partyTypes = ['cash_payment','bank_payment','cash_receipt','bank_receipt'];
            @endphp
            @if(in_array($voucherType, $partyTypes))
                @include('accounting.vouchers._party_header_field', [
                    'partyLabel' => $partyLabel,
                    'voucher' => $voucher ?? null,
                ])
            @endif

            {{-- Narration --}}
            <div class="col-12 col-md-4">
                <label class="form-label fw-semibold">Narration</label>
                <input type="text" name="narration"
                       class="form-control"
                       value="{{ old('narration', $voucher->narration ?? '') }}"
                       placeholder="Brief description of this voucher">
            </div>
        </div>
    </div>
</div>

{{-- ── Account Lines ─────────────────────────────────────────────────────────── --}}
<div class="card mb-4 voucher-journal-card">
    <div class="card-header fw-semibold">
        <i class="bi bi-table me-2 text-primary"></i>Account Lines
        <span class="text-muted fw-normal ms-2" style="font-size:12px">— Debit and Credit must balance</span>
    </div>

    {{-- Balance bar --}}
    <div class="p-3 border-bottom" style="background:#f8f9fa">
        <div class="row g-2 align-items-center">
            <div class="col-4">
                <div style="font-size:11px;color:#6c757d;font-weight:700;text-transform:uppercase;letter-spacing:.4px">Total Debit</div>
                <div id="totalDebitDisplay" class="fw-bold" style="font-size:18px;color:#0a3622;line-height:1.2">0.00</div>
            </div>
            <div class="col-4">
                <div style="font-size:11px;color:#6c757d;font-weight:700;text-transform:uppercase;letter-spacing:.4px">Total Credit</div>
                <div id="totalCreditDisplay" class="fw-bold" style="font-size:18px;color:#842029;line-height:1.2">0.00</div>
            </div>
            <div class="col-4 text-end">
                <span id="balanceBadge" class="badge px-3 py-2" style="font-size:12px;background:#e9ecef;color:#495057">
                    <i class="bi bi-dash-circle me-1"></i>Not Balanced
                </span>
            </div>
        </div>
    </div>

    <div class="card-body p-0">
        <div class="table-responsive voucher-lines-table-wrap">
            <table class="table mb-0" id="linesTable" style="min-width:580px">
                <thead class="table-light">
                    <tr>
                        <th class="ps-3" style="width:32px">#</th>
                        <th style="min-width:200px">Account <span class="text-danger">*</span></th>
                        <th class="text-end" style="width:130px">
                            <span style="color:#198754">Debit</span>
                        </th>
                        <th class="text-end" style="width:130px">
                            <span style="color:#dc3545">Credit</span>
                        </th>
                        <th class="d-none d-md-table-cell">Description</th>
                        @if(count($taxCodes) > 0)
                        <th class="d-none d-xl-table-cell" style="width:130px">Tax Code</th>
                        @endif
                        @foreach($dimensions as $dimension)
                            <th class="d-none d-lg-table-cell voucher-dimension-header" style="min-width:150px">{{ $dimension->name }}</th>
                        @endforeach
                        <th class="d-none d-lg-table-cell voucher-party-header" style="min-width:170px">Name</th>
                        <th style="width:36px"></th>
                    </tr>
                </thead>
                <tbody id="linesBody">
                    @php $existingLines = isset($voucher) ? $voucher->lines : collect(); @endphp
                    @if($existingLines->count() > 0)
                        @foreach($existingLines as $i => $line)
                        @include('accounting.vouchers._line_row', [
                            'i'        => $i,
                            'line'     => $line,
                            'accounts' => $accounts,
                            'taxCodes' => $taxCodes,
                            'dimensions' => $dimensions,
                            'isNew'    => false,
                        ])
                        @endforeach
                    @else
                        @include('accounting.vouchers._line_row', ['i'=>0,'line'=>null,'accounts'=>$accounts,'taxCodes'=>$taxCodes,'dimensions'=>$dimensions,'isNew'=>true])
                        @include('accounting.vouchers._line_row', ['i'=>1,'line'=>null,'accounts'=>$accounts,'taxCodes'=>$taxCodes,'dimensions'=>$dimensions,'isNew'=>true])
                    @endif
                </tbody>
            </table>
        </div>
    </div>

    <div class="card-footer bg-white voucher-journal-footer">
        <div class="d-flex flex-wrap justify-content-between align-items-end gap-3 w-100">
            <div class="voucher-journal-footer-left flex-grow-1">
                <div class="d-flex align-items-center gap-3 mb-2">
                    <button type="button" class="btn btn-outline-primary btn-sm" id="addLine">
                        <i class="bi bi-plus-circle me-1"></i>Add Line
                    </button>
                    <span id="minLinesMsg" class="text-danger" style="display:none;font-size:12.5px">
                        <i class="bi bi-exclamation-triangle me-1"></i>At least one line is required.
                    </span>
                </div>
                @include('accounting.vouchers._attachments_panel', [
                    'mode' => isset($voucher) ? 'edit' : 'create',
                    'layout' => 'inline',
                    'voucher' => $voucher ?? null,
                    'voucherType' => $voucherType,
                    'attachments' => isset($voucher) ? $voucher->attachments : collect(),
                ])
            </div>
            @include('accounting.vouchers._form_footer_actions', [
                'voucherType' => $voucherType,
                'voucher' => $voucher ?? null,
                'approvalReq' => $approvalReq,
            ])
        </div>
    </div>
</div>

</form>

{{-- JS line template --}}
<script type="text/template" id="lineTemplate">
    @include('accounting.vouchers._line_row', ['i'=>'__IDX__','line'=>null,'accounts'=>$accounts,'taxCodes'=>$taxCodes,'dimensions'=>$dimensions,'isNew'=>true])
</script>
@endsection

@push('scripts')
<script>
let lineIndex = document.querySelectorAll('.voucher-line').length;

// ── Balance recalc ────────────────────────────────────────────────────────────
function recalcBalance() {
    let totalDr = 0, totalCr = 0;
    document.querySelectorAll('.voucher-line').forEach(row => {
        const dr = parseFloat(row.querySelector('.debit-input')?.value  || 0) || 0;
        const cr = parseFloat(row.querySelector('.credit-input')?.value || 0) || 0;
        totalDr += dr;
        totalCr += cr;
    });

    document.getElementById('totalDebitDisplay').textContent  = totalDr.toFixed(2);
    document.getElementById('totalCreditDisplay').textContent = totalCr.toFixed(2);

    const diff    = Math.abs(totalDr - totalCr);
    const badge   = document.getElementById('balanceBadge');
    const balanced = diff < 0.01 && totalDr > 0;

    if (balanced) {
        badge.style.cssText = 'background:#d1e7dd;color:#0a3622;font-size:12px';
        badge.innerHTML     = '<i class="bi bi-check-circle me-1"></i>Balanced';
    } else if (totalDr === 0 && totalCr === 0) {
        badge.style.cssText = 'background:#e9ecef;color:#495057;font-size:12px';
        badge.innerHTML     = '<i class="bi bi-dash-circle me-1"></i>Not Balanced';
    } else {
        badge.style.cssText = 'background:#f8d7da;color:#842029;font-size:12px';
        badge.innerHTML     = '<i class="bi bi-exclamation-triangle me-1"></i>Diff: ' + diff.toFixed(2);
    }
}

// ── Mutual exclusion: entering debit clears credit and vice versa ─────────────
document.addEventListener('input', e => {
    if (e.target.classList.contains('debit-input')) {
        if (parseFloat(e.target.value) > 0) {
            const row = e.target.closest('tr');
            if (row) { const cr = row.querySelector('.credit-input'); if (cr) cr.value = ''; }
        }
        recalcBalance();
    }
    if (e.target.classList.contains('credit-input')) {
        if (parseFloat(e.target.value) > 0) {
            const row = e.target.closest('tr');
            if (row) { const dr = row.querySelector('.debit-input'); if (dr) dr.value = ''; }
        }
        recalcBalance();
    }
});

// ── Renumber ──────────────────────────────────────────────────────────────────
function renumberRows() {
    document.querySelectorAll('.voucher-line').forEach((row, i) => {
        const c = row.querySelector('.line-num');
        if (c) c.textContent = i + 1;
    });
}

// ── Add Line ──────────────────────────────────────────────────────────────────
document.getElementById('addLine').addEventListener('click', () => {
    const tmpl = document.getElementById('lineTemplate').textContent || document.getElementById('lineTemplate').innerHTML;
    const html  = tmpl.replaceAll('__IDX__', lineIndex);
    document.getElementById('linesBody').insertAdjacentHTML('beforeend', html);
    const newRow = document.querySelector(`.voucher-line[data-index="${lineIndex}"]`);
    if (newRow) {
        if (typeof window.axisInitVoucherAccountPickers === 'function') {
            window.axisInitVoucherAccountPickers(newRow);
        }
        if (typeof window.axisInitVoucherDimensionPickers === 'function') {
            window.axisInitVoucherDimensionPickers(newRow);
        }
        if (typeof window.axisInitVoucherPartyPickers === 'function') {
            window.axisInitVoucherPartyPickers(newRow);
        }
    }
    lineIndex++;
    renumberRows();
    recalcBalance();
});

// ── Remove Line ───────────────────────────────────────────────────────────────
document.addEventListener('click', e => {
    const btn = e.target.closest('.remove-line');
    if (!btn) return;
    const rows = document.querySelectorAll('.voucher-line');
    if (rows.length <= 1) {
        const msg = document.getElementById('minLinesMsg');
        if (msg) { msg.style.display = ''; setTimeout(() => msg.style.display = 'none', 3000); }
        return;
    }
    btn.closest('tr').remove();
    renumberRows();
    recalcBalance();
});

// ── Currency toggle ───────────────────────────────────────────────────────────
const currEl = document.getElementById('currencyId');
if (currEl) {
    function toggleExchangeRow() {
        const row = document.getElementById('exchangeRateRow');
        if (row) row.style.display = currEl.value ? '' : 'none';
    }
    currEl.addEventListener('change', toggleExchangeRow);
    toggleExchangeRow();
}

// ── Submit spinner ────────────────────────────────────────────────────────────
document.getElementById('voucherForm').addEventListener('submit', function(event) {
    const submitter = event.submitter;
    const activeBtn = submitter?.type === 'submit'
        ? submitter
        : document.getElementById('saveBtn');
    if (activeBtn) {
        activeBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Saving…';
    }
    document.querySelectorAll('#voucherForm button[type="submit"]').forEach((button) => {
        button.disabled = true;
    });
});

// ── Init pickers on load ──────────────────────────────────────────────────────
$(document).ready(function() {
    if (typeof window.axisInitVoucherAccountPickers === 'function') {
        window.axisInitVoucherAccountPickers();
    }
    if (typeof window.axisInitVoucherDimensionPickers === 'function') {
        window.axisInitVoucherDimensionPickers();
    }
    if (typeof window.axisInitVoucherPartyPickers === 'function') {
        window.axisInitVoucherPartyPickers();
    }
    recalcBalance();
});
</script>
@include('accounting.vouchers._cheque_register_scripts', ['voucher' => $voucher ?? null])
@endpush
