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

@push('styles')
<link href="https://cdn.jsdelivr.net/npm/quill@2.0.2/dist/quill.snow.css" rel="stylesheet">
<style>
    .payroll-rich-editor { min-height: 220px; }
    .payroll-rich-editor .ql-editor { min-height: 200px; font-size: 14px; }
    .payroll-slab-table input.form-control { min-width: 90px; }
    .payroll-slab-table .slab-label { min-width: 70px; }
</style>
@endpush

@section('content')
<div class="page-header">
    <div>
        <h1 class="page-title">Payroll Settings</h1>
        <p class="page-subtitle">Configure payroll module, salary tax rules, and transfer letter templates</p>
    </div>
</div>

@include('settings._tabs', ['active' => 'payroll'])

@if(session('success'))
<div class="alert alert-success alert-dismissible d-flex gap-2 mb-4">
    <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

<div class="row g-4">

    {{-- Payroll Module --}}
    <div class="col-12">
        <div class="card">
            <div class="card-header"><i class="bi bi-wallet2 me-2 text-primary"></i>Payroll Module</div>
            <div class="card-body">
                <p class="text-muted mb-3" style="font-size:13px">
                    Turn on the full payroll module for this company. When off, only the Employees list is available so you can still maintain employee records.
                </p>
                <form method="POST" action="{{ route('settings.payroll.module.update') }}">
                    @csrf @method('PUT')
                    <div class="p-3 rounded-2 border bg-light">
                        <div class="form-check form-switch mb-2">
                            <input class="form-check-input" type="checkbox" name="use_payroll_module" value="1" id="usePayrollModule" role="switch"
                                   {{ ($settings['use_payroll_module'] ?? '0') === '1' ? 'checked' : '' }}>
                            <label class="form-check-label fw-semibold" for="usePayrollModule">Use Payroll Module</label>
                        </div>
                        <div class="text-muted" style="font-size:12px">
                            Shows the Payroll menu (Employees, Departments, Designations, Projects, Branches, Salary Components, Payroll Sheet, Payroll Journal, Pay Slip, Bank Transfer Letter, etc.)
                            and moves Employees under it. Off by default for new companies.
                        </div>
                    </div>
                    <div class="mt-3 text-end">
                        <button type="submit" class="btn btn-primary"><i class="bi bi-check-lg me-1"></i>Save changes</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    {{-- Salary Tax Calculation --}}
    <div class="col-12">
        <div class="card">
            <div class="card-header"><i class="bi bi-percent me-2 text-primary"></i>Salary Tax Calculation</div>
            <div class="card-body">
                <p class="text-muted mb-4" style="font-size:13px">
                    Rules used to calculate income tax on salaries. Update the boxed values whenever the Government revises them.
                </p>

                <form method="POST" action="{{ route('settings.payroll.tax.update') }}" id="payrollTaxForm">
                    @csrf @method('PUT')

                    <h6 class="fw-semibold mb-3">Non-Taxable Income Limit for Salaried Employees</h6>
                    <div class="d-flex flex-wrap align-items-center gap-2 mb-4">
                        <input type="number" name="payroll_tax_numerator" class="form-control" style="width:70px"
                               value="{{ old('payroll_tax_numerator', $settings['payroll_tax_numerator']) }}" min="1" required>
                        <span>/</span>
                        <input type="number" name="payroll_tax_denominator" class="form-control" style="width:70px"
                               value="{{ old('payroll_tax_denominator', $settings['payroll_tax_denominator']) }}" min="1" required>
                        <span>of Gross Income or</span>
                        <input type="number" name="payroll_tax_max_exempt" class="form-control" style="width:130px"
                               value="{{ old('payroll_tax_max_exempt', $settings['payroll_tax_max_exempt']) }}" min="0" step="1" required>
                        <span>Whichever is lower.</span>
                    </div>

                    <h6 class="fw-semibold mb-3">Tax Calculation Slabs</h6>
                    <div class="table-responsive mb-3">
                        <table class="table table-sm table-bordered align-middle payroll-slab-table" id="taxSlabTable">
                            <thead class="table-light">
                                <tr>
                                    <th style="width:90px">Slab</th>
                                    <th style="width:90px">Currency</th>
                                    <th>Amount</th>
                                    <th style="width:120px">Tax Rate %</th>
                                    <th style="width:50px"></th>
                                </tr>
                            </thead>
                            <tbody id="taxSlabBody">
                                @foreach($taxSlabs as $i => $slab)
                                <tr data-slab-index="{{ $i }}" data-slab-type="{{ $slab['label'] === 'Rest' ? 'rest' : ($i === 0 ? 'first' : 'next') }}">
                                    <td>
                                        <input type="hidden" name="slabs[{{ $i }}][label]" value="{{ $slab['label'] }}" class="slab-label-input">
                                        <span class="slab-label fw-semibold">{{ $slab['label'] }}</span>
                                    </td>
                                    <td>
                                        <input type="text" name="slabs[{{ $i }}][currency]" class="form-control form-control-sm"
                                               value="{{ $slab['currency'] }}" maxlength="10" required>
                                    </td>
                                    <td>
                                        @if($slab['label'] === 'Rest')
                                            <input type="hidden" name="slabs[{{ $i }}][amount]" value="rest">
                                            <span class="text-muted">Rest amount</span>
                                        @else
                                            <input type="number" name="slabs[{{ $i }}][amount]" class="form-control form-control-sm"
                                                   value="{{ $slab['amount'] }}" min="0" step="1" required>
                                        @endif
                                    </td>
                                    <td>
                                        <input type="number" name="slabs[{{ $i }}][rate]" class="form-control form-control-sm"
                                               value="{{ $slab['rate'] }}" min="0" max="100" step="0.01" required>
                                    </td>
                                    <td class="text-center">
                                        @if($slab['label'] !== 'First' && $slab['label'] !== 'Rest')
                                        <button type="button" class="btn btn-outline-danger btn-sm btn-remove-slab" title="Remove slab"><i class="bi bi-trash"></i></button>
                                        @endif
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                    <button type="button" class="btn btn-outline-secondary btn-sm mb-4" id="btnAddSlab"><i class="bi bi-plus-lg me-1"></i>Add slab</button>

                    <h6 class="fw-semibold mb-2">Investment Allowance (on Invested Amount)</h6>
                    <p class="text-muted mb-3" style="font-size:12px">
                        Eligible Investment = lower of (% of Total Income), Actual Investment Amount, and Maximum Allowable Limit.
                        Tax Rebate = Eligible Investment × Rebate Rate.
                    </p>
                    <div class="row g-3 mb-4">
                        <div class="col-md-4">
                            <label class="form-label fw-semibold">% of Total Income</label>
                            <div class="input-group">
                                <input type="number" name="payroll_investment_pct" class="form-control"
                                       value="{{ old('payroll_investment_pct', $settings['payroll_investment_pct']) }}" min="0" max="100" step="0.01" required>
                                <span class="input-group-text">%</span>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-semibold">Maximum Allowable Limit</label>
                            <input type="number" name="payroll_investment_max" class="form-control"
                                   value="{{ old('payroll_investment_max', $settings['payroll_investment_max']) }}" min="0" step="1" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-semibold">Tax Rebate Rate on Eligible Investment</label>
                            <div class="input-group">
                                <input type="number" name="payroll_investment_rebate_rate" class="form-control"
                                       value="{{ old('payroll_investment_rebate_rate', $settings['payroll_investment_rebate_rate']) }}" min="0" max="100" step="0.01" required>
                                <span class="input-group-text">%</span>
                            </div>
                        </div>
                    </div>
                </form>

                <div class="d-flex justify-content-between align-items-center">
                    <form method="POST" action="{{ route('settings.payroll.tax.reset') }}" class="d-inline"
                          onsubmit="return confirm('Reset salary tax calculation to default values?')">
                        @csrf
                        <button type="submit" class="btn btn-outline-secondary">
                            <i class="bi bi-arrow-counterclockwise me-1"></i>Reset to defaults
                        </button>
                    </form>
                    <button type="submit" form="payrollTaxForm" class="btn btn-primary"><i class="bi bi-check-lg me-1"></i>Save changes</button>
                </div>
            </div>
        </div>
    </div>

    {{-- Salary Transfer Letter --}}
    <div class="col-12">
        <div class="card">
            <div class="card-header"><i class="bi bi-envelope-paper me-2 text-primary"></i>Header and Footer for Salary Transfer Letter</div>
            <div class="card-body">
                <p class="text-muted mb-4" style="font-size:13px">
                    Compose the header and footer that will appear on the Salary Transfer Letter. Use the toolbar to change font, size, color, bold and italic.
                </p>
                <form method="POST" action="{{ route('settings.payroll.letter.update') }}" id="payrollLetterForm">
                    @csrf @method('PUT')
                    <input type="hidden" name="salary_transfer_letter_header" id="letterHeaderInput">
                    <input type="hidden" name="salary_transfer_letter_footer" id="letterFooterInput">

                    <label class="form-label fw-semibold">Header</label>
                    <div id="letterHeaderEditor" class="payroll-rich-editor mb-4">{!! $settings['salary_transfer_letter_header'] !!}</div>

                    <label class="form-label fw-semibold">Footer</label>
                    <div id="letterFooterEditor" class="payroll-rich-editor mb-4">{!! $settings['salary_transfer_letter_footer'] !!}</div>

                    <div class="text-end">
                        <button type="submit" class="btn btn-primary"><i class="bi bi-check-lg me-1"></i>Save changes</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/quill@2.0.2/dist/quill.js"></script>
