@extends('layouts.user')

@section('title', __('accounts_ledger.add_account_entry'))
@section('breadcrumb', __('accounts_ledger.account_ledger'))
@section('page_title', __('accounts_ledger.add_entry'))

@section('content')
<div class="max-w-3xl mx-auto space-y-4 text-xs">

    <div class="bg-white border p-4 shadow-sm">
        <div class="flex items-start justify-between gap-3 flex-wrap">
            <div>
                <div class="text-[11px] text-slate-500">{{ __('accounts_ledger.account') }}</div>
                <div class="text-xl font-extrabold text-slate-900">{{ $account->name }}</div>
                <div class="text-xs text-slate-600 mt-1">
                    {{ __('accounts_ledger.type') }}:
                    <span class="font-semibold">{{ strtoupper($account->type) }}</span>

                    @if(!empty($account->account_number))
                        <span class="text-slate-400">•</span>
                        {{ __('accounts_ledger.account_short') }}:
                        <span class="font-semibold">{{ $account->account_number }}</span>
                    @endif
                </div>
                <div class="text-[11px] text-slate-500 mt-2">
                    {{ __('accounts_ledger.manual_entry_affect_hint') }}
                </div>
            </div>

            <a href="{{ route('user.accounts.ledger.index', $account) }}"
               class="px-3 py-2 border bg-white text-xs font-semibold hover:bg-slate-50">
                {{ __('accounts_ledger.back') }}
            </a>
        </div>
    </div>

    @if(session('ok'))
        <div class="border border-emerald-200 bg-emerald-50 p-3 text-xs text-emerald-700">
            {{ session('ok') }}
        </div>
    @endif

    @if(session('err'))
        <div class="border border-rose-200 bg-rose-50 p-3 text-xs text-rose-700">
            {{ session('err') }}
        </div>
    @endif

    @if($errors->any())
        <div class="border border-rose-200 bg-rose-50 p-3 text-xs text-rose-700">
            <div class="font-bold mb-2">{{ __('accounts_ledger.fix_these_errors') }}</div>
            <ul class="list-disc pl-5 space-y-1">
                @foreach($errors->all() as $e)
                    <li>{{ $e }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <div class="bg-white border p-4 shadow-sm">
        <form id="entryForm" method="POST" action="{{ route('user.accounts.ledger.store', $account) }}" class="space-y-4">
            @csrf

            <div>
                <label class="text-xs font-semibold text-slate-700">{{ __('accounts_ledger.entry_type') }}</label>

                <select name="action" id="action"
                        class="mt-1.5 w-full border border-slate-200 px-3 py-2.5 text-xs focus:border-slate-400 focus:outline-none">
                    <option value="deposit" @selected(old('action') === 'deposit')>{{ __('accounts_ledger.deposit_money_in') }}</option>
                    <option value="withdraw" @selected(old('action') === 'withdraw')>{{ __('accounts_ledger.withdraw_money_out') }}</option>
                    <option value="adjust_in" @selected(old('action') === 'adjust_in')>{{ __('accounts_ledger.adjust_in_correction_in') }}</option>
                    <option value="adjust_out" @selected(old('action') === 'adjust_out')>{{ __('accounts_ledger.adjust_out_correction_out') }}</option>
                </select>
            </div>

            <div class="grid md:grid-cols-2 gap-4">
                <div>
                    <label class="text-xs font-semibold text-slate-700">{{ __('accounts_ledger.amount') }}</label>
                    <input type="number"
                           step="any"
                           min="0"
                           name="amount"
                           value="{{ old('amount') }}"
                           placeholder="example 1000"
                           class="mt-1.5 w-full border border-slate-200 px-3 py-2.5 text-xs focus:border-slate-400 focus:outline-none">
                </div>

                <div>
                    <label class="text-xs font-semibold text-slate-700">{{ __('accounts_ledger.date_time_optional') }}</label>
                    <input type="datetime-local"
                           name="posted_at"
                           value="{{ old('posted_at') }}"
                           class="mt-1.5 w-full border border-slate-200 px-3 py-2.5 text-xs focus:border-slate-400 focus:outline-none">
                    <div class="text-[11px] text-slate-500 mt-1.5">{{ __('accounts_ledger.blank_current_time_hint') }}</div>
                </div>
            </div>

            <div>
                <label class="text-xs font-semibold text-slate-700">{{ __('accounts_ledger.note_optional') }}</label>
                <textarea name="note"
                          rows="4"
                          placeholder="{{ __('accounts_ledger.write_short_note') }}"
                          class="mt-1.5 w-full border border-slate-200 px-3 py-2.5 text-xs focus:border-slate-400 focus:outline-none">{{ old('note') }}</textarea>
            </div>

            <div id="previewBox" class="border bg-slate-50 p-3">
                <div class="text-[11px] text-slate-500">{{ __('accounts_ledger.preview') }}</div>
                <div class="mt-3 grid sm:grid-cols-3 gap-3 text-xs">
                    <div>
                        <span class="font-semibold">{{ __('accounts_ledger.action') }}:</span>
                        <span id="pvAction" class="ml-1 inline-block border bg-white px-2 py-0.5 text-[11px]">{{ __('accounts_ledger.deposit_upper') }}</span>
                    </div>
                    <div>
                        <span class="font-semibold">{{ __('accounts_ledger.effect') }}:</span>
                        <span id="pvEffect" class="ml-1 text-emerald-700 font-extrabold">{{ __('accounts_ledger.plus_debit') }}</span>
                    </div>
                    <div>
                        <span class="font-semibold">{{ __('accounts_ledger.amount') }}:</span>
                        <span id="pvAmount" class="ml-1 font-extrabold">0.00</span>
                    </div>
                </div>
            </div>

            <div class="flex gap-2 pt-1">
                <button type="submit"
                        class="px-4 py-2.5 bg-slate-900 text-white text-xs font-semibold hover:bg-slate-800">
                    {{ __('accounts_ledger.save_entry') }}
                </button>

                <a href="{{ route('user.accounts.ledger.index', $account) }}"
                   class="px-4 py-2.5 border bg-white text-xs font-semibold hover:bg-slate-50">
                    {{ __('accounts_ledger.cancel') }}
                </a>
            </div>
        </form>
    </div>
</div>

<script>
(function(){
    const actionEl = document.getElementById('action');
    const amountEl = document.querySelector('input[name="amount"]');
    const pvAction = document.getElementById('pvAction');
    const pvEffect = document.getElementById('pvEffect');
    const pvAmount = document.getElementById('pvAmount');
    const form = document.getElementById('entryForm');

    const labels = {
        deposit: @json(__('accounts_ledger.deposit_upper')),
        withdraw: @json(__('accounts_ledger.withdraw_upper')),
        adjust_in: @json(__('accounts_ledger.adjust_in_upper')),
        adjust_out: @json(__('accounts_ledger.adjust_out_upper')),
    };

    const effects = {
        debit: @json(__('accounts_ledger.plus_debit')),
        credit: @json(__('accounts_ledger.minus_credit')),
    };

    function fmt(n){
        const x = parseFloat(n || 0);
        return x.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
    }

    function updatePreview(){
        const act = actionEl.value || 'deposit';
        pvAction.textContent = labels[act] || act.toUpperCase();

        if(act === 'withdraw' || act === 'adjust_out'){
            pvEffect.textContent = effects.credit;
            pvEffect.className = 'ml-1 text-rose-700 font-extrabold';
        } else {
            pvEffect.textContent = effects.debit;
            pvEffect.className = 'ml-1 text-emerald-700 font-extrabold';
        }

        pvAmount.textContent = fmt(amountEl.value);
    }

    actionEl.addEventListener('change', updatePreview);
    amountEl.addEventListener('input', updatePreview);
    updatePreview();

    form.addEventListener('submit', function(e){
        if (typeof Swal === 'undefined') return;
        e.preventDefault();

        const act = actionEl.options[actionEl.selectedIndex].text;
        const amt = fmt(amountEl.value);

        Swal.fire({
            title: @json(__('accounts_ledger.confirm_entry_title')),
            html: `<div style="text-align:left">
                    <div><b>${@json(__('accounts_ledger.type'))}:</b> ${act}</div>
                    <div><b>${@json(__('accounts_ledger.amount'))}:</b> ${amt}</div>
                  </div>`,
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: @json(__('accounts_ledger.yes_save')),
            cancelButtonText: @json(__('accounts_ledger.cancel'))
        }).then((r) => {
            if(r.isConfirmed) form.submit();
        });
    });
})();
</script>
@endsection