@extends('layouts.app')
@section('title', 'Salary Components')
@section('breadcrumb')
    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
    <li class="breadcrumb-item"><a href="#">Payroll</a></li>
    <li class="breadcrumb-item active">Salary Components</li>
@endsection

@section('content')
@php
    $subTypeMap = [
        'earning' => \App\Support\SalaryComponentOptions::subTypes('earning'),
        'deduction' => \App\Support\SalaryComponentOptions::subTypes('deduction'),
    ];
@endphp

<div class="page-header">
    <div>
        <h1 class="page-title"><i class="bi bi-cash-coin me-2 text-primary"></i>Salary Components</h1>
        <p class="page-subtitle">{{ $stats['total'] }} total &nbsp;·&nbsp; <span class="text-success">{{ $stats['active'] }} active</span></p>
    </div>
    @if(auth()->user()->hasPermission('payroll','edit'))
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#scAddModal">
        <i class="bi bi-plus-lg me-1"></i>New Salary Component
    </button>
    @endif
</div>

@if(session('success'))
<div class="alert alert-success alert-dismissible d-flex gap-2 mb-3">
    <i class="bi bi-check-circle flex-shrink-0"></i><div>{{ session('success') }}</div>
    <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert"></button>
</div>
@endif
@if($errors->any())
<div class="alert alert-danger alert-dismissible mb-3">
    @foreach($errors->all() as $e)<div>{{ $e }}</div>@endforeach
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
@endif

