@extends('layouts.app')

@section('title', 'Edit Salary Group')
@section('heading', 'Edit Salary Group')

@section('content')
    <x-card
        x-data="salaryGroupBuilder()"
        x-init="init()"
    >
        <form action="{{ route('salary-groups.update', $salaryGroup) }}" method="POST" class="space-y-6" novalidate data-salary-group-form="edit">
            @csrf
            @method('PUT')

            <div class="max-w-xl space-y-4">
                <div>
                    <label class="block text-sm font-medium text-slate-700">Name <span class="text-red-500">*</span></label>
                    <input type="text" name="name" value="{{ old('name', $salaryGroup->name) }}" class="mt-1 block w-full rounded-lg border border-slate-300 px-3 py-2">
                    @error('name')<p class="mt-1 text-sm text-red-600">{{ $message }}</p>@enderror
                    <p data-js-error="name" class="mt-1 text-sm text-red-600 hidden"></p>
                </div>
            </div>
            <hr>
            <div class="grid gap-5 lg:grid-cols-12">
                <div class="lg:col-span-8 cursor-no-drop">
                  <div class="pointer-events-none opacity-50">
                    <h3 class="text-sm font-semibold text-slate-800 mb-2 text-center">Salary Structure</h3>

                    <template x-for="(row, index) in components" :key="row.uid">
                        <div>
                            <input type="hidden" :name="`components[${index}][salary_component_id]`" :value="row.salary_component_id">
                            <input type="hidden" :name="`components[${index}][name]`" :value="row.name">
                            <input type="hidden" :name="`components[${index}][type]`" :value="row.type">
                            <input type="hidden" :name="`components[${index}][value_type]`" :value="row.value_type">
                            <input type="hidden" :name="`components[${index}][value]`" :value="row.value ?? ''">
                            <input type="hidden" :name="`components[${index}][is_custom]`" :value="row.is_custom ? 1 : 0">
                        </div>
                    </template>
                    <template x-for="(deletedId, dIndex) in deletedComponentIds" :key="'deleted-' + dIndex + '-' + deletedId">
                        <input type="hidden" :name="`deleted_component_ids[${dIndex}]`" :value="deletedId">
                    </template>

                    <div class="grid grid-cols-1 gap-4 lg:grid-cols-2">
                        <div>
                            <h4 class="mb-2 text-sm font-semibold text-slate-700">Earnings</h4>
                            <table class="w-full text-sm border border-slate-200 rounded-lg">
                                <thead class="bg-slate-50">
                                    <tr>
                                        <th class="px-3 py-2 text-left font-medium">Name</th>
                                        <th class="px-3 py-2 text-left font-medium">Value Type</th>
                                        <th class="px-3 py-2 text-right font-medium">Monthly</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <template x-for="row in earningsRows()" :key="row.uid">
                                        <tr class="border-t border-slate-200">
                                            <td class="px-3 py-2">
                                                <template x-if="row.is_custom">
                                                    <input type="text" x-model="row.name" class="w-full rounded border border-slate-300 px-2 py-1 text-xs" placeholder="Component name" required>
                                                </template>
                                                <template x-if="!row.is_custom">
                                                    <span x-text="row.name"></span>
                                                </template>
                                            </td>
                                            <td class="px-3 py-2">
                                                <select x-model="row.value_type" class="w-full rounded border border-slate-300 px-2 py-1 text-xs">
                                                    <option value="fixed">Fixed</option>
                                                    <option value="variable">Variable</option>
                                                    <option value="basic_percent">Basic Percent</option>
                                                    <option value="ctc_percent">CTC Percent</option>
                                                </select>
                                            </td>
                                            <td class="px-3 py-2 text-right">
                                                <input type="number" step="0.01" min="0" x-model.number="row.value" class="w-24 rounded border border-slate-300 px-2 py-1 text-right text-xs">
                                                <button type="button" class="text-red-600" title="Remove" @click="removeRow(row.uid)" x-show="!row.is_fixed"><i class="bi bi-trash3"></i></button>
                                            </td>
                                        </tr>
                                    </template>
                                    <tr class="border-t border-slate-200">
                                        <td class="px-3 py-2">Special Allowance</td>
                                        <td class="px-3 py-2">
                                            <span class="text-xs text-slate-700">Balancing Amount of CTC</span>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                            <div class="mt-3 grid grid-cols-1 gap-2 sm:grid-cols-3">
                                <select x-model="selectedEarningId" class="rounded-lg border border-slate-300 px-3 py-2 text-sm sm:col-span-2">
                                    <option value="">Select Earning Component</option>
                                    <template x-for="item in earningCatalog()" :key="item.id">
                                        <option :value="item.id" x-text="item.name"></option>
                                    </template>
                                </select>
                                <button type="button" class="rounded-lg bg-slate-700 text-white px-3 py-2 text-sm" @click="addRow('earning', selectedEarningId)">Add</button>
                            </div>
                        </div>

                        <div>
                            <h4 class="mb-2 text-sm font-semibold text-slate-700">Deductions</h4>
                            <table class="w-full text-sm border border-slate-200 rounded-lg">
                                <thead class="bg-slate-50">
                                    <tr>
                                        <th class="px-3 py-2 text-left font-medium">Name</th>
                                        <th class="px-3 py-2 text-left font-medium">Value Type</th>
                                        <th class="px-3 py-2 text-right font-medium">Monthly</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr class="border-t border-slate-200">
                                        <td class="px-3 py-2">PF</td>
                                        <td class="px-3 py-2">
                                            <span class="text-xs text-slate-700">System Calculated</span>
                                        </td>
                                    </tr>
                                    <tr class="border-t border-slate-200">
                                        <td class="px-3 py-2">ESI</td>
                                        <td class="px-3 py-2">
                                            <span class="text-xs text-slate-700">System Calculated</span>
                                        </td>
                                    </tr>
                                    <tr class="border-t border-slate-200">
                                        <td class="px-3 py-2">PT</td>
                                        <td class="px-3 py-2">
                                            <span class="text-xs text-slate-700">System Calculated</span>
                                        </td>
                                    </tr>
                                    <template x-for="row in deductionRows()" :key="row.uid">
                                        <tr class="border-t border-slate-200">
                                            <td class="px-3 py-2">
                                                <template x-if="row.is_custom">
                                                    <input type="text" x-model="row.name" class="w-full rounded border border-slate-300 px-2 py-1 text-xs" placeholder="Component name" required>
                                                </template>
                                                <template x-if="!row.is_custom">
                                                    <span x-text="row.name"></span>
                                                </template>
                                            </td>
                                            <td class="px-3 py-2">
                                                <select x-model="row.value_type" class="w-full rounded border border-slate-300 px-2 py-1 text-xs">
                                                    <option value="fixed">Fixed</option>
                                                    <option value="variable">Variable</option>
                                                    <option value="basic_percent">Basic Percent</option>
                                                    <option value="ctc_percent">CTC Percent</option>
                                                </select>
                                            </td>
                                            <td class="px-3 py-2 text-right">
                                                <input type="number" step="0.01" min="0" x-model.number="row.value" class="w-24 rounded border border-slate-300 px-2 py-1 text-right text-xs">
                                                <button type="button" class="text-red-600" title="Remove" @click="removeRow(row.uid)" x-show="!row.is_fixed"><i class="bi bi-trash3"></i></button>
                                            </td>
                                        </tr>
                                    </template>
                                </tbody>
                            </table>
                            <div class="mt-3 grid grid-cols-1 gap-2 sm:grid-cols-3">
                                <select x-model="selectedDeductionId" class="rounded-lg border border-slate-300 px-3 py-2 text-sm sm:col-span-2">
                                    <option value="">Select Deduction Component</option>
                                    <template x-for="item in deductionCatalog()" :key="item.id">
                                        <option :value="item.id" x-text="item.name"></option>
                                    </template>
                                </select>
                                <button type="button" class="rounded-lg bg-slate-700 text-white px-3 py-2 text-sm" @click="addRow('deduction', selectedDeductionId)">Add</button>
                            </div>
                        </div>
                    </div>
                    @php
                        $componentNameErrors = collect($errors->getMessages())
                            ->filter(fn ($msgs, $key) => preg_match('/^components\.\d+\.name$/', $key))
                            ->flatten();
                    @endphp
                    @if($errors->has('components') || $componentNameErrors->isNotEmpty())
                        <div class="mt-2 space-y-1">
                            @error('components')<p class="text-xs text-red-600">{{ $message }}</p>@enderror
                            @foreach($componentNameErrors as $message)
                                <p class="text-xs text-red-600">{{ $message }}</p>
                            @endforeach
                        </div>
                    @endif
                    <p data-js-error="components" class="mt-2 text-xs text-red-600 hidden"></p>
                  </div>
                </div>

                <div class="lg:col-span-4">
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-2">Assign employees to this group</label>
                        <p class="text-xs text-slate-500 mb-2">Select employees who belong to this salary group.</p>
                        <div class="max-h-64 overflow-y-auto rounded-lg border border-slate-300 p-3 space-y-2">
                            @foreach($users as $u)
                                <label class="flex items-center gap-2">
                                    <input type="checkbox" name="user_ids[]" value="{{ $u->id }}" {{ in_array($u->id, $salaryGroup->users->pluck('id')->all()) ? 'checked' : '' }} class="rounded border-slate-300">
                                    <span class="text-sm">{{ $u->name }} ({{ $u->email }})</span>
                                </label>
                            @endforeach
                        </div>
                    </div>
                </div>
            </div>

            <div class="flex gap-2">
                <button type="submit" class="rounded-lg bg-primary px-4 py-2 text-sm font-medium text-white">Update</button>
                <a href="{{ route('salary-groups.index') }}" class="rounded-lg bg-slate-100 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-200">Cancel</a>
            </div>
        </form>
    </x-card>

    <script>
        function salaryGroupBuilder() {
            return {
                catalog: { fixed: [], dropdown: [] },
                components: @json(old('components', $existingRows ?? [])),
                selectedEarningId: '',
                selectedDeductionId: '',
                deletedComponentIds: @json(old('deleted_component_ids', [])),
                uidCount: 0,
                init() {
                    this.components = (this.components || []).map((row) => ({
                        uid: this.nextUid(),
                        salary_component_id: Number(row.salary_component_id),
                        name: row.name || '',
                        type: row.type || 'earning',
                        value_type: row.value_type || 'fixed',
                        value: row.value !== null && row.value !== undefined ? Number(row.value) : 0,
                        is_locked: !!row.is_locked,
                        is_fixed: !!row.is_fixed,
                        is_custom: !!row.is_custom,
                    }));
                    this.fetchCatalog();
                },
                nextUid() {
                    this.uidCount += 1;
                    return 'row-' + this.uidCount + '-' + Date.now();
                },
                fetchCatalog() {
                    fetch(@json(route('salary-groups.components.catalog')))
                        .then((res) => res.json())
                        .then((data) => {
                            this.catalog = data || { fixed: [], dropdown: [] };
                            this.ensureFixedStructureRows();
                            this.refreshSelect2();
                        })
                        .catch(() => { this.catalog = { fixed: [], dropdown: [] }; });
                },
                refreshSelect2() {
                    this.$nextTick(() => {
                        if (!window.jQuery || !window.jQuery.fn || !window.jQuery.fn.select2) {
                            return;
                        }

                        window.jQuery(this.$el).find('.js-select2').each(function () {
                            const $select = window.jQuery(this);
                            if ($select.data('select2')) return;

                            const inlineWidth = $select[0].style.width;
                            const inlineMinWidth = $select[0].style.minWidth;

                            $select.select2({
                                width: inlineWidth ? 'style' : '100%',
                                minimumResultsForSearch: Infinity,
                                dropdownCssClass: 'site-select2-dropdown',
                                templateResult: function (data) {
                                    if (data.element && data.element.hidden) return null;
                                    return data.text;
                                }
                            });

                            const $container = $select.next('.select2-container');
                            $container.addClass('site-select2');

                            if ($select.hasClass('text-xs')) {
                                $container.addClass('site-select2-xs');
                            }
                            if (inlineMinWidth) {
                                $container.css('min-width', inlineMinWidth);
                            }
                        });
                    });
                },
                usedCatalogIds() {
                    const ids = new Set();
                    for (const row of this.components) {
                        if (row.is_custom) continue;
                        const id = Number(row.salary_component_id);
                        if (Number.isNaN(id) || id === 0) continue;
                        ids.add(id);
                    }
                    return ids;
                },
                earningCatalog() {
                    const used = this.usedCatalogIds();
                    return (this.catalog.dropdown || []).filter((item) => {
                        if (item.type !== 'earnings') return false;
                        if (item.addable) return true;
                        return !used.has(Number(item.id));
                    });
                },
                deductionCatalog() {
                    const used = this.usedCatalogIds();
                    return (this.catalog.dropdown || []).filter((item) => {
                        if (item.type !== 'deductions') return false;
                        if (item.addable) return true;
                        return !used.has(Number(item.id));
                    });
                },
                ensureFixedStructureRows() {
                    const takenNames = new Set(
                        this.components.map((r) => String(r.name || '').trim().toLowerCase()).filter(Boolean)
                    );
                    for (const item of this.catalog.fixed || []) {
                        if (item.type !== 'earnings') continue;
                        const nameKey = String(item.name || '').trim().toLowerCase();
                        if (!nameKey || takenNames.has(nameKey)) continue;
                        takenNames.add(nameKey);
                        const id = Number(item.id);
                        this.components.push({
                            uid: this.nextUid(),
                            salary_component_id: id,
                            name: item.name || 'Component',
                            type: 'earning',
                            value_type: item.value_type || 'fixed',
                            value: Number(item.monthly || 0),
                            is_fixed: true,
                            is_custom: false,
                        });
                    }
                },
                earningsRows() {
                    return this.components.filter((row) => row.type === 'earning' || row.type === 'earnings');
                },
                deductionRows() {
                    return this.components.filter((row) => row.type === 'deduction' || row.type === 'deductions');
                },
                addRow(type, selectedId) {
                    const componentId = Number(selectedId);
                    if (!componentId) return;
                    const item = [...(this.catalog.dropdown || []), ...(this.catalog.fixed || [])].find((row) => Number(row.id) === componentId);
                    if (!item) return;
                    const normalizedType = type === 'deduction' ? 'deduction' : 'earning';
                    if (!item.addable) {
                        const alreadyExists = this.components.some(
                            (row) => !row.is_custom && Number(row.salary_component_id) === componentId
                        );
                        if (alreadyExists) {
                            return;
                        }
                    }
                    if (item.addable) {
                        this.components.push({
                            uid: this.nextUid(),
                            salary_component_id: componentId,
                            name: null,
                            type: normalizedType,
                            value_type: item.value_type || 'fixed',
                            value: Number(item.monthly || 0),
                            is_locked: false,
                            is_fixed: false,
                            is_custom: true,
                        });
                    } else {
                        this.components.push({
                            uid: this.nextUid(),
                            salary_component_id: componentId,
                            name: item.name || 'Component',
                            type: normalizedType,
                            value_type: item.value_type || 'fixed',
                            value: Number(item.monthly || 0),
                            is_fixed: false,
                            is_custom: false,
                        });
                    }
                    if (normalizedType === 'earning') this.selectedEarningId = '';
                    if (normalizedType === 'deduction') this.selectedDeductionId = '';
                    this.refreshSelect2();
                },
                removeRow(uid) {
                    const row = this.components.find((item) => item.uid === uid);
                    if (row && !row.is_locked && !row.is_fixed) {
                        const id = Number(row.salary_component_id);
                        if (id > 0 && !this.deletedComponentIds.includes(id)) {
                            this.deletedComponentIds.push(id);
                        }
                    }
                    this.components = this.components.filter(
                        (rowItem) => rowItem.uid !== uid || rowItem.is_locked || rowItem.is_fixed
                    );
                    this.refreshSelect2();
                },
            };
        }
    </script>
@endsection

@push('scripts')
<script src="{{ asset('js/form-validation.js') }}"></script>
<script src="{{ asset('js/form-text-rules.js') }}"></script>
<script src="{{ asset('js/salary-group-form-validation.js') }}"></script>
@endpush