<script>
(function () {
    const toolbar = [
        [{ 'font': [] }, { 'size': ['small', false, 'large', 'huge'] }],
        [{ 'color': [] }],
        ['bold', 'italic'],
        [{ 'list': 'ordered' }, { 'list': 'bullet' }],
        ['clean']
    ];

    const headerQuill = new Quill('#letterHeaderEditor', { theme: 'snow', modules: { toolbar } });
    const footerQuill = new Quill('#letterFooterEditor', { theme: 'snow', modules: { toolbar } });

    document.getElementById('payrollLetterForm').addEventListener('submit', function () {
        document.getElementById('letterHeaderInput').value = headerQuill.root.innerHTML;
        document.getElementById('letterFooterInput').value = footerQuill.root.innerHTML;
    });

    const slabBody = document.getElementById('taxSlabBody');

    function reindexSlabs() {
        const rows = slabBody.querySelectorAll('tr');
        rows.forEach(function (row, index) {
            row.dataset.slabIndex = index;
            const isFirst = index === 0;
            const isRest = index === rows.length - 1;
            row.dataset.slabType = isRest ? 'rest' : (isFirst ? 'first' : 'next');

            const label = isFirst ? 'First' : (isRest ? 'Rest' : 'Next');
            row.querySelector('.slab-label').textContent = label;
            row.querySelector('.slab-label-input').name = 'slabs[' + index + '][label]';
            row.querySelector('.slab-label-input').value = label;

            const currencyInput = row.querySelector('input[name*="[currency]"]');
            currencyInput.name = 'slabs[' + index + '][currency]';

            const rateInput = row.querySelector('input[name*="[rate]"]');
            rateInput.name = 'slabs[' + index + '][rate]';

            const amountCell = row.children[2];
            if (isRest) {
                amountCell.innerHTML = '<input type="hidden" name="slabs[' + index + '][amount]" value="rest"><span class="text-muted">Rest amount</span>';
            } else {
                let amountInput = amountCell.querySelector('input[name*="[amount]"]');
                if (!amountInput) {
                    const val = '';
                    amountCell.innerHTML = '<input type="number" name="slabs[' + index + '][amount]" class="form-control form-control-sm" min="0" step="1" required>';
                    amountInput = amountCell.querySelector('input');
                    amountInput.value = val;
                } else {
                    amountInput.name = 'slabs[' + index + '][amount]';
                }
            }

            const actionCell = row.children[4];
            if (isFirst || isRest) {
                actionCell.innerHTML = '';
            } else if (!actionCell.querySelector('.btn-remove-slab')) {
                actionCell.innerHTML = '<button type="button" class="btn btn-outline-danger btn-sm btn-remove-slab" title="Remove slab"><i class="bi bi-trash"></i></button>';
            }
        });
    }

    document.getElementById('btnAddSlab').addEventListener('click', function () {
        const rows = slabBody.querySelectorAll('tr');
        const restRow = rows[rows.length - 1];
        const newRow = document.createElement('tr');
        newRow.innerHTML = `
            <td><input type="hidden" name="slabs[0][label]" value="Next" class="slab-label-input"><span class="slab-label fw-semibold">Next</span></td>
            <td><input type="text" name="slabs[0][currency]" class="form-control form-control-sm" value="BDT" maxlength="10" required></td>
            <td><input type="number" name="slabs[0][amount]" class="form-control form-control-sm" value="0" min="0" step="1" required></td>
            <td><input type="number" name="slabs[0][rate]" class="form-control form-control-sm" value="0" min="0" max="100" step="0.01" required></td>
            <td class="text-center"><button type="button" class="btn btn-outline-danger btn-sm btn-remove-slab" title="Remove slab"><i class="bi bi-trash"></i></button></td>
        `;
        slabBody.insertBefore(newRow, restRow);
        reindexSlabs();
    });

    slabBody.addEventListener('click', function (event) {
        const btn = event.target.closest('.btn-remove-slab');
        if (!btn) return;
        const rows = slabBody.querySelectorAll('tr');
        if (rows.length <= 2) return;
        btn.closest('tr').remove();
        reindexSlabs();
    });
})();
</script>
@endpush
