@extends('layouts.app')

@section('content')
<div class="space-y-6">
    <!-- Header Block -->
    <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
            <h1 class="text-xl font-bold tracking-tight text-slate-900 md:text-2xl">📖 কর্পোরেট হিসাব খাত ও লেজার বুক (General Ledger Registry)</h1>
            <p class="text-xs text-slate-500 font-medium">কোম্পানির বাস্তব লেজার অ্যাকাউন্ট খতিয়ান, লেনদেনের ধরন ভিত্তিক সারসংক্ষেপ এবং সর্বমোট সমন্বয় ট্র্যাকার।</p>
        </div>
        <div>
            <button onclick="window.print()" class="bg-slate-900 hover:bg-slate-800 text-white font-extrabold text-xs px-4 py-2.5 rounded-xl flex items-center gap-2 shadow-sm transition">
                🖨️ লেজার প্রিন্ট বা পিডিএফ (Export to Print)
            </button>
        </div>
    </div>

    <!-- Category Balance Bento Grid -->
    <div class="bg-white border border-slate-200 rounded-3xl p-6 shadow-sm">
        <h3 class="text-xs font-black uppercase text-slate-400 tracking-wider mb-4">📈 খাত ভিত্তিক অনুমোদিত ব্যালেন্স সামারি (Approved Category Accumulations)</h3>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            @forelse($categorySummaries as $summary)
                <div class="bg-slate-50 border border-slate-100 rounded-2xl p-4 flex flex-col justify-between">
                    <div>
                        <span class="text-[9px] font-black uppercase {{ $summary->type === 'Cash In' ? 'bg-emerald-50 text-emerald-700' : 'bg-rose-50 text-rose-700' }} px-2 py-0.5 rounded-md">
                            {{ $summary->type === 'Cash In' ? 'প্রাপ্তি / Cash In' : 'প্রদান / Cash Out' }}
                        </span>
                        <h4 class="text-xs font-extrabold text-slate-700 mt-2 truncate" title="{{ $summary->category }}">{{ $summary->category }}</h4>
                    </div>
                    <div class="mt-4">
                        <span class="text-[9px] text-slate-400 font-semibold block uppercase">মোট ভলিউম</span>
                        <span class="text-base font-black font-mono {{ $summary->type === 'Cash In' ? 'text-emerald-600' : 'text-rose-600' }}">৳{{ number_format($summary->total_amount, 2) }}</span>
                    </div>
                </div>
            @empty
                <div class="col-span-full py-6 text-center text-slate-400 text-xs">কোনো লেজার ক্যাটাগরি ডাটা পাওয়া যায়নি।</div>
            @endforelse
        </div>
    </div>

    <!-- Live Filters Panel -->
    <div class="bg-white border border-slate-200 rounded-3xl p-5 shadow-sm print:hidden">
        <form action="{{ route('ledgers.index') }}" method="GET" class="grid grid-cols-1 md:grid-cols-4 gap-4 text-xs font-bold text-slate-600">
            <div>
                <label class="block text-[11px] text-slate-400 mb-1.5 uppercase tracking-wider">হিসাবের খাত (Category)</label>
                <select name="category" class="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2.5 text-slate-750 focus:outline-none focus:ring-1 focus:ring-blue-500">
                    <option value="">সকল খাত (All Categories)</option>
                    @foreach($categories as $cat)
                        <option value="{{ $cat }}" {{ request('category') === $cat ? 'selected' : '' }}>{{ $cat }}</option>
                    @endforeach
                </select>
            </div>
            <div>
                <label class="block text-[11px] text-slate-400 mb-1.5 uppercase tracking-wider">পেমেন্ট সোর্স</label>
                <select name="payment_method" class="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2.5 text-slate-750 focus:outline-none focus:ring-1 focus:ring-blue-500">
                    <option value="">সকল মেথড</option>
                    <option value="Cash" {{ request('payment_method') === 'Cash' ? 'selected' : '' }}>Cash Drawer (ক্যাশ)</option>
                    <option value="Bank" {{ request('payment_method') === 'Bank' ? 'selected' : '' }}>Bank Account (ব্যাংক)</option>
                    <option value="Cheque" {{ request('payment_method') === 'Cheque' ? 'selected' : '' }}>Cheque (চেক)</option>
                </select>
            </div>
            <div>
                <label class="block text-[11px] text-slate-400 mb-1.5 uppercase tracking-wider">শুরুর তারিখ</label>
                <input type="date" name="start_date" value="{{ request('start_date') }}" class="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-2 focus:outline-none focus:ring-1 focus:ring-blue-500">
            </div>
            <div>
                <label class="block text-[11px] text-slate-400 mb-1.5 uppercase tracking-wider">শেষের তারিখ</label>
                <div class="flex gap-2">
                    <input type="date" name="end_date" value="{{ request('end_date') }}" class="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-2 focus:outline-none focus:ring-1 focus:ring-blue-500">
                    <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white px-5 rounded-xl font-bold transition">🔍</button>
                    <a href="{{ route('ledgers.index') }}" class="bg-slate-100 hover:bg-slate-200 text-slate-600 px-3.5 py-2.5 rounded-xl font-extrabold flex items-center justify-center transition">🔄</a>
                </div>
            </div>
        </form>
    </div>

    <!-- General Ledger Details Table -->
    <div class="bg-white border border-slate-200 rounded-3xl p-6 shadow-sm overflow-hidden">
        <h3 class="text-sm font-extrabold text-slate-800 pb-4 mb-4 border-b border-slate-100">📋 বিস্তারিত লেজার পোস্টিং রিকোর্ডস (Ledger Book Logs)</h3>
        <div class="overflow-x-auto">
            <table class="w-full text-xs font-medium text-slate-700">
                <thead>
                    <tr class="text-left text-[11px] text-slate-400 font-bold border-b border-slate-100 uppercase tracking-wider">
                        <th class="py-3 px-4">আইডি ও তারিখ</th>
                        <th class="py-3 px-4">খাত ও বিবরণ বিবরণী</th>
                        <th class="py-3 px-4">পেমেন্ট মেথড</th>
                        <th class="py-3 px-4">টাইপ</th>
                        <th class="py-3 px-4">স্ট্যাটাস</th>
                        <th class="py-3 px-4 text-right">পরিমাণ (Amount)</th>
                        @if(Auth::user()->isSuperAdmin())
                            <th class="py-3 px-4 text-center print:hidden">কন্ট্রোল</th>
                        @endif
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    @forelse($transactions as $tx)
                        <tr class="hover:bg-slate-50/50 transition">
                            <td class="py-4 px-4 font-mono font-bold">
                                <span class="block text-slate-800">{{ $tx->voucher_no }}</span>
                                <span class="text-[9px] text-slate-400 font-normal block mt-1">{{ $tx->created_at->format('Y-m-d H:i') }}</span>
                            </td>
                            <td class="py-4 px-4">
                                <div class="font-extrabold text-slate-800">{{ $tx->category }}</div>
                                <p class="text-slate-500 mt-1 max-w-[300px] truncate-3-lines" title="{{ $tx->particulars }}">{{ $tx->particulars }}</p>
                                <span class="text-[9px] font-normal text-slate-400 mt-1 block">প্রস্তুতকারীঃ {{ $tx->created_by_name }}</span>
                            </td>
                            <td class="py-4 px-4 font-bold text-slate-600 font-mono">
                                {{ $tx->payment_method }}
                            </td>
                            <td class="py-4 px-4">
                                <span class="px-2 py-0.5 rounded text-[9px] font-bold uppercase {{ $tx->type === 'Cash In' ? 'bg-emerald-50 text-emerald-700 border border-emerald-100' : 'bg-rose-50 text-rose-700 border border-rose-100' }}">
                                    {{ $tx->type }}
                                </span>
                            </td>
                            <td class="py-4 px-4">
                                <span class="px-2 py-0.5 rounded-full text-[9px] font-black uppercase {{ $tx->status === 'Approved' ? 'bg-emerald-50 text-emerald-700' : ($tx->status === 'Rejected' ? 'bg-rose-50 text-rose-700' : 'bg-amber-50 text-amber-700') }}">
                                    {{ $tx->status }}
                                </span>
                            </td>
                            <td class="py-4 px-4 text-right">
                                <span class="font-mono font-black text-sm {{ $tx->type === 'Cash In' ? 'text-emerald-600' : 'text-rose-600' }}">
                                    ৳{{ number_format($tx->amount, 2) }}
                                </span>
                            </td>
                            @if(Auth::user()->isSuperAdmin())
                                <td class="py-4 px-4 text-center print:hidden">
                                    <div class="flex items-center justify-center gap-1.5">
                                        <!-- Edit trigger -->
                                        <button 
                                            onclick="openEditVoucherModal(this)"
                                            data-id="{{ $tx->id }}"
                                            data-voucher-no="{{ $tx->voucher_no }}"
                                            data-type="{{ $tx->type }}"
                                            data-amount="{{ $tx->amount }}"
                                            data-category="{{ $tx->category }}"
                                            data-particulars="{{ $tx->particulars }}"
                                            data-payment-method="{{ $tx->payment_method }}"
                                            data-bank-account-id="{{ $tx->bank_account_id }}"
                                            data-reference-no="{{ $tx->reference_no }}"
                                            data-status="{{ $tx->status }}"
                                            class="bg-indigo-600 hover:bg-indigo-700 text-white font-extrabold text-[10px] px-2.5 py-1.5 rounded-lg shadow-sm cursor-pointer whitespace-nowrap"
                                        >
                                            ✏️ এডিট
                                        </button>

                                        <!-- Delete form -->
                                        <form action="{{ route('superadmin.vouchers.delete', $tx->id) }}" method="POST" onsubmit="return confirm('এই ভাউচারটি কি সম্পূর্ণ ডিলিট করতে চান? ডিলিট করলে এর আর্থিক প্রভাব উল্টানো হবে।');" class="inline">
                                            @csrf
                                            @method('DELETE')
                                            <button type="submit" class="bg-rose-600 hover:bg-rose-700 text-white font-extrabold text-[10px] px-2.5 py-1.5 rounded-lg shadow-sm whitespace-nowrap">
                                                🗑️ ডিলিট
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            @endif
                        </tr>
                    @empty
                        <tr>
                            <td colspan="{{ Auth::user()->isSuperAdmin() ? 7 : 6 }}" class="py-12 text-center text-slate-400 font-bold">ফিল্টার মানদণ্ডে কোনো হিসাব বা ভাউচার লেজার পাওয়া যায়নি।</td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        <div class="mt-4">
            {{ $transactions->links() }}
        </div>
    </div>
