<?php if (isset($component)) { $__componentOriginal9ac128a9029c0e4701924bd2d73d7f54 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54 = $attributes; } ?>
<?php $component = App\View\Components\AppLayout::resolve([] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('app-layout'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\App\View\Components\AppLayout::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes([]); ?>
    <div class="flex flex-col md:flex-row md:items-center justify-between mb-6 md:mb-8 gap-4 md:gap-0">
        <div class="flex items-center gap-3 md:gap-4">
            <div class="header-icon-size ios-icon-container shadow-lg flex items-center justify-center">
                <img src="<?php echo e(asset('uploads/dashboard-icons/Expenses.jpg')); ?>" alt="Expenses" class="w-full h-full object-cover">
            </div>
            <div>
                <h2 class="text-2xl font-bold text-slate-800">Expenses Log</h2>
                <p class="text-slate-500 text-xs mt-1">Record business outgoings, purchases, utility bills, and operations.</p>
            </div>
        </div>
        <?php if(!auth()->user()->isAccountant()): ?>
        <div class="mt-4 md:mt-0 flex space-x-3" x-data="">
            <button @click="$dispatch('open-category-modal')" class="inline-flex items-center justify-center py-2.5 px-4 bg-black hover:bg-slate-800 text-white text-sm font-semibold rounded-xl border border-slate-200 transition duration-150">
                📁 Manage Categories
            </button>
            <a href="<?php echo e(route('expenses.create')); ?>" class="inline-flex items-center justify-center py-2.5 px-5 bg-brand-500 hover:bg-brand-600 text-white text-sm font-semibold rounded-xl shadow-sm transition duration-150">
                <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M12 4v16m8-8H4"></path>
                </svg>
                Add New Expense
            </a>
        </div>
        <?php endif; ?>
    </div>

    <!-- Filters Section -->
    <div x-data="{ openFilter: false }" class="bg-white border border-slate-200 rounded-2xl p-4 mb-4 md:mb-6">
        <div class="flex items-center justify-between md:hidden cursor-pointer" @click="openFilter = !openFilter">
            <div class="flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-600">
                <svg class="w-4 h-4 text-brand-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"></path></svg>
                <span>Filter Records</span>
            </div>
            <svg class="w-4 h-4 text-slate-500 transition-transform duration-200" :class="{'rotate-180': openFilter}" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M19 9l-7 7-7-7"></path></svg>
        </div>

        <form action="<?php echo e(route('expenses.index')); ?>" method="GET"
              class="grid grid-cols-1 md:grid-cols-4 gap-4 items-end mt-4 md:mt-0"
              x-show="true"
              :class="{'hidden': !openFilter, 'md:grid': true}">
            <div>
                <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">Date From</label>
                <input type="date" name="date_from" value="<?php echo e($dateFrom); ?>"
                    class="w-full py-2 px-3 bg-white border border-slate-300 focus:border-brand-500 focus:ring-0 rounded-xl text-slate-700 text-sm focus:outline-none transition duration-150">
            </div>

            <div>
                <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">Date To</label>
                <input type="date" name="date_to" value="<?php echo e($dateTo); ?>"
                    class="w-full py-2 px-3 bg-white border border-slate-300 focus:border-brand-500 focus:ring-0 rounded-xl text-slate-700 text-sm focus:outline-none transition duration-150">
            </div>

            <div>
                <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">Category</label>
                <select name="category_id"
                    class="w-full py-2 px-3 bg-white border border-slate-300 focus:border-brand-500 focus:ring-0 rounded-xl text-slate-700 text-sm focus:outline-none transition duration-150">
                    <option value="">All Categories</option>
                    <?php $__currentLoopData = $parentCategories; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $parent): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <option value="<?php echo e($parent->id); ?>" <?php echo e($categoryId == $parent->id ? 'selected' : ''); ?> class="font-bold text-slate-500"><?php echo e($parent->name); ?></option>
                        <?php $__currentLoopData = $parent->children; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $child): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($child->id); ?>" <?php echo e($categoryId == $child->id ? 'selected' : ''); ?>>&nbsp;&nbsp;&mdash;&nbsp;<?php echo e($child->name); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </select>
            </div>

            <div class="flex gap-2">
                <button type="submit" class="flex-1 py-2.5 px-4 bg-brand-500 hover:bg-brand-600 text-white font-semibold rounded-xl text-sm transition duration-150">
                    Filter
                </button>
                <?php if($dateFrom || $dateTo || $categoryId || $search): ?>
                    <a href="<?php echo e(route('expenses.index')); ?>" class="py-2.5 px-3 bg-red-50 hover:bg-red-100 text-red-600 rounded-xl text-sm border border-red-200 transition duration-150">
                        Reset
                    </a>
                <?php endif; ?>
            </div>
        </form>
    </div>

    <!-- Summary Box -->
    <div class="flex justify-between items-center mb-6 bg-white border border-slate-200 rounded-xl p-4">
        <span class="text-xs text-slate-500 font-semibold uppercase tracking-wider">Filtered Expenses Total:</span>
        <span class="text-lg md:text-xl font-bold text-rose-650 font-mono text-red-600"><?php echo e($currencySymbol); ?><?php echo e(number_format($totalExpense, 2)); ?></span>
    </div>

    <!-- Data Table Registry -->
    <div class="bg-white border border-slate-200 rounded-xl shadow-sm p-5 overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full text-left text-sm border-collapse">
                <thead>
                    <tr class="border-b border-slate-200 text-slate-400 text-xs uppercase tracking-wider">
                        <th class="pb-3 font-semibold">Date</th>
                        <th class="pb-3 font-semibold">Category</th>
                        <th class="pb-3 font-semibold">Payee</th>
                        <th class="pb-3 font-semibold">Paid From</th>
                        <th class="pb-3 font-semibold">Transaction ID</th>
                        <th class="pb-3 font-semibold text-right">Amount</th>
                        <th class="pb-3 font-semibold text-center">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-200 text-base">
                    <?php $__empty_1 = true; $__currentLoopData = $expenses; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $exp): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                        <tr class="hover:bg-slate-50">
                            <td class="py-3.5"><?php echo e($exp->date->format('d-m-Y')); ?></td>
                            <td class="py-3.5">
                                <?php if($exp->category): ?>
                                    <?php if($exp->category->parent): ?>
                                        <span class="text-slate-400 text-xs block"><?php echo e($exp->category->parent->name); ?></span>
                                    <?php endif; ?>
                                    <span class="font-medium text-slate-700"><?php echo e($exp->category->name); ?></span>
                                <?php else: ?>
                                    <span class="text-slate-400 italic">Uncategorized</span>
                                <?php endif; ?>
                            </td>
                            <td class="py-3.5 text-slate-700"><?php echo e($exp->payee_bank_name ?: '-'); ?></td>
                            <td class="py-3.5 text-slate-600"><?php echo e($exp->bankAccount ? $exp->bankAccount->name : '-'); ?></td>
                            <td class="py-3.5 font-mono text-xs text-slate-500"><?php echo e($exp->transaction_id ?? '-'); ?></td>
                            <td class="py-3.5 text-right font-mono text-rose-600 font-bold">
                                <?php if($exp->original_currency): ?>
                                    <span class="block text-xs text-slate-400 font-normal"><?php echo e(number_format($exp->original_amount, 2)); ?> <?php echo e($exp->original_currency); ?></span>
                                <?php endif; ?>
                                <span><?php echo e($currencySymbol); ?><?php echo e(number_format($exp->amount, 2)); ?></span>
                            </td>
                            <td class="py-3.5 text-center">
                                <div class="flex items-center justify-center space-x-2">
                                    <a href="<?php echo e(route('expenses.show', $exp->id)); ?>" class="text-black hover:text-slate-700 text-sm font-semibold">👁 View</a>
                                    <?php if(!auth()->user()->isAccountant()): ?>
                                    <a href="<?php echo e(route('expenses.edit', $exp->id)); ?>" class="text-brand-500 hover:text-brand-600 text-sm font-semibold">✏️ Edit</a>
                                    <?php endif; ?>
                                    <?php if(auth()->user()->isAdmin()): ?>
                                        <form action="<?php echo e(route('expenses.destroy', $exp->id)); ?>" method="POST" onsubmit="return confirm('Delete this record permanently?')">
                                            <?php echo csrf_field(); ?>
                                            <?php echo method_field('DELETE'); ?>
                                            <button type="submit" class="text-red-600 hover:text-red-500 text-sm font-semibold">🗑 Del</button>
                                        </form>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                        <tr>
                            <td colspan="7" class="py-12 text-center text-slate-400">No expense records logged.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <div class="mt-4 border-t border-slate-200 pt-4">
            <?php echo e($expenses->links()); ?>

        </div>
    </div>

    <!-- Inline Category Management Modal -->
    <div x-data="{ 
        open: false, 
        parents: [],
        newCategoryName: '',
        newParentId: '',
        saving: false,
        
        editingId: null,
        editingName: '',
        editingParentId: '',
        
        async fetchCategories() {
            try {
                let url = new URL('<?php echo e(route('expenses.categories.list')); ?>', window.location.origin);
                let res = await fetch(url.pathname + url.search);
                if (!res.ok) {
                    throw new Error('Server returned status: ' + res.status);
                }
                let data = await res.json();
                this.parents = data.categories;
            } catch(e) {
                console.error('Failed to fetch categories:', e);
                alert('Failed to load categories: ' + e.message);
            }
        },

        async saveCategory() {
            if(!this.newCategoryName) return;
            this.saving = true;
            try {
                let params = new URLSearchParams();
                params.append('name', this.newCategoryName);
                if(this.newParentId) params.append('parent_id', this.newParentId);
                params.append('_token', '<?php echo e(csrf_token()); ?>');
                
                let url = new URL('<?php echo e(route('expenses.categories.store-ajax')); ?>', window.location.origin);
                let res = await fetch(url.pathname + url.search, {
                    method: 'POST',
                    body: params,
                    headers: { 'Accept': 'application/json' }
                });
                if (!res.ok) {
                    throw new Error('Server returned status: ' + res.status);
                }
                this.newCategoryName = '';
                this.newParentId = '';
                await this.fetchCategories();
                alert('Category added successfully.');
            } catch(e) {
                console.error('Failed to save category:', e);
                alert('Failed to save category: ' + e.message);
            }
            finally { this.saving = false; }
        },

        startEdit(category) {
            this.editingId = category.id;
            this.editingName = category.name;
            this.editingParentId = category.parent_id || '';
        },

        async updateCategory(id) {
            if(!this.editingName) return;
            try {
                let params = new URLSearchParams();
                params.append('name', this.editingName);
                if(this.editingParentId) params.append('parent_id', this.editingParentId);
                params.append('_token', '<?php echo e(csrf_token()); ?>');
                
                let targetUrl = '<?php echo e(route('expenses.categories.update-ajax', ['category' => 'TEMP_ID'])); ?>'.replace('TEMP_ID', id);
                let url = new URL(targetUrl, window.location.origin);
                let res = await fetch(url.pathname + url.search, {
                    method: 'POST',
                    body: params,
                    headers: { 'Accept': 'application/json' }
                });
                if (!res.ok) {
                    throw new Error('Server returned status: ' + res.status);
                }
                this.editingId = null;
                await this.fetchCategories();
                alert('Category updated successfully.');
            } catch(e) {
                console.error('Failed to update category:', e);
                alert('Failed to update category: ' + e.message);
            }
        },

        async deleteCategory(id) {
            if(!confirm('Are you sure you want to delete this category? Any associated expenses will be uncategorized.')) return;
            try {
                let params = new URLSearchParams();
                params.append('_token', '<?php echo e(csrf_token()); ?>');
                
                let targetUrl = '<?php echo e(route('expenses.categories.destroy-ajax', ['id' => 'TEMP_ID'])); ?>'.replace('TEMP_ID', id);
                let url = new URL(targetUrl, window.location.origin);
                let res = await fetch(url.pathname + url.search, {
                    method: 'POST',
                    body: params,
                    headers: { 'Accept': 'application/json' }
                });
                if (!res.ok) {
                    throw new Error('Server returned status: ' + res.status);
                }
                await this.fetchCategories();
            } catch(e) {
                console.error('Failed to delete category:', e);
                alert('Failed to delete category: ' + e.message);
            }
        }
    }" x-on:open-category-modal.window="open = true; fetchCategories()" class="relative">
        <div x-show="open" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/40" @click.self="open = false">
            <div class="bg-white rounded-2xl shadow-2xl p-6 w-full max-w-3xl mx-4 max-h-[85vh] overflow-y-auto">
                <div class="flex items-center justify-between border-b border-slate-200 pb-3 mb-4">
                    <h3 class="text-lg font-bold text-slate-800">📂 Manage Expense Categories</h3>
                    <button @click="open = false" class="text-slate-400 hover:text-slate-600 text-2xl leading-none">&times;</button>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- Create Category -->
                    <div class="bg-slate-50 border border-slate-200 rounded-xl p-4 space-y-4 h-max">
                        <h4 class="text-sm font-semibold text-slate-700">Add New Category</h4>
                        <div class="space-y-3">
                            <div>
                                <label class="block text-xs font-semibold text-slate-600 mb-1">Category Name *</label>
                                <input type="text" x-model="newCategoryName" placeholder="e.g. Office Supplies"
                                    class="w-full py-2 px-3 border border-slate-300 rounded-xl text-sm focus:outline-none focus:border-brand-500">
                            </div>
                            <div>
                                <label class="block text-xs font-semibold text-slate-600 mb-1">Parent Category (optional)</label>
                                <select x-model="newParentId" class="w-full py-2 px-3 border border-slate-300 rounded-xl text-sm text-slate-700">
                                    <option value="">-- No Parent (Make Main Category) --</option>
                                    <template x-for="p in parents.filter(c => !c.parent_id)" :key="p.id">
                                        <option :value="p.id" x-text="p.name"></option>
                                    </template>
                                </select>
                            </div>
                            <button type="button" @click="saveCategory()" :disabled="saving || !newCategoryName"
                                class="w-full py-2 bg-brand-500 hover:bg-brand-600 disabled:opacity-55 text-white font-semibold rounded-xl text-sm transition">
                                <span x-text="saving ? 'Saving...' : 'Add Category'"></span>
                            </button>
                        </div>
                    </div>

                    <!-- Categories list -->
                    <div class="space-y-3">
                        <h4 class="text-sm font-semibold text-slate-700">Existing Categories</h4>
                        <div class="space-y-2 max-h-[45vh] overflow-y-auto pr-1">
                            <template x-for="p in parents" :key="p.id">
                                <div class="bg-white border border-slate-200 rounded-xl p-3 shadow-xs">
                                    <!-- View Mode -->
                                    <div x-show="editingId !== p.id" class="flex justify-between items-center">
                                        <span class="font-bold text-sm text-slate-800" :class="p.parent_id ? 'pl-4 text-slate-600 font-medium' : ''" x-text="p.parent_id ? '↳ ' + p.name : p.name"></span>
                                        <div class="flex items-center space-x-2">
                                            <button type="button" @click="startEdit(p)" class="text-brand-500 text-xs font-semibold hover:underline">Edit</button>
                                            <span class="text-slate-300">|</span>
                                            <button type="button" @click="deleteCategory(p.id)" class="text-rose-600 text-xs font-semibold hover:underline">Delete</button>
                                        </div>
                                    </div>
                                    
                                    <!-- Edit Mode -->
                                    <div x-show="editingId === p.id" class="space-y-3" x-cloak>
                                        <div>
                                            <label class="block text-xxs font-semibold text-slate-500 uppercase tracking-wider mb-1">Edit Category Name</label>
                                            <input type="text" x-model="editingName" class="w-full py-1 px-2 border border-slate-300 rounded-lg text-sm focus:outline-none focus:border-brand-500">
                                        </div>
                                        <div>
                                            <label class="block text-xxs font-semibold text-slate-500 uppercase tracking-wider mb-1">Parent Category</label>
                                            <select x-model="editingParentId" class="w-full py-1 px-2 border border-slate-300 rounded-lg text-sm text-slate-700">
                                                <option value="">-- No Parent (Make Main Category) --</option>
                                                <template x-for="parentOpt in parents.filter(c => !c.parent_id && c.id !== p.id)" :key="parentOpt.id">
                                                    <option :value="parentOpt.id" :selected="parentOpt.id == editingParentId" x-text="parentOpt.name"></option>
                                                </template>
                                            </select>
                                        </div>
                                        <div class="flex justify-end space-x-2 pt-1">
                                            <button type="button" @click="editingId = null" class="py-1 px-2.5 bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-semibold rounded-lg transition">Cancel</button>
                                            <button type="button" @click="updateCategory(p.id)" class="py-1 px-2.5 bg-brand-500 hover:bg-brand-600 text-white text-xs font-semibold rounded-lg transition">Save</button>
                                        </div>
                                    </div>
                                </div>
                            </template>
                            <div x-show="parents.length === 0" class="text-center py-6 text-slate-400 text-sm">No categories found.</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
 <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54)): ?>
<?php $attributes = $__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54; ?>
<?php unset($__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal9ac128a9029c0e4701924bd2d73d7f54)): ?>
<?php $component = $__componentOriginal9ac128a9029c0e4701924bd2d73d7f54; ?>
<?php unset($__componentOriginal9ac128a9029c0e4701924bd2d73d7f54); ?>
<?php endif; ?><?php /**PATH E:\MOBILE POS\Open Code Projects\EU\resources\views/expenses/index.blade.php ENDPATH**/ ?>