<x-app-layout>
    <x-slot name="header">
        <div class="flex justify-between items-center">
            <h2 class="font-semibold text-xl text-gray-800 leading-tight">
                {{ \App\Helpers\TranslationHelper::transFromDatabase('ChartOfAccounts.Index.Title', __('Chart of Accounts')) }}
            </h2>
            <div class="flex gap-2">
                <!-- طباعة -->
                <button onclick="printChartOfAccounts()" 
                        class="inline-flex items-center px-4 py-2 bg-blue-600 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-blue-700 focus:bg-blue-700 active:bg-blue-800 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition ease-in-out duration-150"
                        title="{{ \App\Helpers\TranslationHelper::transFromDatabase('common.print', __('Print')) }}">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 ml-1" viewBox="0 0 20 20" fill="currentColor">
                        <path d="M5 4a2 2 0 012-2h6a2 2 0 012 2v14l-5-2.5L5 18V4z"></path>
                    </svg>
                    {{ \App\Helpers\TranslationHelper::transFromDatabase('common.print', __('Print')) }}
                </button>

                <!-- تصدير Excel -->
                <a href="{{ route('accounting.chart-of-accounts.export') }}"
                   class="inline-flex items-center px-4 py-2 bg-green-600 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-green-700 focus:bg-green-700 active:bg-green-800 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 transition ease-in-out duration-150"
                   title="{{ \App\Helpers\TranslationHelper::transFromDatabase('common.excel', __('Excel')) }}">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 ml-1" viewBox="0 0 20 20" fill="currentColor">
                        <path fill-rule="evenodd" d="M3 17a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm3.293-7.707a1 1 0 011.414 0L9 10.586V3a1 1 0 112 0v7.586l1.293-1.293a1 1 0 111.414 1.414l-3 3a1 1 0 01-1.414 0l-3-3a1 1 0 010-1.414z" clip-rule="evenodd"></path>
                    </svg>
                    {{ \App\Helpers\TranslationHelper::transFromDatabase('common.excel', __('Excel')) }}
                </a>

                <!-- تصدير PDF -->
                <a href="{{ route('accounting.chart-of-accounts.export-pdf') }}"
                   class="inline-flex items-center px-4 py-2 bg-red-600 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-red-700 focus:bg-red-700 active:bg-red-800 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 transition ease-in-out duration-150"
                   title="{{ \App\Helpers\TranslationHelper::transFromDatabase('common.pdf', __('PDF')) }}">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 ml-1" viewBox="0 0 20 20" fill="currentColor">
                        <path fill-rule="evenodd" d="M3 17a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm3.293-7.707a1 1 0 011.414 0L9 10.586V3a1 1 0 112 0v7.586l1.293-1.293a1 1 0 111.414 1.414l-3 3a1 1 0 01-1.414 0l-3-3a1 1 0 010-1.414z" clip-rule="evenodd"></path>
                    </svg>
                    {{ \App\Helpers\TranslationHelper::transFromDatabase('common.pdf', __('PDF')) }}
                </a>

                <!-- الرجوع -->
                <a href="{{ route('accounting.chart-of-accounts.tree') }}"
                   class="inline-flex items-center px-4 py-2 bg-gray-600 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-gray-700 focus:bg-gray-700 active:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition ease-in-out duration-150">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 ml-1" viewBox="0 0 20 20" fill="currentColor">
                        <path fill-rule="evenodd" d="M9.707 16.707a1 1 0 01-1.414 0l-6-6a1 1 0 010-1.414l6-6a1 1 0 011.414 1.414L5.414 9H17a1 1 0 110 2H5.414l4.293 4.293a1 1 0 010 1.414z" clip-rule="evenodd" />
                    </svg>
                    {{ \App\Helpers\TranslationHelper::transFromDatabase('ChartOfAccounts.Back', __('Back')) }}
                </a>
            </div>
        </div>
    </x-slot>

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 bg-white border-b border-gray-200">
                    <div class="mb-6">
                        <h3 class="text-lg font-medium text-gray-900">{{ \App\Helpers\TranslationHelper::transFromDatabase('ChartOfAccounts.Index.Title', __('Chart of Accounts')) }}</h3>
                        <p class="mt-1 text-sm text-gray-600">{{ \App\Helpers\TranslationHelper::transFromDatabase('ChartOfAccounts.Index.Description', __('View Account Structure')) }}</p>
                    </div>

                    <!-- Search Bar -->
                    <div class="mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200">
                        <div class="flex items-center gap-4">
                            <div class="flex-1 relative">
                                <svg xmlns="http://www.w3.org/2000/svg" class="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" viewBox="0 0 20 20" fill="currentColor">
                                    <path fill-rule="evenodd" d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z" clip-rule="evenodd" />
                                </svg>
                                <input 
                                    type="text" 
                                    id="search-accounts" 
                                    placeholder="{{ \App\Helpers\TranslationHelper::transFromDatabase('ChartOfAccounts.SearchPlaceholder', __('Search by account number or name')) }}"
                                    class="w-full pl-10 pr-10 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent focus:outline-none transition"
                                >
                                <button 
                                    id="clear-search" 
                                    class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 hidden transition"
                                    title="{{ \App\Helpers\TranslationHelper::transFromDatabase('common.search', __('Search')) }}"
                                >
                                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                                        <path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd" />
                                    </svg>
                                </button>
                            </div>
                            <div id="search-results-count" class="text-sm text-gray-600 font-medium whitespace-nowrap hidden">
                                <span id="match-count">0</span> {{ \App\Helpers\TranslationHelper::transFromDatabase('ChartOfAccounts.Results', __('Results')) }}
                            </div>
                        </div>
                    </div>

                    <div id="no-results" class="hidden p-8 text-center">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-12 w-12 mx-auto text-gray-400 mb-3" viewBox="0 0 20 20" fill="currentColor">
                            <path fill-rule="evenodd" d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z" clip-rule="evenodd" />
                        </svg>
                        <p class="text-gray-500">{{ \App\Helpers\TranslationHelper::transFromDatabase('ChartOfAccounts.NoResults', __('No results found matching search')) }}</p>
                    </div>

                    <div class="mt-6">
                        @if($accounts->count())
                            <div class="space-y-2" id="accounts-list">
                                @foreach ($accounts as $account)
                                    <div class="flex items-center p-3 border-l-4 border-blue-500 bg-blue-50 account-item" data-account-code="{{ $account->code }}" data-account-name="{{ $account->name }}">
                                        <div class="flex-1">
                                            <div class="font-medium text-gray-900">
                                                <span class="account-code">{{ $account->code }}</span> - <span class="account-name">{{ $account->name }}</span>
                                            </div>
                                            <div class="text-sm text-gray-500">
                                                {{ $account->category->name ?? \App\Helpers\TranslationHelper::transFromDatabase('ChartOfAccounts.NoCategory', __('No Category')) }}
                                            </div>
                                        </div>
                                        <div class="flex items-center space-x-2">
                                            @if ($account->is_active)
                                                <span class="px-2 py-1 text-xs font-medium bg-green-100 text-green-800 rounded">{{ \App\Helpers\TranslationHelper::transFromDatabase('ChartOfAccounts.Active', __('Active')) }}</span>
                                            @else
                                                <span class="px-2 py-1 text-xs font-medium bg-red-100 text-red-800 rounded">{{ \App\Helpers\TranslationHelper::transFromDatabase('ChartOfAccounts.Inactive', __('Inactive')) }}</span>
                                            @endif
                                            <a href="{{ route('accounting.chart-of-accounts.show', $account) }}" class="text-blue-600 hover:text-blue-900">{{ \App\Helpers\TranslationHelper::transFromDatabase('ChartOfAccounts.View', __('View')) }}</a>
                                        </div>
                                    </div>
                                @endforeach
                            </div>
                        @else
                            <div class="text-center py-8">
                                <p class="text-gray-500">{{ \App\Helpers\TranslationHelper::transFromDatabase('ChartOfAccounts.NoAccounts', __('No Accounts')) }}</p>
                            </div>
                        @endif
                    </div>
                </div>
            </div>
        </div>
    </div>

    @push('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const searchInput = document.getElementById('search-accounts');
            const clearBtn = document.getElementById('clear-search');
            const resultsCount = document.getElementById('search-results-count');
            const noResults = document.getElementById('no-results');
            const accountsList = document.getElementById('accounts-list');
            const matchCountSpan = document.getElementById('match-count');

            // Search functionality
            searchInput.addEventListener('input', function() {
                const searchTerm = this.value.toLowerCase().trim();
                
                if (searchTerm) {
                    clearBtn.classList.remove('hidden');
                } else {
                    clearBtn.classList.add('hidden');
                    noResults.classList.add('hidden');
                    resultsCount.classList.add('hidden');
                }

                filterAccounts(searchTerm);
            });

            clearBtn.addEventListener('click', function() {
                searchInput.value = '';
                clearBtn.classList.add('hidden');
                noResults.classList.add('hidden');
                resultsCount.classList.add('hidden');
                filterAccounts('');
            });

            function filterAccounts(searchTerm) {
                const allItems = document.querySelectorAll('.account-item');
                let matchCount = 0;

                allItems.forEach(item => {
                    const code = item.getAttribute('data-account-code').toLowerCase();
                    const name = item.getAttribute('data-account-name').toLowerCase();
                    
                    const isMatch = code.includes(searchTerm) || name.includes(searchTerm);
                    
                    if (searchTerm) {
                        if (isMatch) {
                            item.style.display = 'block';
                            // Highlight matched item
                            item.style.backgroundColor = '#fffbeb';
                            item.style.borderLeft = '4px solid #fbbf24';
                            item.style.paddingLeft = '8px';
                            matchCount++;
                        } else {
                            item.style.display = 'none';
                        }
                    } else {
                        item.style.display = 'block';
                        item.style.backgroundColor = '#eff6ff';
                        item.style.borderLeft = '4px solid #3b82f6';
                        item.style.paddingLeft = '';
                    }
                });

                // Show/hide no results message and count
                if (searchTerm) {
                    if (matchCount === 0) {
                        noResults.classList.remove('hidden');
                        resultsCount.classList.add('hidden');
                    } else {
                        noResults.classList.add('hidden');
                        resultsCount.classList.remove('hidden');
                        matchCountSpan.textContent = matchCount;
                    }
                }
            }
        });

        // وظيفة الطباعة
        function printChartOfAccounts() {
            const printWindow = window.open('', '', 'width=900,height=600');
            const printContent = document.querySelector('.bg-white.overflow-hidden.shadow-sm');
            
            printWindow.document.write(`
                <html dir="rtl">
                    <head>
                        <title>دليل الحسابات - طباعة</title>
                        <style>
                            * {
                                margin: 0;
                                padding: 0;
                                box-sizing: border-box;
                            }
                            body {
                                font-family: 'Arial', sans-serif;
                                padding: 20px;
                                background-color: #fff;
                            }
                            .print-header {
                                text-align: center;
                                margin-bottom: 30px;
                                border-bottom: 2px solid #333;
                                padding-bottom: 15px;
                            }
                            .print-header h1 {
                                font-size: 24px;
                                color: #333;
                                margin-bottom: 10px;
                            }
                            .print-header p {
                                color: #666;
                                font-size: 12px;
                            }
                            table {
                                width: 100%;
                                border-collapse: collapse;
                                margin-top: 20px;
                            }
                            th, td {
                                padding: 12px;
                                text-align: right;
                                border-bottom: 1px solid #ddd;
                            }
                            th {
                                background-color: #f5f5f5;
                                font-weight: bold;
                                color: #333;
                                border-bottom: 2px solid #333;
                            }
                            tr:nth-child(even) {
                                background-color: #f9f9f9;
                            }
                            .status-active {
                                color: #22c55e;
                                font-weight: bold;
                            }
                            .status-inactive {
                                color: #ef4444;
                                font-weight: bold;
                            }
                            .account-code {
                                font-weight: bold;
                                color: #1e40af;
                            }
                            .print-footer {
                                margin-top: 30px;
                                text-align: center;
                                font-size: 12px;
                                color: #666;
                                border-top: 2px solid #333;
                                padding-top: 15px;
                            }
                            @media print {
                                body {
                                    padding: 0;
                                }
                                .print-footer {
                                    page-break-inside: avoid;
                                }
                            }
                        </style>
                    </head>
                    <body>
                        <div class="print-header">
                            <h1>دليل الحسابات</h1>
                            <p>تم الطباعة بتاريخ: ${new Date().toLocaleDateString('ar-SA')}</p>
                        </div>
                        <table>
                            <thead>
                                <tr>
                                    <th>رقم الحساب</th>
                                    <th>اسم الحساب</th>
                                    <th>الفئة</th>
                                    <th>الحالة</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${Array.from(document.querySelectorAll('.account-item')).map(item => {
                                    if (item.style.display === 'none') return '';
                                    const code = item.querySelector('.account-code').textContent;
                                    const name = item.querySelector('.account-name').textContent;
                                    const category = item.querySelector('.text-sm.text-gray-500').textContent;
                                    const statusElement = item.querySelector('[class*="text-green"], [class*="text-red"]');
                                    const status = statusElement ? statusElement.textContent : 'نشط';
                                    const statusClass = statusElement && statusElement.classList.contains('text-red-800') ? 'status-inactive' : 'status-active';
                                    
                                    return \`
                                        <tr>
                                            <td><span class="account-code">\${code}</span></td>
                                            <td>\${name}</td>
                                            <td>\${category}</td>
                                            <td><span class="\${statusClass}">\${status}</span></td>
                                        </tr>
                                    \`;
                                }).join('')}
                            </tbody>
                        </table>
                        <div class="print-footer">
                            <p>© جميع الحقوق محفوظة - {{ \App\Models\SystemSetting::get('system_name', 'نظام إدارة المقاولات') }}</p>
                        </div>
                        <script>
                            window.print();
                            setTimeout(() => window.close(), 500);
                        </script>
                    </body>
                </html>
            `);
            printWindow.document.close();
        }
    </script>
    @endpush
</x-app-layout>