</div>

@if(Auth::user()->isSuperAdmin())
<!-- Edit Voucher Modal for Super Admin -->
<div id="edit-voucher-modal" class="hidden fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4">
    <div class="bg-white rounded-3xl border border-slate-200 shadow-xl overflow-hidden max-w-lg w-full flex flex-col relative animate-in fade-in zoom-in-95 duration-200">
        <div class="p-5 border-b border-slate-100 flex items-center justify-between bg-slate-50 text-xs text-left">
            <h3 class="text-xs font-black uppercase tracking-wider text-slate-700 flex items-center gap-2">
                <span>✏️</span> ভাউচার সংশোধন ও এডিট (Edit Ledger Voucher)
            </h3>
            <button onclick="closeEditVoucherModal()" class="text-slate-400 hover:text-slate-700 font-bold text-sm">✖</button>
        </div>
        <form id="editVoucherForm" action="" method="POST" class="p-5 space-y-4 text-xs font-bold text-slate-600 text-left">
            @csrf
            
            <div class="bg-indigo-50/55 border border-indigo-100 rounded-xl p-3 mb-2 flex justify-between items-center">
                <span class="text-indigo-800">ভাউচার নম্বর:</span>
                <span id="editVoucherNoLabel" class="font-mono text-slate-900 font-black tracking-wider w-max">VCH-XXXX</span>
            </div>

            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block mb-1.5">লেনদেনের ধরণ *</label>
                    <select name="type" id="editVoucherType" required class="w-full bg-slate-50 border border-slate-200 rounded-xl p-2.5 font-bold focus:ring-1 focus:ring-indigo-500">
                        <option value="Cash In">Cash In (প্রাপ্তি)</option>
                        <option value="Cash Out">Cash Out (পরিশোধ)</option>
                    </select>
                </div>
                <div>
                    <label class="block mb-1.5">টাকার পরিমাণ (BDT) *</label>
                    <input type="number" step="0.01" name="amount" id="editVoucherAmount" required min="1" class="w-full bg-slate-50 border border-slate-200 rounded-xl p-2.5 font-mono font-bold focus:ring-1 focus:ring-indigo-500">
                </div>
            </div>

            <div>
                <label class="block mb-1.5">হিসাবের খাত (Category) *</label>
                <select name="category" id="editVoucherCategory" required class="w-full bg-slate-50 border border-slate-200 rounded-xl p-2.5 focus:ring-1 focus:ring-indigo-500">
                    @php
                        $userCompId = auth()->user()->company_id;
                        $editModalAllCats = \App\Models\Category::getExpenseCategories($userCompId)->merge(\App\Models\Category::getIncomeCategories($userCompId));
                    @endphp
                    @foreach($editModalAllCats as $catName)
                        <option value="{{ $catName }}">{{ $catName }}</option>
                    @endforeach
                </select>
            </div>

            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block mb-1.5">পেমেন্ট মেথড *</label>
                    <select name="payment_method" id="editVoucherPaymentMethod" onchange="toggleEditVoucherBankSelect(this.value)" required class="w-full bg-slate-50 border border-slate-200 rounded-xl p-2.5 focus:ring-1 focus:ring-indigo-500">
                        <option value="Cash">Cash (নগদ)</option>
                        <option value="Bank">Bank (ব্যাংক ট্রান্সফার)</option>
                        <option value="Cheque">Cheque (চেক)</option>
                    </select>
                </div>
                <div>
                    <label class="block mb-1.5">রেফারেন্স নং / মেমো</label>
                    <input type="text" name="reference_no" id="editVoucherReferenceNo" class="w-full bg-slate-50 border border-slate-200 rounded-xl p-2.5 font-mono focus:ring-1 focus:ring-indigo-500">
                </div>
            </div>

            @php
                $editModalBankAccounts = \App\Models\BankAccount::where('company_id', $userCompId)->where('status', 'Active')->get();
            @endphp
            <div id="editVoucherBankSelectDiv" class="hidden">
                <label class="block mb-1.5">ব্যাংক অ্যাকাউন্ট *</label>
                <select name="bank_account_id" id="editVoucherBankAccountId" class="w-full bg-slate-50 border border-slate-200 rounded-xl p-2.5 focus:ring-1 focus:ring-indigo-500">
                    <option value="">-- অ্যাকাউন্ট নির্বাচন করুন --</option>
                    @foreach($editModalBankAccounts as $b)
                        <option value="{{ $b->id }}">{{ $b->bank_name }} - ({{ $b->account_number }})</option>
                    @endforeach
                </select>
            </div>

            <div>
                <label class="block mb-1.5">অডিট স্ট্যাটাস (Status) *</label>
                <select name="status" id="editVoucherStatus" required class="w-full bg-slate-50 border border-slate-200 rounded-xl p-2.5 focus:ring-1 focus:ring-indigo-500">
                    <option value="Pending">Pending (অপেক্ষমান)</option>
                    <option value="Approved">Approved (অনুমোদিত)</option>
                    <option value="Rejected">Rejected (প্রত্যাখ্যাত)</option>
                </select>
            </div>

            <div>
                <label class="block mb-1.5">লেনদেনের বিবরণ (Particulars) *</label>
                <textarea name="particulars" id="editVoucherParticulars" rows="3" required class="w-full bg-slate-50 border border-slate-200 rounded-xl p-2.5 font-normal text-slate-800 focus:ring-1 focus:ring-indigo-500"></textarea>
            </div>

            <div class="pt-2 border-t border-slate-100 flex items-center justify-end gap-3 font-bold text-xs">
                <button type="button" onclick="closeEditVoucherModal()" class="bg-slate-100 text-slate-700 px-4 py-2.5 rounded-xl hover:bg-slate-200 transition">
                    বাতিল (Close)
                </button>
                <button type="submit" class="bg-indigo-600 text-white px-5 py-2.5 rounded-xl hover:bg-indigo-700 shadow-md shadow-indigo-500/10">
                    পরিবর্তন সংরক্ষণ করুন
                </button>
            </div>
        </form>
    </div>
