﻿<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-l text-gray-800 leading-tight">
            {{ __('إضافة قيد يومية جديد') }}
        </h2>
    </x-slot>

    <div class="py-12">
        <div class="max-w-7l m-auto sm:p-6 lg:p-8">
            <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 bg-white border-b border-gray-200">
                    <form action="{{ route('accounting.journal-entries.store') }}" method="POST" id="journal-entry-form">
                        @csrf

                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                            <div>
                                <label for="fiscal_year_id" class="block text-sm font-medium text-gray-700">{{ __('السنة المالية') }}</label>
                                <input type="text" value="{{ $fiscalYear->name }}" class="mt-1 block w-full py-2 p-3 border border-gray-300 bg-gray-100 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" readonly>
                                <input type="hidden" name="fiscal_year_id" value="{{ $fiscalYear->id }}">
                            </div>

                            <div>
                                <label for="accounting_period_id" class="block text-sm font-medium text-gray-700">{{ __('الفترة المحاسبية') }}</label>
                                <input type="text" value="{{ $period->name }}" class="mt-1 block w-full py-2 p-3 border border-gray-300 bg-gray-100 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" readonly>
                                <input type="hidden" name="accounting_period_id" value="{{ $period->id }}">
                                @error('accounting_period_id')
                                    <p class="text-red-500 text-s mt-1">{{ $message }}</p>
                                @enderror
                            </div>

                            <div>
                                <label for="branch_id" class="block text-sm font-medium text-gray-700">{{ __('الفرع') }}</label>
                                <select id="branch_id" name="branch_id" class="select2 mt-1 block w-full py-2 p-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                                    <option value="">{{ __('المركز الرئيسي') }}</option>
                                    @foreach ($branches as $branch)
                                        <option value="{{ $branch->id }}" {{ old('branch_id') == $branch->id ? 'selected' : '' }}>
                                            {{ $branch->name }}
                                        </option>
                                    @endforeach
                                </select>
                                @error('branch_id')
                                    <p class="text-red-500 text-s mt-1">{{ $message }}</p>
                                @enderror
                            </div>
                        </div>

                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                            <div>
                                <label for="entry_date" class="block text-sm font-medium text-gray-700">{{ __('تاريخ القيد') }}</label>
                                <input type="date" name="entry_date" id="entry_date" value="{{ old('entry_date', now()->format('Y-m-d')) }}" class="mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm sm:text-sm border-gray-300 rounded-md">
                                @error('entry_date')
                                    <p class="text-red-500 text-s mt-1">{{ $message }}</p>
                                @enderror
                            </div>

                            <div>
                                <label for="entry_type" class="block text-sm font-medium text-gray-700">{{ __('نوع القيد') }}</label>
                                <select id="entry_type" name="entry_type" class="select2 mt-1 block w-full py-2 p-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                                    @foreach ($entryTypes as $key => $value)
                                        <option value="{{ $key }}" {{ old('entry_type', 'manual') == $key ? 'selected' : '' }}>
                                            {{ $value }}
                                        </option>
                                    @endforeach
                                </select>
                                @error('entry_type')
                                    <p class="text-red-500 text-s mt-1">{{ $message }}</p>
                                @enderror
                            </div>
                        </div>

                        <div class="mb-4">
                            <label for="description" class="block text-sm font-medium text-gray-700">{{ __('وصف القيد') }}</label>
                            <input type="text" name="description" id="description" value="{{ old('description') }}" class="mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm sm:text-sm border-gray-300 rounded-md">
                            @error('description')
                                <p class="text-red-500 text-s mt-1">{{ $message }}</p>
                            @enderror
                        </div>

                        <div class="mb-4">
                            <label for="notes" class="block text-sm font-medium text-gray-700">{{ __('ملاحظات') }}</label>
                            <textarea name="notes" id="notes" rows="2" class="mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm sm:text-sm border-gray-300 rounded-md">{{ old('notes') }}</textarea>
                            @error('notes')
                                <p class="text-red-500 text-s mt-1">{{ $message }}</p>
                            @enderror
                        </div>

                        <div class="mt-6 mb-4">
                            <h3 class="text-lg font-medium text-gray-900">{{ __('تفاصيل القيد') }}</h3>
                            @error('accounts')
                                <p class="text-red-500 text-s mt-1">{{ $message }}</p>
                            @enderror
                        </div>

                        <div class="overflow--auto mb-4">
                            <table class="min-w-full divide-y divide-gray-200" id="accounts-table">
                                <thead class="bg-gray-50">
                                    <tr>
                                        <th scope="col" class="p-6 py-3 text-right text-s font-medium text-gray-500 uppercase tracking-wider">
                                            {{ __('الحساب') }}
                                        </th>
                                        <th scope="col" class="p-6 py-3 text-right text-s font-medium text-gray-500 uppercase tracking-wider">
                                            {{ __('مركز التكلفة') }}
                                        </th>
                                        <th scope="col" class="p-6 py-3 text-right text-s font-medium text-gray-500 uppercase tracking-wider">
                                            {{ __('الوصف') }}
                                        </th>
                                        <th scope="col" class="p-6 py-3 text-right text-s font-medium text-gray-500 uppercase tracking-wider">
                                            {{ __('مدين') }}
                                        </th>
                                        <th scope="col" class="p-6 py-3 text-right text-s font-medium text-gray-500 uppercase tracking-wider">
                                            {{ __('دائن') }}
                                        </th>
                                        <th scope="col" class="p-6 py-3 text-right text-s font-medium text-gray-500 uppercase tracking-wider">
                                            {{ __('الإجراءات') }}
                                        </th>
                                    </tr>
                                </thead>
                                <tbody class="bg-white divide-y divide-gray-200" id="account-rows">
                                    <tr class="account-row">
                                        <td class="p-6 py-4 whitespace-nowrap">
                                            <select name="accounts[0][account_id]" class="select2 block w-full py-2 p-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                                                <option value="">{{ __('اختر الحساب') }}</option>
                                                @foreach ($accounts as $account)
                                                    <option value="{{ $account->id }}">
                                                        {{ $account->code }} - {{ $account->name }}
                                                    </option>
                                                @endforeach
                                            </select>
                                        </td>
                                        <td class="p-6 py-4 whitespace-nowrap">
                                            <select name="accounts[0][cost_center_id]" class="select2 block w-full py-2 p-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                                                <option value="">{{ __('اختر مركز التكلفة') }}</option>
                                                @foreach ($costCenters as $costCenter)
                                                    <option value="{{ $costCenter->id }}">
                                                        {{ $costCenter->code }} - {{ $costCenter->name }}
                                                    </option>
                                                @endforeach
                                            </select>
                                        </td>
                                        <td class="p-6 py-4 whitespace-nowrap">
                                            <input type="text" name="accounts[0][description]" class="block w-full py-2 p-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                                        </td>
                                        <td class="p-6 py-4 whitespace-nowrap">
                                            <input type="number" name="accounts[0][debit_amount]" step="0.01" min="0" class="debit-amount block w-full py-2 p-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" onchange="calculateTotals()">
                                        </td>
                                        <td class="p-6 py-4 whitespace-nowrap">
                                            <input type="number" name="accounts[0][credit_amount]" step="0.01" min="0" class="credit-amount block w-full py-2 p-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" onchange="calculateTotals()">
                                        </td>
                                        <td class="p-6 py-4 whitespace-nowrap">
                                            <button type="button" class="text-red-600 hover:text-red-900 delete-row" onclick="deleteRow(this)">
                                                <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="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd" />
                                                </svg>
                                            </button>
                                        </td>
                                    </tr>
                                    <tr class="account-row">
                                        <td class="p-6 py-4 whitespace-nowrap">
                                            <select name="accounts[1][account_id]" class="select2 block w-full py-2 p-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                                                <option value="">{{ __('اختر الحساب') }}</option>
                                                @foreach ($accounts as $account)
                                                    <option value="{{ $account->id }}">
                                                        {{ $account->code }} - {{ $account->name }}
                                                    </option>
                                                @endforeach
                                            </select>
                                        </td>
                                        <td class="p-6 py-4 whitespace-nowrap">
                                            <select name="accounts[1][cost_center_id]" class="select2 block w-full py-2 p-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                                                <option value="">{{ __('اختر مركز التكلفة') }}</option>
                                                @foreach ($costCenters as $costCenter)
                                                    <option value="{{ $costCenter->id }}">
                                                        {{ $costCenter->code }} - {{ $costCenter->name }}
                                                    </option>
                                                @endforeach
                                            </select>
                                        </td>
                                        <td class="p-6 py-4 whitespace-nowrap">
                                            <input type="text" name="accounts[1][description]" class="block w-full py-2 p-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                                        </td>
                                        <td class="p-6 py-4 whitespace-nowrap">
                                            <input type="number" name="accounts[1][debit_amount]" step="0.01" min="0" class="debit-amount block w-full py-2 p-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" onchange="calculateTotals()">
                                        </td>
                                        <td class="p-6 py-4 whitespace-nowrap">
                                            <input type="number" name="accounts[1][credit_amount]" step="0.01" min="0" class="credit-amount block w-full py-2 p-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" onchange="calculateTotals()">
                                        </td>
                                        <td class="p-6 py-4 whitespace-nowrap">
                                            <button type="button" class="text-red-600 hover:text-red-900 delete-row" onclick="deleteRow(this)">
                                                <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="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd" />
                                                </svg>
                                            </button>
                                        </td>
                                    </tr>
                                </tbody>
                                <tfoot>
                                    <tr class="bg-gray-50">
                                        <td colspan="3" class="p-6 py-4 whitespace-nowrap text-sm font-bold text-gray-900 text-left">
                                            {{ __('الإجمالي') }}
                                        </td>
                                        <td class="p-6 py-4 whitespace-nowrap text-sm font-bold text-gray-900">
                                            <span id="total-debit">0.00</span>
                                        </td>
                                        <td class="p-6 py-4 whitespace-nowrap text-sm font-bold text-gray-900">
                                            <span id="total-credit">0.00</span>
                                        </td>
                                        <td class="p-6 py-4 whitespace-nowrap">
                                            <button type="button" class="text-blue-600 hover:text-blue-900" onclick="addRow()">
                                                <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="M10 5a1 1 0 011 1v3h3a1 1 0 110 2h-3v3a1 1 0 11-2 0v-3H6a1 1 0 110-2h3V6a1 1 0 011-1z" clip-rule="evenodd" />
                                                </svg>
                                            </button>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="6" class="p-6 py-4">
                                            <div id="balance-status" class="text-center"></div>
                                        </td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>

                        <div class="flex items-center justify-between mt-6">
                            <a href="{{ route('accounting.journal-entries.index') }}" class="inline-flex items-center p-4 py-2 bg-gray-300 border border-transparent rounded-md font-semibold text-s text-gray-700 uppercase tracking-widest hover:bg-gray-400 active:bg-gray-500 focus:outline-none focus:border-gray-500 focus:ring ring-gray-300 disabled:opacity-25 transition ease-in-out duration-150">
                                {{ __('إلغاء') }}
                            </a>
                            <button type="submit" class="inline-flex items-center p-4 py-2 bg-blue-600 border border-transparent rounded-md font-semibold text-s text-white uppercase tracking-widest hover:bg-blue-700 active:bg-blue-800 focus:outline-none focus:border-blue-700 focus:ring ring-blue-300 disabled:opacity-25 transition ease-in-out duration-150">
                                {{ __('حفظ') }}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script>
        let rowInde = 2;

        function addRow() {
            const tbody = document.getElementById('account-rows');
            const newRow = document.createElement('tr');
            newRow.className = 'account-row';
            
            newRow.innerHTML = `
                <td class="p-6 py-4 whitespace-nowrap">
                    <select name="accounts[${rowInde}][account_id]" class="select2 block w-full py-2 p-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                        <option value="">{{ __('اختر الحساب') }}</option>
                        @foreach ($accounts as $account)
                            <option value="{{ $account->id }}">
                                {{ $account->code }} - {{ $account->name }}
                            </option>
                        @endforeach
                    </select>
                </td>
                <td class="p-6 py-4 whitespace-nowrap">
                    <select name="accounts[${rowInde}][cost_center_id]" class="select2 block w-full py-2 p-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                        <option value="">{{ __('اختر مركز التكلفة') }}</option>
                        @foreach ($costCenters as $costCenter)
                            <option value="{{ $costCenter->id }}">
                                {{ $costCenter->code }} - {{ $costCenter->name }}
                            </option>
                        @endforeach
                    </select>
                </td>
                <td class="p-6 py-4 whitespace-nowrap">
                    <input type="text" name="accounts[${rowInde}][description]" class="block w-full py-2 p-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                </td>
                <td class="p-6 py-4 whitespace-nowrap">
                    <input type="number" name="accounts[${rowInde}][debit_amount]" step="0.01" min="0" class="debit-amount block w-full py-2 p-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" onchange="calculateTotals()">
                </td>
                <td class="p-6 py-4 whitespace-nowrap">
                    <input type="number" name="accounts[${rowInde}][credit_amount]" step="0.01" min="0" class="credit-amount block w-full py-2 p-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" onchange="calculateTotals()">
                </td>
                <td class="p-6 py-4 whitespace-nowrap">
                    <button type="button" class="text-red-600 hover:text-red-900 delete-row" onclick="deleteRow(this)">
                        <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="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd" />
                        </svg>
                    </button>
                </td>
            `;
            
            tbody.appendChild(newRow);

            // Initialize Select2 for the new selects
            $(newRow).find('.select2').select2({
                theme: 'bootstrap-5',
                width: '100%',
                dir: document.documentElement.dir || 'rtl'
            });

            rowInde++;
        }

        function deleteRow(button) {
            const rows = document.querySelectorAll('.account-row');
            if (rows.length <= 2) {
                alert('{{ __("يجب أن يحتوي القيد على سطرين على الأقل") }}');
                return;
            }
            
            const row = button.closest('tr');
            row.remove();
            calculateTotals();
            
            // إعادة ترقيم الصفوف
            const accountRows = document.querySelectorAll('.account-row');
            accountRows.forEach((row, inde) => {
                const accountSelect = row.querySelector('select[name^="accounts["][name$="[account_id]"]');
                const costCenterSelect = row.querySelector('select[name^="accounts["][name$="[cost_center_id]"]');
                const description = row.querySelector('input[name^="accounts["][name$="[description]"]');
                const debitAmount = row.querySelector('input[name^="accounts["][name$="[debit_amount]"]');
                const creditAmount = row.querySelector('input[name^="accounts["][name$="[credit_amount]"]');
                
                accountSelect.name = `accounts[${inde}][account_id]`;
                costCenterSelect.name = `accounts[${inde}][cost_center_id]`;
                description.name = `accounts[${inde}][description]`;
                debitAmount.name = `accounts[${inde}][debit_amount]`;
                creditAmount.name = `accounts[${inde}][credit_amount]`;
            });
            
            rowInde = accountRows.length;
        }

        function calculateTotals() {
            let totalDebit = 0;
            let totalCredit = 0;
            
            const debitInputs = document.querySelectorAll('.debit-amount');
            const creditInputs = document.querySelectorAll('.credit-amount');
            
            debitInputs.forEach(input => {
                const value = parseFloat(input.value) || 0;
                totalDebit += value;
            });
            
            creditInputs.forEach(input => {
                const value = parseFloat(input.value) || 0;
                totalCredit += value;
            });
            
            document.getElementById('total-debit').textContent = totalDebit.toFixed(2);
            document.getElementById('total-credit').textContent = totalCredit.toFixed(2);
            
            const balanceStatus = document.getElementById('balance-status');
            if (Math.abs(totalDebit - totalCredit) < 0.01) {
                balanceStatus.textContent = '{{ __("القيد متوازن") }}';
                balanceStatus.className = 'text-center text-green-600 font-bold';
            } else {
                balanceStatus.textContent = '{{ __("القيد غير متوازن") }}';
                balanceStatus.className = 'text-center text-red-600 font-bold';
            }
        }

        // تنفيذ حساب الإجماليات عند تحميل الصفحة
        document.addEventListener('DOMContentLoaded', function() {
            calculateTotals();
        });
    </script>
</x-app-layout>
