<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-l text-gray-800 leading-tight">
            {{ \App\Helpers\TranslationHelper::transFromDatabase('Create New Account', __('Create New Account')) }}
        </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 method="POST" action="{{ route("accounting.chart-of-accounts.store") }}" id="accountForm">
                        @csrf

                        <!-- الحساب الأب -->
                        <div class="mb-4">
                            <label for="parent_id" class="block text-sm font-medium text-gray-700">
                                {{ \App\Helpers\TranslationHelper::transFromDatabase('Parent Account', __('Parent Account')) }} <span class="text-red-600">*</span>
                            </label>
                            <select name="parent_id" id="parent_id" required class="select2 mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                <option value="">{{ \App\Helpers\TranslationHelper::transFromDatabase('-- Select Parent Account --', __('-- Select Parent Account --')) }}</option>
                                @foreach($parentAccounts as $parent)
                                    <option value="{{ $parent->id }}" 
                                            data-code="{{ $parent->code }}"
                                            data-type="{{ $parent->account_type }}"
                                            data-balance="{{ $parent->balance_type }}"
                                            {{ old('parent_id') == $parent->id ? 'selected' : '' }}>
                                        {{ $parent->code }} - {{ $parent->name }}
                                    </option>
                                @endforeach
                            </select>
                            @error("parent_id")
                                <p class="text-red-600 text-sm mt-1">{{ $message }}</p>
                            @enderror
                        </div>

                        <!-- رقم الحساب -->
                        <div class="mb-4">
                            <label for="code" class="block text-sm font-medium text-gray-700">{{ \App\Helpers\TranslationHelper::transFromDatabase('Account Code', __('Account Code')) }}</label>
                            <input type="text" name="code" id="code" value="{{ old("code") }}" readonly required class="mt-1 block w-full rounded-md border-gray-300 bg-gray-100 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" placeholder="سيتم توليده تلقائياً">
                            @error("code")
                                <p class="text-red-600 text-sm mt-1">{{ $message }}</p>
                            @enderror
                            <p class="text-sm text-gray-500 mt-1">{{ \App\Helpers\TranslationHelper::transFromDatabase('Account Code will be generated automatically', __('Account Code will be generated automatically')) }}</p>
                        </div>

                        <!-- اسم الحساب -->
                        <div class="mb-4">
                            <label for="name" class="block text-sm font-medium text-gray-700">{{ \App\Helpers\TranslationHelper::transFromDatabase('Account Name', __('Account Name')) }}</label>
                            <input type="text" name="name" id="name" value="{{ old("name") }}" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" placeholder="الأصول الحالية">
                            @error("name")
                                <p class="text-red-600 text-sm mt-1">{{ $message }}</p>
                            @enderror
                        </div>

                        <!-- نوع الحساب -->
                        <div class="mb-4">
                            <label for="account_type" class="block text-sm font-medium text-gray-700">{{ \App\Helpers\TranslationHelper::transFromDatabase('Account Type', __('Account Type')) }}</label>
                            <select name="account_type" id="account_type" required class="mt-1 block w-full rounded-md border-gray-300 bg-gray-100 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                <option value="">{{ \App\Helpers\TranslationHelper::transFromDatabase('-- Will be set automatically --', __('-- Will be set automatically --')) }}</option>
                                <option value="asset" {{ old('account_type') == 'asset' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Assets', __('Assets')) }}</option>
                                <option value="liability" {{ old('account_type') == 'liability' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Liabilities', __('Liabilities')) }}</option>
                                <option value="equity" {{ old('account_type') == 'equity' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Equity', __('Equity')) }}</option>
                                <option value="revenue" {{ old('account_type') == 'revenue' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Revenue', __('Revenue')) }}</option>
                                <option value="expense" {{ old('account_type') == 'expense' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Expense', __('Expense')) }}</option>
                            </select>
                            @error("account_type")
                                <p class="text-red-600 text-sm mt-1">{{ $message }}</p>
                            @enderror
                            <p class="text-sm text-gray-500 mt-1">{{ \App\Helpers\TranslationHelper::transFromDatabase('Account Type will be set automatically from parent account', __('Account Type will be set automatically from parent account')) }}</p>
                        </div>

                        <!-- نوع الرصيد -->
                        <div class="mb-4">
                            <label for="balance_type" class="block text-sm font-medium text-gray-700">{{ \App\Helpers\TranslationHelper::transFromDatabase('Balance Type', __('Balance Type')) }}</label>
                            <select name="balance_type" id="balance_type" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                <option value="">{{ \App\Helpers\TranslationHelper::transFromDatabase('-- Select Balance Type --', __('-- Select Balance Type --')) }}</option>
                                <option value="debit" {{ old('balance_type') == 'debit' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Debit', __('Debit')) }}</option>
                                <option value="credit" {{ old('balance_type') == 'credit' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Credit', __('Credit')) }}</option>
                            </select>
                            @error("balance_type")
                                <p class="text-red-600 text-sm mt-1">{{ $message }}</p>
                            @enderror
                            <p class="text-sm text-gray-500 mt-1">{{ \App\Helpers\TranslationHelper::transFromDatabase('Balance Type is set automatically from parent account and can be modified', __('Balance Type is set automatically from parent account and can be modified')) }}</p>
                        </div>

                        <!-- نوع الحساب (رئيسي أم فرعي) -->
                        <div class="mb-4">
                            <label for="is_parent" class="block text-sm font-medium text-gray-700">{{ \App\Helpers\TranslationHelper::transFromDatabase('Account Classification', __('Account Classification')) }}</label>
                            <select name="is_parent" id="is_parent" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                <option value="0" {{ old('is_parent') == '0' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Sub Account (Cannot add child accounts)', __('Sub Account (Cannot add child accounts)')) }}</option>
                                <option value="1" {{ old('is_parent') == '1' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Parent Account (Can add child accounts)', __('Parent Account (Can add child accounts)')) }}</option>
                            </select>
                            @error("is_parent")
                                <p class="text-red-600 text-sm mt-1">{{ $message }}</p>
                            @enderror
                            <p class="text-sm text-gray-500 mt-1">
                                <strong>{{ \App\Helpers\TranslationHelper::transFromDatabase('Sub Account:', __('Sub Account:')) }}</strong> {{ \App\Helpers\TranslationHelper::transFromDatabase('Used to record journal entries directly', __('Used to record journal entries directly')) }}<br>
                                <strong>{{ \App\Helpers\TranslationHelper::transFromDatabase('Parent Account:', __('Parent Account:')) }}</strong> {{ \App\Helpers\TranslationHelper::transFromDatabase('Used as a group for child accounts and cannot be used in journal entries', __('Used as a group for child accounts and cannot be used in journal entries')) }}
                            </p>
                        </div>

                        <!-- الوصف -->
                        <div class="mb-4">
                            <label for="description" class="block text-sm font-medium text-gray-700">{{ \App\Helpers\TranslationHelper::transFromDatabase('Description', __('Description')) }}</label>
                            <textarea name="description" id="description" rows="3" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" placeholder="وصف اختياري للحساب">{{ old("description") }}</textarea>
                            @error("description")
                                <p class="text-red-600 text-sm mt-1">{{ $message }}</p>
                            @enderror
                        </div>

                        <!-- مرتبط بمركز تكلفة -->
                        <div class="mb-4">
                            <label for="has_cost_center" class="flex items-center">
                                <input type="checkbox" name="has_cost_center" id="has_cost_center" value="1" {{ old('has_cost_center') ? 'checked' : '' }} class="rounded border-gray-300 text-indigo-600 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                <span class="ml-2 text-sm text-gray-700">{{ \App\Helpers\TranslationHelper::transFromDatabase('Link to Cost Center', __('Link to Cost Center')) }}</span>
                            </label>
                        </div>

                        <!-- يتطلب مركز تكلفة -->
                        <div class="mb-4">
                            <label for="requires_cost_center" class="flex items-center">
                                <input type="checkbox" name="requires_cost_center" id="requires_cost_center" value="1" {{ old('requires_cost_center') ? 'checked' : '' }} class="rounded border-gray-300 text-indigo-600 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                <span class="ml-2 text-sm text-gray-700">{{ \App\Helpers\TranslationHelper::transFromDatabase('Requires Cost Center', __('Requires Cost Center')) }}</span>
                            </label>
                            <p class="text-xs text-gray-500 mt-1">{{ \App\Helpers\TranslationHelper::transFromDatabase('If checked, system will require selecting a cost center when using this account in journal entries', __('If checked, system will require selecting a cost center when using this account in journal entries')) }}</p>
                        </div>

                        <!-- اختيار مركز التكلفة -->
                        <div class="mb-4" id="cost_center_section" style="display: none;">
                            <label for="cost_center_id" class="block text-sm font-medium text-gray-700">{{ \App\Helpers\TranslationHelper::transFromDatabase('Cost Center', __('Cost Center')) }}</label>
                            <select name="cost_center_id" id="cost_center_id" class="select2 mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                <option value="">{{ \App\Helpers\TranslationHelper::transFromDatabase('-- Select Cost Center --', __('-- Select Cost Center --')) }}</option>
                                @foreach($costCenters as $center)
                                    <option value="{{ $center->id }}" {{ old('cost_center_id') == $center->id ? 'selected' : '' }}>
                                        {{ $center->code }} - {{ $center->name }}
                                    </option>
                                @endforeach
                            </select>
                            @error("cost_center_id")
                                <p class="text-red-600 text-sm mt-1">{{ $message }}</p>
                            @enderror
                        </div>

                        <!-- الأزرار -->
                        <div class="flex items-center justify-end mt-4 space-y-3">
                            <a href="{{ route("accounting.chart-of-accounts.index") }}" class="inline-flex items-center p-4 py-2 bg-gray-300 border border-transparent rounded-md font-semibold text-s text-gray-800 uppercase tracking-widest hover:bg-gray-400">
                                {{ \App\Helpers\TranslationHelper::transFromDatabase('Cancel', __('Cancel')) }}
                            </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">
                                {{ \App\Helpers\TranslationHelper::transFromDatabase('Save', __('Save')) }}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    
@push('scripts')
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const parentSelect = document.getElementById('parent_id');
        const codeInput = document.getElementById('code');
        const accountTypeSelect = document.getElementById('account_type');
        const balanceTypeSelect = document.getElementById('balance_type');
        const hasCostCenterCheckbox = document.getElementById('has_cost_center');
        const costCenterSection = document.getElementById('cost_center_section');

        function updateCostCenterVisibility() {
            if (hasCostCenterCheckbox.checked) {
                costCenterSection.style.display = 'block';
            } else {
                costCenterSection.style.display = 'none';
                document.getElementById('cost_center_id').value = '';
            }
        }

        function updateAccountCode() {
            const $selectedOption = $(parentSelect).find(':selected');
            
            if (parentSelect.value && $selectedOption.length) {
                const parentCode = $selectedOption.data('code');
                const accountType = $selectedOption.data('type');
                const balanceType = $selectedOption.data('balance');

                if (accountType) accountTypeSelect.value = accountType;
                if (balanceType) balanceTypeSelect.value = balanceType;

                fetch(`{{ route('accounting.chart-of-accounts.generate-code') }}?parent_id=${parentSelect.value}`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    credentials: 'same-origin'
                })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('Network response was not ok');
                        }
                        return response.json();
                    })
                    .then(data => {
                        if (data.code) {
                            codeInput.value = data.code;
                        } else if (data.error) {
                            console.error('Error from server:', data.error);
                            alert('خطأ: ' + data.error);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('حدث خطأ أثناء توليد رقم الحساب. يرجى المحاولة مرة أخرى.');
                    });
            } else {
                codeInput.value = '';
                accountTypeSelect.value = '';
                balanceTypeSelect.value = '';
            }
        }

        $(parentSelect).on('change', updateAccountCode);
        hasCostCenterCheckbox.addEventListener('change', updateCostCenterVisibility);
        
        updateCostCenterVisibility();
        if (parentSelect.value) {
            updateAccountCode();
        }
    });
</script>
@endpush

</x-app-layout>
