@extends('layouts.aura-main')

@section('main-content')
<div x-data="{ 
    loading: false,
    actionType: 'draft',
    showClearModal: false,
    rows: [
        { account_id: '', description: '', debit: '', credit: '' },
        { account_id: '', description: '', debit: '', credit: '' }
    ],

    importCSV(event) {
        const file = event.target.files[0];
        if (!file) return;

        const reader = new FileReader();
        reader.onload = (e) => {
            const content = e.target.result;
            const lines = content.split('\n');
            
            if (this.rows.length === 2 && !this.rows[0].account_id) {
                this.rows = [];
            }

            lines.forEach((line, index) => {
                if (index === 0 || line.trim() === '') return;
                
                const columns = line.split(',');
                if (columns.length >= 3) {
                    this.rows.push({
                        account_id: columns[0].trim(),
                        debit: columns[1] ? columns[1].trim() : '',
                        credit: columns[2] ? columns[2].trim() : '',
                        description: columns[3] ? columns[3].trim() : ''
                    });
                }
            });
        };
        reader.readAsText(file);
        event.target.value = '';
    },

    formatMoney(amount) {
        if (!amount || isNaN(amount)) return '0.00';
        return parseFloat(amount).toLocaleString('en-US', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        });
    },
    addRow() {
        this.rows.push({ account_id: '', description: '', debit: '', credit: '' });
    },
    removeRow(index) {
        if(this.rows.length > 2) {
            this.rows.splice(index, 1);
        }
    },
    confirmClear() {
        this.rows = [
            { account_id: '', description: '', debit: '', credit: '' },
            { account_id: '', description: '', debit: '', credit: '' }
        ];
        this.showClearModal = false;
    },
    get totalDebit() {
        return this.rows.reduce((sum, row) => sum + parseFloat(row.debit || 0), 0);
    },
    get totalCredit() {
        return this.rows.reduce((sum, row) => sum + parseFloat(row.credit || 0), 0);
    },
    get isBalanced() {
        const diff = Math.abs(this.totalDebit - this.totalCredit);
        return this.totalDebit > 0 && diff < 0.01;
    }
}">
    <div class="mb-6 flex flex-col lg:flex-row justify-between items-start lg:items-end gap-4 border-b border-slate-100 pb-4">
        <div>
            <h1 class="text-xl font-bold text-slate-800 tracking-tight">Journal entry</h1>
            <p class="text-slate-400 text-[10px] font-bold">Manual ledger and bulk import</p>
        </div>
        
        <div class="flex items-center gap-3">
            <a href="{{ route('accounting.transactions') }}" class="text-[11px] font-bold text-slate-400 px-4 py-2 hover:text-slate-600 transition">Cancel</a>
            
            <button type="submit" form="create-form" @click="actionType = 'draft'" :disabled="loading"
                    class="bg-white border border-slate-300 text-slate-600 px-5 py-2 rounded text-[11px] font-bold shadow-sm hover:bg-slate-50 transition">
                <span x-text="loading && actionType === 'draft' ? 'Saving...' : 'Save draft'"></span>
            </button>

            <button type="submit" form="create-form" @click="actionType = 'post'" :disabled="!isBalanced || loading" 
                    class="bg-indigo-600 text-white px-6 py-2 rounded text-[11px] font-bold shadow-sm hover:bg-indigo-700 disabled:opacity-50 transition">
                <span x-text="loading && actionType === 'post' ? 'Posting...' : 'Post journal'"></span>
            </button>
        </div>
    </div>

    <form id="create-form" action="{{ route('accounting.transactions.store') }}" method="POST" @submit="loading = true">
        @csrf
        
        <input type="hidden" name="action" :value="actionType">

        <div class="flex flex-wrap gap-8 mb-8">
            <div class="w-44">
                <label class="block text-[10px] font-bold text-slate-500 mb-1">Journal date</label>
                <input type="date" name="transaction_date" value="{{ date('Y-m-d') }}" class="w-full border border-slate-300 rounded px-2 py-1.5 text-xs font-bold outline-none focus:border-indigo-500 transition" required>
            </div>
            <div class="w-64">
                <label class="block text-[10px] font-bold text-slate-500 mb-1">Journal reference</label>
                <input type="text" name="reference" class="w-full border border-slate-300 rounded px-2 py-1.5 text-xs font-bold outline-none focus:border-indigo-500 transition" placeholder="e.g. jv/2026/001" required>
            </div>
        </div>

        <div class="bg-white border border-slate-300 rounded-sm overflow-hidden shadow-sm">
            <table class="w-full text-left border-collapse">
                <thead>
                    <tr class="bg-slate-50 border-b border-slate-300 text-[10px] font-bold text-slate-600">
                        <th class="px-2 py-3 border-r border-slate-200 w-10 text-center">#</th>
                        <th class="px-3 py-3 border-r border-slate-200 w-1/3">Account</th>
                        <th class="px-3 py-3 border-r border-slate-200 text-right w-36">Debits (zmw)</th>
                        <th class="px-3 py-3 border-r border-slate-200 text-right w-36">Credits (zmw)</th>
                        <th class="px-3 py-3 border-r border-slate-200">Line description</th>
                        <th class="px-2 py-3 w-10"></th>
                    </tr>
                </thead>
                <tbody class="text-xs">
                    <template x-for="(row, index) in rows" :key="index">
                        <tr class="border-b border-slate-200 hover:bg-slate-50/50 transition group">
                            <td class="px-2 py-2 border-r border-slate-200 text-center text-slate-400 font-mono" x-text="index + 1"></td>
                            <td class="px-0 py-0 border-r border-slate-200">
                                <select :name="`items[${index}][account_id]`" x-model="row.account_id" class="w-full px-3 py-2.5 bg-transparent outline-none font-bold text-slate-700" required>
                                    <option value="">Select account...</option>
                                    @foreach($accounts as $account)
                                        <option value="{{ $account->id }}">{{ $account->code }} - {{ $account->name }}</option>
                                    @endforeach
                                </select>
                            </td>
                            <td class="px-0 py-0 border-r border-slate-200">
                                <input type="number" step="0.01" :name="`items[${index}][debit]`" x-model="row.debit" 
                                       @input="if(row.debit > 0) row.credit = ''" 
                                       class="w-full px-3 py-2.5 bg-transparent text-right outline-none font-mono font-bold focus:bg-white text-indigo-600" placeholder="0.00">
                            </td>
                            <td class="px-0 py-0 border-r border-slate-200">
                                <input type="number" step="0.01" :name="`items[${index}][credit]`" x-model="row.credit" 
                                       @input="if(row.credit > 0) row.debit = ''" 
                                       class="w-full px-3 py-2.5 bg-transparent text-right outline-none font-mono font-bold focus:bg-white text-rose-600" placeholder="0.00">
                            </td>
                            <td class="px-0 py-0 border-r border-slate-200">
                                <input type="text" :name="`items[${index}][description]`" x-model="row.description" class="w-full px-3 py-2.5 bg-transparent outline-none text-slate-500" placeholder="Line memo...">
                            </td>
                            <td class="px-2 py-2 text-center">
                                <button type="button" @click="removeRow(index)" class="text-slate-300 hover:text-rose-500 opacity-0 group-hover:opacity-100 transition">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg>
                                </button>
                            </td>
                        </tr>
                    </template>
                </tbody>
                <tfoot class="bg-slate-50 text-xs font-bold text-slate-700">
                    <tr>
                        <td colspan="2" class="px-4 py-3 border-r border-slate-200 text-right">Total balance</td>
                        <td class="px-3 py-3 border-r border-slate-200 text-right font-mono text-indigo-600" x-text="formatMoney(totalDebit)"></td>
                        <td class="px-3 py-3 border-r border-slate-200 text-right font-mono text-rose-600" x-text="formatMoney(totalCredit)"></td>
                        <td colspan="2" class="px-4">
                            <span x-show="isBalanced" class="text-emerald-600 flex items-center gap-1">Balanced</span>
                            <span x-show="!isBalanced && totalDebit > 0" class="text-rose-500">Out of balance</span>
                        </td>
                    </tr>
                </tfoot>
            </table>
        </div>

        <div class="mt-4 flex flex-wrap gap-2">
            <button type="button" @click="addRow()" class="bg-white border border-slate-300 rounded px-4 py-1.5 text-[11px] font-bold text-slate-600 hover:bg-slate-50 transition shadow-sm">Add lines</button>
            
            <label class="cursor-pointer bg-white border border-slate-300 rounded px-4 py-1.5 text-[11px] font-bold text-slate-600 hover:bg-slate-50 transition shadow-sm">
                Upload csv
                <input type="file" accept=".csv" class="hidden" @change="importCSV($event)">
            </label>

            <a href="{{ route('accounting.transactions.template') }}" class="bg-white border border-slate-300 rounded px-4 py-1.5 text-[11px] font-bold text-slate-400 hover:text-slate-600 hover:bg-slate-50 transition shadow-sm">
                Download template
            </a>

            <button type="button" @click="showClearModal = true" class="bg-white border border-slate-300 rounded px-4 py-1.5 text-[11px] font-bold text-slate-600 hover:bg-slate-50 transition shadow-sm">Reset all</button>
        </div>

        <div class="mt-10 border-t border-slate-100 pt-8">
            <div class="max-w-xl">
                <label class="block text-[11px] font-bold text-slate-500 mb-2">General memo</label>
                <textarea name="description" rows="4" class="w-full border border-slate-300 rounded-sm p-3 text-xs outline-none focus:border-indigo-500 shadow-sm transition" placeholder="Enter general description for this transaction..."></textarea>
            </div>
        </div>
    </form>

    <div x-show="showClearModal" class="fixed inset-0 z-[60] flex items-center justify-center p-4 bg-slate-900/40 backdrop-blur-sm" x-cloak x-transition>
        <div class="bg-white rounded-sm shadow-xl w-full max-w-sm overflow-hidden border border-slate-200" @click.away="showClearModal = false">
            <div class="p-6">
                <h3 class="text-sm font-bold text-slate-800 mb-2">Reset journal?</h3>
                <p class="text-[11px] text-slate-500 leading-relaxed mb-6">This will permanently remove all current entries from the table.</p>
                <div class="flex justify-end gap-2">
                    <button @click="showClearModal = false" class="px-4 py-2 text-[10px] font-bold text-slate-400 hover:text-slate-600 uppercase transition">Cancel</button>
                    <button @click="confirmClear()" class="bg-rose-500 text-white px-5 py-2 rounded-sm text-[10px] font-bold uppercase hover:bg-rose-600 transition shadow-sm">Yes, clear all</button>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection