@extends('layouts.admin')

@section('title', 'Create Journal Entry')

@section('page-title', 'Create Journal Entry')

@section('content')
<form method="POST" action="{{ route('admin.journal-entries.store') }}" id="journal-form" class="max-w-5xl mx-auto flex flex-col gap-6 pb-24">
    @csrf

    <div class="bg-white rounded-xl shadow-sm border border-[#e5e7eb] p-6">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
                <label class="block text-sm font-medium text-[#111418] text-gray-900 mb-2">Entry Date <span class="text-red-500">*</span></label>
                <input type="date" name="entry_date" value="{{ old('entry_date', now()->format('Y-m-d')) }}" required class="w-full h-11 rounded-lg border border-[#dbe0e6] bg-white px-3 py-2 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900">
            </div>
            <div>
                <label class="block text-sm font-medium text-[#111418] text-gray-900 mb-2">Status</label>
                <select name="status" class="w-full h-11 rounded-lg border border-[#dbe0e6] bg-white px-3 py-2 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900">
                    <option value="draft" {{ old('status') == 'draft' ? 'selected' : '' }}>Draft</option>
                    <option value="posted" {{ old('status') == 'posted' ? 'selected' : '' }}>Posted</option>
                </select>
            </div>
        </div>
        <div class="mt-6">
            <label class="block text-sm font-medium text-[#111418] text-gray-900 mb-2">Description</label>
            <textarea name="description" rows="2" class="w-full rounded-lg border border-[#dbe0e6] bg-white px-3 py-2 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900">{{ old('description') }}</textarea>
        </div>
    </div>

    <div class="bg-white rounded-xl shadow-sm border border-[#e5e7eb] p-6">
        <h3 class="text-lg font-bold text-[#111418] text-gray-900 mb-6">Journal Entry Lines</h3>
        <div class="overflow-x-auto">
            <table class="w-full text-left border-collapse" id="lines-table">
                <thead>
                    <tr class="border-b border-[#e5e7eb]">
                        <th class="py-3 px-2 text-xs font-semibold text-[#617589] uppercase tracking-wider">Account</th>
                        <th class="py-3 px-2 text-xs font-semibold text-[#617589] uppercase tracking-wider">Type</th>
                        <th class="py-3 px-2 text-xs font-semibold text-[#617589] uppercase tracking-wider text-right">Amount</th>
                        <th class="py-3 px-2 text-xs font-semibold text-[#617589] uppercase tracking-wider">Description</th>
                        <th class="py-3 px-2 text-xs font-semibold text-[#617589] uppercase tracking-wider"></th>
                    </tr>
                </thead>
                <tbody class="text-sm" id="lines-tbody"></tbody>
            </table>
        </div>
        <div class="flex gap-3 mt-4">
            <button type="button" onclick="addLine()" class="flex items-center gap-2 px-4 py-2 rounded-lg bg-primary/10 text-primary font-medium text-sm hover:bg-primary/20 transition-colors">
                <span class="material-symbols-outlined text-lg">add_circle</span> Add Line
            </button>
        </div>
        <div class="mt-6 pt-6 border-t border-[#e5e7eb] flex justify-between items-center">
            <span class="text-sm font-medium text-[#111418] text-gray-900">Total Debit:</span>
            <span class="text-lg font-bold text-[#111418] text-gray-900" id="total-debit">0.00</span>
        </div>
        <div class="flex justify-between items-center">
            <span class="text-sm font-medium text-[#111418] text-gray-900">Total Credit:</span>
            <span class="text-lg font-bold text-[#111418] text-gray-900" id="total-credit">0.00</span>
        </div>
        <div class="flex justify-between items-center pt-2 border-t border-[#e5e7eb]">
            <span class="text-base font-bold text-[#111418] text-gray-900">Balance:</span>
            <span class="text-xl font-bold {{ $balance = 0 }}" id="balance">0.00</span>
        </div>
    </div>

    <div class="fixed bottom-0 left-0 right-0 bg-white border-t border-[#e5e7eb] p-4 z-20 shadow-[0_-4px_6px_-1px_rgba(0,0,0,0.05)]">
        <div class="max-w-5xl mx-auto flex justify-between items-center">
            <a href="{{ route('admin.journal-entries.index') }}" class="px-6 py-2.5 rounded-lg border border-[#dbe0e6] text-[#617589] font-medium hover:bg-background-light transition-colors">Cancel</a>
            <button type="submit" class="px-8 py-2.5 rounded-lg bg-primary text-white font-bold hover:bg-blue-600 transition-all flex items-center gap-2">
                Create Entry <span class="material-symbols-outlined text-lg">save</span>
            </button>
        </div>
    </div>
