@extends('layouts.aura-main')

@section('main-content')
<div x-data="{ 
    openModal: false, 
    deleteModal: false,
    errorModal: {{ $errors->any() ? 'true' : 'false' }},
    editMode: false,
    loading: false,
    uploading: false,
    searchQuery: '', 
    filterCategory: 'all',
    
    // Form Data
    accountId: '',
    accountCode: '',
    accountName: '',
    typeId: '',
    isActive: 1,
    actionUrl: '',

    setEdit(account) {
        this.editMode = true;
        this.accountId = account.id;
        this.accountCode = account.code;
        this.accountName = account.name;
        this.typeId = account.account_type_id;
        this.isActive = account.is_active;
        this.actionUrl = '{{ url('accounting/accounts') }}/' + account.id;
        this.openModal = true;
    },

    setCreate() {
        this.editMode = false;
        this.accountId = '';
        this.accountCode = '';
        this.accountName = '';
        this.typeId = '';
        this.isActive = 1;
        this.actionUrl = '{{ route('accounting.accounts.store') }}';
        this.openModal = true;
    },

    confirmDelete(account) {
        this.accountId = account.id;
        this.accountName = account.name;
        this.deleteModal = true;
    },

    matchesSearch(code, name, categoryId) {
        const query = this.searchQuery.toLowerCase();
        const matchesText = code.toLowerCase().includes(query) || name.toLowerCase().includes(query);
        const matchesCat = this.filterCategory === 'all' || categoryId == this.filterCategory;
        return matchesText && matchesCat;
    }
}">
    <div class="mb-6 flex flex-col lg:flex-row justify-between items-start lg:items-end gap-4">
        <div>
            <h1 class="text-lg font-bold text-slate-900 leading-tight">Chart of Accounts</h1>
            <p class="text-slate-500 text-[11px] font-medium uppercase tracking-widest text-indigo-600">General Ledger Structure</p>
        </div>
        
        <div class="flex flex-wrap items-center gap-3 w-full lg:w-auto">
            <div class="flex items-center bg-slate-100 rounded-lg p-1 border border-slate-200">
                <a href="{{ route('accounting.accounts.template') }}" 
                   class="text-[10px] font-bold text-slate-600 hover:text-indigo-600 px-3 py-1 transition flex items-center gap-1">
                    <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0L8 8m4-4v12" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg>
                    Template
                </a>
                <div class="w-px h-4 bg-slate-200"></div>
                <form action="{{ route('accounting.accounts.import') }}" method="POST" enctype="multipart/form-data" class="inline-flex">
                    @csrf
                    <input type="file" name="file" id="fileInput" class="hidden" @change="uploading = true; $el.form.submit()">
                    <button type="button" @click="document.getElementById('fileInput').click()" 
                            class="text-[10px] font-bold text-indigo-600 hover:text-indigo-800 px-3 py-1 transition flex items-center gap-2">
                        <span x-show="!uploading" class="flex items-center gap-1">
                            <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M9 11l3-3m0 0l3 3m-3-3v8m0-13a9 9 0 110 18 9 9 0 010-18z" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg>
                            Import
                        </span>
                        <span x-show="uploading" class="animate-spin h-3 w-3 border-2 border-indigo-600 border-t-transparent rounded-full"></span>
                    </button>
                </form>
            </div>

            <select x-model="filterCategory" class="bg-white border border-slate-200 rounded px-3 py-1.5 text-xs outline-none focus:border-indigo-500 shadow-sm font-medium">
                <option value="all">All Primary Categories</option>
                @foreach($categories as $category)
                    <option value="{{ $category->id }}">{{ $category->name }}</option>
                @endforeach
            </select>

            <div class="relative flex-grow lg:w-64">
                <span class="absolute inset-y-0 left-0 pl-3 flex items-center text-slate-400">
                    <svg class="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg>
                </span>
                <input type="text" x-model="searchQuery" placeholder="Search code or name..." class="w-full bg-white border border-slate-200 rounded px-3 py-1.5 pl-9 text-xs outline-none focus:border-indigo-500 transition shadow-sm">
            </div>
            
            <button @click="setCreate()" class="bg-indigo-600 text-white px-4 py-1.5 rounded text-[11px] font-bold shadow-sm hover:bg-indigo-700 transition">
                + New Account
            </button>
        </div>
    </div>

    <div class="bg-white border border-slate-200 rounded shadow-sm overflow-hidden">
        <table class="w-full text-left border-collapse">
            <thead class="bg-slate-50 border-b border-slate-200">
                <tr>
                    <th class="px-4 py-2 text-[10px] font-bold uppercase text-slate-400 w-24 text-center">Code</th>
                    <th class="px-4 py-2 text-[10px] font-bold uppercase text-slate-400">Account Name</th>
                    <th class="px-4 py-2 text-[10px] font-bold uppercase text-slate-400">Classification</th>
                    <th class="px-4 py-2 text-[10px] font-bold uppercase text-slate-400">Status</th>
                    <th class="px-4 py-2 text-[10px] font-bold uppercase text-slate-400 text-right">Actions</th>
                </tr>
            </thead>
            <tbody class="text-xs">
                @forelse($accounts as $account)
                <tr x-show="matchesSearch('{{ $account->code }}', '{{ $account->name }}', '{{ $account->type->group->primary_category_id ?? 0 }}')" 
                    class="border-b border-slate-100 hover:bg-slate-50/50 transition" x-cloak x-transition.opacity>
                    <td class="px-4 py-2 font-mono text-indigo-600 font-bold tracking-tight text-center">{{ $account->code }}</td>
                    <td class="px-4 py-2 font-semibold text-slate-700">{{ $account->name }}</td>
                    <td class="px-4 py-2">
                        <div class="flex flex-col leading-tight">
                            <span class="text-slate-600 font-medium">{{ $account->type->name }}</span>
                            <span class="text-[9px] text-slate-400 uppercase font-bold tracking-tighter">{{ $account->type->group->name }}</span>
                        </div>
                    </td>
                    <td class="px-4 py-2 text-center">
                        <span class="px-2 py-0.5 rounded-full {{ $account->is_active ? 'bg-green-50 text-green-600' : 'bg-slate-100 text-slate-400' }} font-bold text-[9px] uppercase">
                            {{ $account->is_active ? 'Active' : 'Archived' }}
                        </span>
                    </td>
                    <td class="px-4 py-2 text-right flex justify-end gap-3">
                        <button @click="setEdit({ 
                            id: '{{ $account->id }}', 
                            code: '{{ $account->code }}', 
                            name: '{{ addslashes($account->name) }}', 
                            account_type_id: '{{ $account->account_type_id }}', 
                            is_active: {{ $account->is_active }} 
                        })" class="text-indigo-600 hover:underline">Edit</button>
                        
                        <button @click="confirmDelete({ id: '{{ $account->id }}', name: '{{ addslashes($account->name) }}' })" 
                                class="text-red-400 hover:text-red-600">Delete</button>
                    </td>
                </tr>
                @empty
                <tr><td colspan="5" class="px-4 py-12 text-center text-slate-400 italic">No ledger accounts found.</td></tr>
                @endforelse
            </tbody>
        </table>
    </div>

    <div x-show="openModal" class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40 backdrop-blur-sm" x-cloak x-transition>
        <div class="bg-white rounded shadow-xl w-full max-w-md p-6 border border-slate-200">
            <h2 class="text-sm font-bold text-slate-900 mb-4" x-text="editMode ? 'Edit Ledger Account' : 'New Ledger Account'"></h2>
            
            <form :action="actionUrl" method="POST" @submit="loading = true">
                @csrf
                <template x-if="editMode"><input type="hidden" name="_method" value="PUT"></template>

                <div class="space-y-4">
                    <div class="grid grid-cols-3 gap-3">
                        <div class="col-span-1">
                            <label class="block text-[10px] font-bold text-slate-400 uppercase mb-1 tracking-wider">Account Code</label>
                            <input type="text" name="code" x-model="accountCode" class="w-full bg-slate-50 border border-slate-200 rounded px-3 py-2 text-xs outline-none focus:border-indigo-500" placeholder="e.g. 5030" required>
                        </div>
                        <div class="col-span-2">
                            <label class="block text-[10px] font-bold text-slate-400 uppercase mb-1 tracking-wider">Account Name</label>
                            <input type="text" name="name" x-model="accountName" class="w-full bg-slate-50 border border-slate-200 rounded px-3 py-2 text-xs outline-none focus:border-indigo-500" placeholder="e.g. Internet Expenses" required>
                        </div>
                    </div>

                    <div>
                        <label class="block text-[10px] font-bold text-slate-400 uppercase mb-1 tracking-wider">Account Type (Blueprint)</label>
                        <select name="account_type_id" x-model="typeId" class="w-full bg-slate-50 border border-slate-200 rounded px-3 py-2 text-xs outline-none focus:border-indigo-500" required>
                            <option value="">Choose a type...</option>
                            @foreach($types as $type)
                                <option value="{{ $type->id }}">{{ $type->name }} ({{ $type->group->name }})</option>
                            @endforeach
                        </select>
                    </div>

                    <div class="flex items-center gap-2 py-2">
                        <input type="checkbox" name="is_active" id="isActive" value="1" x-model="isActive" class="rounded border-slate-300 text-indigo-600">
                        <label for="isActive" class="text-xs font-medium text-slate-600">Active and available for posting</label>
                    </div>
                </div>

                <div class="flex justify-end gap-2 pt-4 mt-6 border-t border-slate-100">
                    <button type="button" @click="openModal = false" class="text-[11px] font-bold text-slate-400 px-4 py-2 hover:text-slate-600">Cancel</button>
                    <button type="submit" :disabled="loading" class="bg-indigo-600 text-white text-[11px] font-bold px-5 py-2 rounded shadow-sm hover:bg-indigo-700 flex items-center gap-2 transition-all">
                        <span x-text="loading ? 'Processing...' : 'Save Account'"></span>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <div x-show="deleteModal" class="fixed inset-0 z-[60] flex items-center justify-center bg-slate-900/60 backdrop-blur-sm" x-cloak x-transition>
        <div class="bg-white rounded-lg shadow-2xl w-full max-sm p-6 border border-slate-200 text-center">
            <div class="w-12 h-12 rounded-full bg-red-50 text-red-500 flex items-center justify-center mx-auto mb-4">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 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"></path></svg>
            </div>
            <h3 class="text-sm font-bold text-slate-900 mb-2">Delete <span x-text="accountName"></span>?</h3>
            <p class="text-slate-500 text-[11px] mb-6 leading-relaxed px-4">This action cannot be undone. If this account has existing transactions, the deletion will be blocked by the system.</p>
            <div class="flex flex-col gap-2">
                <form :action="'{{ url('accounting/accounts') }}/' + accountId" method="POST">
                    @csrf @method('DELETE')
                    <button type="submit" class="w-full bg-red-500 text-white text-[11px] font-bold py-2.5 rounded shadow-sm hover:bg-red-600 transition">Confirm Delete</button>
                </form>
                <button type="button" @click="deleteModal = false" class="w-full text-slate-400 text-[11px] font-bold py-2 hover:text-slate-600">Nevermind, Go Back</button>
            </div>
        </div>
    </div>

    <div x-show="errorModal" class="fixed inset-0 z-[70] flex items-center justify-center bg-slate-900/60 backdrop-blur-sm" x-cloak x-transition>
        <div class="bg-white rounded-lg shadow-2xl w-full max-w-md p-6 border border-slate-200" @click.away="errorModal = false">
            <div class="w-12 h-12 rounded-full bg-red-50 text-red-500 flex items-center justify-center mx-auto mb-4">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path></svg>
            </div>
            <h3 class="text-sm font-bold text-slate-900 text-center mb-2 uppercase tracking-tight">Import Blocked</h3>
            <p class="text-slate-500 text-[10px] text-center mb-4 leading-relaxed">The entire file was rejected. No changes were made to the database. Fix these issues and re-upload:</p>
            
            <div class="max-h-48 overflow-y-auto bg-red-50/50 rounded-lg border border-red-100 p-3 mb-6">
                <ul class="space-y-2">
                    @foreach($errors->all() as $error)
                        <li class="flex gap-2 text-[10px] text-red-600 leading-tight">
                            <span class="font-bold">•</span>
                            <span>{{ $error }}</span>
                        </li>
                    @endforeach
                </ul>
            </div>

            <button type="button" @click="errorModal = false" class="w-full bg-slate-900 text-white text-[11px] font-bold py-2.5 rounded shadow-sm hover:bg-slate-800 transition">
                I'll Fix the File
            </button>
        </div>
    </div>
</div>
@endsection