</div>

<script>
    function openEditVoucherModal(button) {
        const id = button.getAttribute('data-id');
        const voucherNo = button.getAttribute('data-voucher-no');
        const type = button.getAttribute('data-type');
        const amount = button.getAttribute('data-amount');
        const category = button.getAttribute('data-category');
        const particulars = button.getAttribute('data-particulars');
        const paymentMethod = button.getAttribute('data-payment-method');
        const bankAccountId = button.getAttribute('data-bank-account-id');
        const referenceNo = button.getAttribute('data-reference-no');
        const status = button.getAttribute('data-status');

        document.getElementById('editVoucherForm').action = `/admin/vouchers/${id}/update`;
        document.getElementById('editVoucherNoLabel').innerText = voucherNo;
        document.getElementById('editVoucherType').value = type;
        document.getElementById('editVoucherAmount').value = amount;
        document.getElementById('editVoucherCategory').value = category;
        document.getElementById('editVoucherParticulars').value = particulars;
        document.getElementById('editVoucherPaymentMethod').value = paymentMethod;
        document.getElementById('editVoucherReferenceNo').value = referenceNo || '';
        document.getElementById('editVoucherStatus').value = status;

        if (paymentMethod === 'Bank') {
            document.getElementById('editVoucherBankSelectDiv').classList.remove('hidden');
            document.getElementById('editVoucherBankAccountId').value = bankAccountId || '';
            document.getElementById('editVoucherBankAccountId').required = true;
        } else {
            document.getElementById('editVoucherBankSelectDiv').classList.add('hidden');
            document.getElementById('editVoucherBankAccountId').value = '';
            document.getElementById('editVoucherBankAccountId').required = false;
        }

        document.getElementById('edit-voucher-modal').classList.remove('hidden');
    }

    function closeEditVoucherModal() {
        document.getElementById('edit-voucher-modal').classList.add('hidden');
    }

    function toggleEditVoucherBankSelect(method) {
        const bankDiv = document.getElementById('editVoucherBankSelectDiv');
        const bankAccountSelect = document.getElementById('editVoucherBankAccountId');
        if (method === 'Bank') {
            bankDiv.classList.remove('hidden');
            bankAccountSelect.required = true;
        } else {
            bankDiv.classList.add('hidden');
            bankAccountSelect.value = '';
            bankAccountSelect.required = false;
        }
    }
</script>
@endif
@endsection