</form>

<script>
let lineIndex = 0;
const accounts = @json($accounts->map(fn($a) => ['id' => $a->id, 'code' => $a->code, 'name' => $a->name]));

function addLine() {
    const tbody = document.getElementById('lines-tbody');
    const row = document.createElement('tr');
    row.className = 'group hover:bg-background-light/50 border-b border-[#f0f2f4]';
    row.dataset.index = lineIndex;

    let accountOptions = accounts.map(a => `<option value="${a.id}">${a.code} - ${a.name}</option>`).join('');

    row.innerHTML = `
        <td class="py-4 px-2">
            <select name="lines[${lineIndex}][account_id]" required class="w-full h-10 rounded-lg border border-[#e5e7eb] bg-white px-3 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900">
                <option value="">Select account...</option>
                ${accountOptions}
            </select>
        </td>
        <td class="py-4 px-2">
            <select name="lines[${lineIndex}][type]" required class="w-full h-10 rounded-lg border border-[#e5e7eb] bg-white px-3 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900" onchange="calculateTotals()">
                <option value="debit">Debit</option>
                <option value="credit">Credit</option>
            </select>
        </td>
        <td class="py-4 px-2">
            <input type="number" name="lines[${lineIndex}][amount]" required min="0.01" step="0.01" class="w-full text-right h-10 rounded-lg border border-[#e5e7eb] bg-white px-3 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900" onchange="calculateTotals()">
        </td>
        <td class="py-4 px-2">
            <input type="text" name="lines[${lineIndex}][description]" class="w-full h-10 rounded-lg border border-[#e5e7eb] bg-white px-3 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900">
        </td>
        <td class="py-4 px-2 text-center">
            <button type="button" onclick="removeLine(${lineIndex})" class="text-red-400 hover:text-red-600 transition-opacity">
                <span class="material-symbols-outlined text-lg">delete</span>
            </button>
        </td>
    `;

    tbody.appendChild(row);
    lineIndex++;
    calculateTotals();
}

function removeLine(index) {
    const row = document.querySelector(`tr[data-index="${index}"]`);
    if (row) {
        row.remove();
        calculateTotals();
    }
}

function calculateTotals() {
    let totalDebit = 0;
    let totalCredit = 0;

    document.querySelectorAll('tr[data-index]').forEach((row, index) => {
        const type = row.querySelector(`select[name="lines[${index}][type]"]`)?.value;
        const amount = parseFloat(row.querySelector(`input[name="lines[${index}][amount]"]`)?.value) || 0;

        if (type === 'debit') {
            totalDebit += amount;
        } else if (type === 'credit') {
            totalCredit += amount;
        }
    });

    const balance = totalDebit - totalCredit;

    document.getElementById('total-debit').textContent = totalDebit.toFixed(2);
    document.getElementById('total-credit').textContent = totalCredit.toFixed(2);
    document.getElementById('balance').textContent = balance.toFixed(2);
    document.getElementById('balance').className = `text-xl font-bold ${balance === 0 ? 'text-green-600' : 'text-red-600'}`;
}

document.addEventListener('DOMContentLoaded', function() {
    addLine();
    addLine();
});
</script>
@endsection