<div class="card mb-3">
    <div class="card-body py-2 px-3">
        <form method="GET">
            <div class="row g-2 align-items-center">
                <div class="col-12 col-sm-3">
                    <input type="text" name="search" class="form-control form-control-sm" placeholder="Search component…" value="{{ request('search') }}">
                </div>
                <div class="col-6 col-sm-2">
                    <select name="type" class="form-select form-select-sm">
                        <option value="">All Types</option>
                        @foreach(\App\Support\SalaryComponentOptions::types() as $value => $label)
                        <option value="{{ $value }}" {{ request('type') === $value ? 'selected' : '' }}>{{ $label }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-6 col-sm-2">
                    <select name="sub_type" class="form-select form-select-sm">
                        <option value="">All Sub Types</option>
                        @foreach(\App\Support\SalaryComponentOptions::allSubTypes() as $value => $label)
                        <option value="{{ $value }}" {{ request('sub_type') === $value ? 'selected' : '' }}>{{ $label }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-6 col-sm-2">
                    <select name="status" class="form-select form-select-sm">
                        <option value="">All Status</option>
                        <option value="active" {{ request('status') === 'active' ? 'selected' : '' }}>Active</option>
                        <option value="inactive" {{ request('status') === 'inactive' ? 'selected' : '' }}>Inactive</option>
                    </select>
                </div>
                <div class="col-3 col-sm-1">
                    <button type="submit" class="btn btn-primary btn-sm w-100"><i class="bi bi-search"></i></button>
                </div>
                <div class="col-3 col-sm-1">
                    <a href="{{ route('payroll.salary-components.index') }}" class="btn btn-outline-secondary btn-sm w-100"><i class="bi bi-x-lg"></i></a>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="card">
    <div class="card-header fw-semibold">All Salary Components</div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover mb-0" style="min-width:1100px">
                <thead class="table-light">
                    <tr>
                        <th class="ps-4">Component</th>
                        <th>Type</th>
                        <th>Sub Type</th>
                        <th>Expense A/C</th>
                        <th>COA Type</th>
                        <th>Liability A/C</th>
                        <th>Liability COA Type</th>
                        <th>Status</th>
                        <th class="text-end pe-4">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($components as $component)
                    <tr class="{{ !$component->is_active ? 'table-secondary' : '' }}">
                        <td class="ps-4 fw-semibold" style="font-size:13.5px">{{ $component->name }}</td>
                        <td style="font-size:13px">{{ $component->typeLabel() }}</td>
                        <td style="font-size:13px">{{ $component->subTypeLabel() }}</td>
                        <td style="font-size:13px">{{ $component->expenseAccount?->name ?? '—' }}</td>
                        <td style="font-size:13px">{{ $component->expenseCoaTypeLabel() }}</td>
                        <td style="font-size:13px">{{ $component->liabilityAccount?->name ?? '—' }}</td>
                        <td style="font-size:13px">{{ $component->liabilityCoaTypeLabel() }}</td>
                        <td>
                            <span class="badge" style="font-size:11px;background:{{ $component->is_active ? '#d1e7dd' : '#e9ecef' }};color:{{ $component->is_active ? '#0a3622' : '#495057' }}">
                                {{ $component->is_active ? 'Active' : 'Inactive' }}
                            </span>
                        </td>
                        <td class="text-end pe-3">
                            @if(auth()->user()->hasPermission('payroll','edit'))
                            <div class="d-flex justify-content-end gap-1">
                                <button type="button" class="btn btn-outline-secondary btn-sm btn-edit-sc"
                                        data-name="{{ $component->name }}"
                                        data-type="{{ $component->type }}"
                                        data-sub-type="{{ $component->sub_type }}"
                                        data-expense-account-id="{{ $component->expense_account_id ?? '' }}"
                                        data-liability-account-id="{{ $component->liability_account_id ?? '' }}"
                                        data-active="{{ $component->is_active ? '1' : '0' }}"
                                        data-url="{{ route('payroll.salary-components.update', $component) }}"
                                        title="Edit">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <form method="POST" action="{{ route('payroll.salary-components.toggle', $component) }}">
                                    @csrf @method('PATCH')
                                    <button type="submit" class="btn btn-sm {{ $component->is_active ? 'btn-outline-warning' : 'btn-outline-success' }}"
                                            title="{{ $component->is_active ? 'Mark inactive' : 'Mark active' }}">
                                        <i class="bi bi-{{ $component->is_active ? 'eye-slash' : 'eye' }}"></i>
                                    </button>
                                </form>
                                <form method="POST" action="{{ route('payroll.salary-components.destroy', $component) }}" onsubmit="return confirm('Delete {{ addslashes($component->name) }}?')">
                                    @csrf @method('DELETE')
                                    <button type="submit" class="btn btn-outline-danger btn-sm" title="Delete"><i class="bi bi-trash"></i></button>
                                </form>
                            </div>
                            @endif
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="9" class="text-center py-5 text-muted">
                            <i class="bi bi-cash-coin display-5 d-block mb-2"></i>
                            No salary components found.
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        @if($components->hasPages())
        <div class="px-4 py-3 border-top">{{ $components->links() }}</div>
        @endif
    </div>
</div>

@if(auth()->user()->hasPermission('payroll','edit'))
@include('payroll.salary-components._form-modal', [
    'modalId' => 'scAddModal',
    'title' => 'New Salary Component',
    'formAction' => route('payroll.salary-components.store'),
    'formId' => 'scAddForm',
    'canCreateCoaAccount' => $canCreateCoaAccount,
])

@include('payroll.salary-components._form-modal', [
    'modalId' => 'scEditModal',
    'title' => 'Edit Salary Component',
    'formAction' => '#',
    'formId' => 'scEditForm',
    'isEdit' => true,
    'canCreateCoaAccount' => $canCreateCoaAccount,
])

@if($canCreateCoaAccount)
@include('payroll.salary-components._coa-quick-add-modal')
@endif

<script type="application/json" id="salaryComponentAccountTrees">@json($accountTrees)</script>
@if($canCreateCoaAccount)
<script type="application/json" id="salaryComponentCoaQuickAddSections">@json($coaQuickAddSections)</script>
<script type="application/json" id="salaryComponentCoaParentPickerTree">@json($parentPickerTree)</script>
<script type="application/json" id="salaryComponentCoaParentPickerAccounts">@json($parentPickerAccounts)</script>
@endif
@endif
@endsection

@push('scripts')
@if($canCreateCoaAccount ?? false)
<script src="{{ asset('js/coa-parent-picker.js') }}?v={{ filemtime(public_path('js/coa-parent-picker.js')) }}"></script>
@endif
<script>
(function () {
    const subTypeMap = @json($subTypeMap);

    function fillSubTypes(selectEl, type, selected) {
        if (!selectEl) return;
        selectEl.innerHTML = '<option value="">Select sub type</option>';
        Object.entries(subTypeMap[type] || {}).forEach(function ([value, label]) {
            const opt = document.createElement('option');
            opt.value = value;
            opt.textContent = label;
            if (selected === value) opt.selected = true;
            selectEl.appendChild(opt);
        });
    }

    function getFormPicker(form, className) {
        return form.querySelector('.' + className);
    }

    function refreshCreditAccounts(form, type, selected) {
        const picker = getFormPicker(form, 'sc-liability-picker');
        if (!picker || typeof window.axisRefreshSalaryComponentAccountPicker !== 'function') return;
        window.axisRefreshSalaryComponentAccountPicker(
            picker,
            type === 'earning' ? 'liability' : 'deductionCredit',
            selected || ''
        );
    }

    function toggleTypeFields(form, type, subType, options) {
        options = options || {};
        const expenseWrap = form.querySelector('.sc-expense-wrap');
        const isEarning = type === 'earning';
        const showExpense = isEarning;

        if (expenseWrap) {
            expenseWrap.classList.toggle('d-none', !showExpense);
        }

        const expensePicker = getFormPicker(form, 'sc-expense-picker');
        const expenseInput = form.querySelector('.sc-expense-account');
        if (expenseInput) {
            expenseInput.required = showExpense;
        }
        if (expensePicker && typeof window.axisRefreshSalaryComponentAccountPicker === 'function') {
            if (!showExpense) {
                window.axisRefreshSalaryComponentAccountPicker(expensePicker, 'expense', '');
            } else if (options.expenseAccountId) {
                window.axisRefreshSalaryComponentAccountPicker(expensePicker, 'expense', options.expenseAccountId);
            }
        }

        const liabilityLabel = form.querySelector('.sc-liability-label');
        const liabilityPicker = getFormPicker(form, 'sc-liability-picker');
        if (liabilityLabel) {
            liabilityLabel.innerHTML = isEarning
                ? 'Liability Ledger <span class="text-danger">*</span>'
                : 'Income/Liability Ledger <span class="text-danger">*</span>';
        }
        if (liabilityPicker) {
            liabilityPicker.dataset.placeholder = isEarning
                ? 'Select liability account...'
                : 'Select account...';
        }

        if (options.refreshAccounts) {
            refreshCreditAccounts(form, type, options.selectedAccount);
        }
    }

    function initSalaryPickers(scope) {
        const run = function () {
            if (typeof window.axisInitSalaryComponentAccountPickers !== 'function') {
                return false;
            }
            window.axisInitSalaryComponentAccountPickers(scope || document);
            return true;
        };

        if (run()) {
            return;
        }

        let attempts = 0;
        const wait = setInterval(function () {
            attempts += 1;
            if (run() || attempts > 80) {
                clearInterval(wait);
            }
        }, 50);
    }

    function bindSalaryComponentForm(form) {
        if (!form || form.dataset.scBound === '1') return;
        form.dataset.scBound = '1';

        const typeSelect = form.querySelector('.sc-type');
        const subTypeSelect = form.querySelector('.sc-sub-type');

        typeSelect?.addEventListener('change', function () {
            fillSubTypes(subTypeSelect, this.value, '');
            toggleTypeFields(form, this.value, '', { refreshAccounts: true });
        });

        subTypeSelect?.addEventListener('change', function () {
            toggleTypeFields(form, typeSelect.value, this.value);
        });
    }

    document.querySelectorAll('.sc-component-form').forEach(bindSalaryComponentForm);

    const addForm = document.getElementById('scAddForm');
    if (addForm && addForm.querySelector('.sc-type')?.value) {
        const type = addForm.querySelector('.sc-type').value;
        const subType = @json(old('sub_type'));
        fillSubTypes(addForm.querySelector('.sc-sub-type'), type, subType);
        toggleTypeFields(addForm, type, subType, {
            refreshAccounts: true,
            selectedAccount: @json(old('liability_account_id')),
            expenseAccountId: @json(old('expense_account_id')),
        });
    }

    document.getElementById('scAddModal')?.addEventListener('shown.bs.modal', function () {
        const form = document.getElementById('scAddForm');
        if (!form) return;
        initSalaryPickers(form);
        if (!form.querySelector('.sc-name')?.value) {
            const typeSelect = form.querySelector('.sc-type');
            if (!typeSelect.value) typeSelect.value = 'earning';
            fillSubTypes(form.querySelector('.sc-sub-type'), typeSelect.value, '');
            toggleTypeFields(form, typeSelect.value, '', { refreshAccounts: true });
        }
    });

    document.getElementById('scEditModal')?.addEventListener('shown.bs.modal', function () {
        initSalaryPickers(document.getElementById('scEditForm'));
        const form = document.getElementById('scEditForm');
        if (form?.querySelector('.sc-type')?.value) {
            toggleTypeFields(form, form.querySelector('.sc-type').value, form.querySelector('.sc-sub-type')?.value || '', {
                refreshAccounts: true,
                selectedAccount: form.querySelector('.sc-liability-account')?.value || '',
                expenseAccountId: form.querySelector('.sc-expense-account')?.value || '',
            });
        }
    });

    document.querySelectorAll('.btn-edit-sc').forEach(function (btn) {
        btn.addEventListener('click', function () {
            const form = document.getElementById('scEditForm');
            form.action = this.dataset.url;
            form.querySelector('.sc-name').value = this.dataset.name;
            const typeSelect = form.querySelector('.sc-type');
            typeSelect.value = this.dataset.type;
            fillSubTypes(form.querySelector('.sc-sub-type'), this.dataset.type, this.dataset.subType);
            toggleTypeFields(form, this.dataset.type, this.dataset.subType, {
                refreshAccounts: true,
                selectedAccount: this.dataset.liabilityAccountId || '',
                expenseAccountId: this.dataset.expenseAccountId || '',
            });
            const liabilityInput = form.querySelector('.sc-liability-account');
            const expenseInput = form.querySelector('.sc-expense-account');
            if (liabilityInput) liabilityInput.value = this.dataset.liabilityAccountId || '';
            if (expenseInput) expenseInput.value = this.dataset.expenseAccountId || '';
            form.querySelector('.sc-inactive').checked = this.dataset.active !== '1';
            if (typeof bootstrap !== 'undefined') {
                bootstrap.Modal.getOrCreateInstance(document.getElementById('scEditModal')).show();
            }
        });
    });

    @if($errors->any())
    const errorModalId = @json(old('_form') === 'edit' ? 'scEditModal' : 'scAddModal');
    const errorModalEl = document.getElementById(errorModalId);
    if (errorModalEl && typeof bootstrap !== 'undefined') {
        errorModalEl.addEventListener('shown.bs.modal', function () {
            initSalaryPickers(document.getElementById(errorModalId === 'scEditModal' ? 'scEditForm' : 'scAddForm'));
        }, { once: true });
        bootstrap.Modal.getOrCreateInstance(errorModalEl).show();
    }
    @endif

    @if($canCreateCoaAccount ?? false)
    (function () {
        const quickAddModalEl = document.getElementById('scCoaQuickAddModal');
        const quickAddForm = document.getElementById('scCoaQuickAddForm');
        if (!quickAddModalEl || !quickAddForm) return;

        const sectionMap = @json($coaQuickAddSections);
        let parentPickerTree = @json($parentPickerTree);
        let parentPickerAccounts = @json($parentPickerAccounts);
        const parentAccountMap = Object.fromEntries(parentPickerAccounts.map(function (acc) {
            return [String(acc.id), acc];
        }));
        const quickAddUrl = @json(route('coa.quick-store'));
        const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';
        const sectionSelect = quickAddForm.querySelector('.sc-coa-section');
        const errorEl = document.getElementById('scCoaQuickAddError');
        const submitBtn = document.getElementById('scCoaQuickAddSubmit');
        const saveNewBtn = quickAddForm.querySelector('.sc-coa-save-new');
        const parentPickerEl = document.getElementById('scCoaQuickParentPicker');
        const parentInlineAdd = document.getElementById('scCoaParentInlineAdd');
        let activePicker = null;
        let saveAction = 'save';

        function readJsonScript(id, fallback) {
            const el = document.getElementById(id);
            if (!el?.textContent?.trim()) return fallback;
            try { return JSON.parse(el.textContent); } catch (e) { return fallback; }
        }

        function accountsMapFromList(list) {
            return Object.fromEntries(list.map(function (acc) { return [String(acc.id), acc]; }));
        }

        function currentSectionType() {
            const selected = sectionSelect?.selectedOptions?.[0];
            return selected?.dataset.accountType || '';
        }

        function fillSectionOptions(listKey) {
            if (!sectionSelect) return;
            sectionSelect.innerHTML = '';
            Object.entries(sectionMap[listKey] || {}).forEach(function ([value, meta]) {
                const opt = document.createElement('option');
                opt.value = value;
                opt.textContent = meta.label;
                opt.dataset.accountType = meta.type;
                sectionSelect.appendChild(opt);
            });
        }

        function refreshParentPicker(typeFilter, selectedId) {
            if (!parentPickerEl || typeof window.axisRefreshCoaParentPicker !== 'function') return;
            window.axisRefreshCoaParentPicker(parentPickerEl, {
                tree: parentPickerTree,
                accountsMap: parentAccountMap,
                typeFilter: typeFilter || '',
            });
            if (selectedId !== undefined) {
                window.axisSetCoaParentPickerValue(parentPickerEl, selectedId || '');
            }
        }

        function showError(message) {
            if (!errorEl) return;
            errorEl.textContent = message;
            errorEl.classList.remove('d-none');
        }

        function hideError() {
            errorEl?.classList.add('d-none');
        }

        function resetQuickForm(preserveType) {
            const listKey = quickAddForm.dataset.listKey || 'liability';
            const sectionValue = preserveType ? sectionSelect?.value : '';
            quickAddForm.querySelector('.sc-coa-name').value = '';
            quickAddForm.querySelector('.sc-coa-code').value = '';
            fillSectionOptions(listKey);
            if (preserveType && sectionValue) {
                sectionSelect.value = sectionValue;
            }
            hideError();
            parentInlineAdd?.classList.remove('is-open');
            refreshParentPicker(currentSectionType(), '');
        }

        function initParentPickerOnce() {
            if (!parentPickerEl || typeof window.axisInitCoaParentPicker !== 'function') return;
            window.axisInitCoaParentPicker(parentPickerEl, {
                tree: parentPickerTree,
                accountsMap: parentAccountMap,
                typeFilter: currentSectionType(),
                onAddNew: function () {
                    parentInlineAdd?.classList.add('is-open');
                    parentInlineAdd?.querySelector('.sc-coa-parent-name')?.focus();
                },
            });
        }

        sectionSelect?.addEventListener('change', function () {
            refreshParentPicker(currentSectionType(), parentPickerEl?.querySelector('.coa-parent-picker-input')?.value || '');
        });

        parentInlineAdd?.querySelector('.sc-coa-parent-cancel')?.addEventListener('click', function () {
            parentInlineAdd.classList.remove('is-open');
            parentInlineAdd.querySelector('.sc-coa-parent-error')?.classList.add('d-none');
        });

        parentInlineAdd?.querySelector('.sc-coa-parent-create')?.addEventListener('click', function () {
            const nameInput = parentInlineAdd.querySelector('.sc-coa-parent-name');
            const codeInput = parentInlineAdd.querySelector('.sc-coa-parent-code');
            const parentError = parentInlineAdd.querySelector('.sc-coa-parent-error');
            const name = nameInput?.value.trim() || '';
            if (!name) {
                if (parentError) {
                    parentError.textContent = 'Parent account name is required.';
                    parentError.classList.remove('d-none');
                }
                nameInput?.focus();
                return;
            }

            const payload = new FormData();
            payload.append('intent', 'parent');
            payload.append('name', name);
            payload.append('code', codeInput?.value || '');
            payload.append('account_section', sectionSelect?.value || '');

            fetch(quickAddUrl, {
                method: 'POST',
                headers: { 'X-CSRF-TOKEN': csrfToken, 'Accept': 'application/json' },
                body: payload,
            }).then(function (response) {
                return response.json().then(function (data) {
                    if (!response.ok) throw data;
                    return data;
                });
            }).then(function (data) {
                parentPickerTree = data.parentPickerTree || parentPickerTree;
                parentPickerAccounts = data.parentPickerAccounts || parentPickerAccounts;
                Object.assign(parentAccountMap, accountsMapFromList(parentPickerAccounts));
                refreshParentPicker(currentSectionType(), data.account?.id || '');
                parentInlineAdd.classList.remove('is-open');
                if (nameInput) nameInput.value = '';
                if (codeInput) codeInput.value = '';
                parentError?.classList.add('d-none');
            }).catch(function (error) {
                const message = error?.message
                    || (error?.errors ? Object.values(error.errors).flat().join(' ') : 'Unable to create parent account.');
                if (parentError) {
                    parentError.textContent = message;
                    parentError.classList.remove('d-none');
                }
            });
        });

        window.axisOpenSalaryComponentCoaQuickAdd = function (picker) {
            activePicker = picker;
            const listKey = picker.dataset.listKey || 'liability';
            picker.querySelector('.voucher-account-picker-menu')?.classList.add('d-none');
            picker.querySelector('.voucher-account-picker-toggle')?.setAttribute('aria-expanded', 'false');
            quickAddForm.dataset.listKey = listKey;
            resetQuickForm(false);
            initParentPickerOnce();
            refreshParentPicker(currentSectionType(), '');

            if (typeof bootstrap !== 'undefined') {
                bootstrap.Modal.getOrCreateInstance(quickAddModalEl, { backdrop: 'static', focus: true }).show();
            }
        };

        function submitQuickForm(event) {
            event.preventDefault();
            if (!activePicker) return;

            hideError();
            submitBtn.disabled = true;
            saveNewBtn.disabled = true;
            submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Saving...';

            const payload = new FormData(quickAddForm);
            payload.append('list_key', quickAddForm.dataset.listKey || activePicker.dataset.listKey || '');
            payload.append('intent', 'ledger');
            payload.append('save_action', saveAction);

            fetch(quickAddUrl, {
                method: 'POST',
                headers: { 'X-CSRF-TOKEN': csrfToken, 'Accept': 'application/json' },
                body: payload,
            }).then(function (response) {
                return response.json().then(function (data) {
                    if (!response.ok) throw data;
                    return data;
                });
            }).then(function (data) {
                if (typeof window.axisRefreshSalaryComponentAccountTrees === 'function' && data.trees) {
                    window.axisRefreshSalaryComponentAccountTrees(data.trees, activePicker, data.account?.id);
                }
                parentPickerTree = data.parentPickerTree || parentPickerTree;
                parentPickerAccounts = data.parentPickerAccounts || parentPickerAccounts;
                Object.assign(parentAccountMap, accountsMapFromList(parentPickerAccounts));

                if (saveAction === 'save_new') {
                    resetQuickForm(true);
                    initParentPickerOnce();
                    refreshParentPicker(currentSectionType(), '');
                    return;
                }

                if (typeof bootstrap !== 'undefined') {
                    bootstrap.Modal.getOrCreateInstance(quickAddModalEl).hide();
                }
            }).catch(function (error) {
                const message = error?.message
                    || (error?.errors ? Object.values(error.errors).flat().join(' ') : 'Unable to create account.');
                showError(message);
            }).finally(function () {
                saveAction = 'save';
                submitBtn.disabled = false;
                saveNewBtn.disabled = false;
                submitBtn.innerHTML = '<i class="bi bi-check-lg me-1"></i>Save';
            });
        }

        quickAddForm.addEventListener('submit', submitQuickForm);
        saveNewBtn?.addEventListener('click', function () {
            saveAction = 'save_new';
            quickAddForm.requestSubmit();
        });
    })();
    @endif
})();
</script>
@endpush
