@extends('layouts.user')

@section('title', __('payrolls.payroll_preview'))
@section('page_title', __('payrolls.payroll_preview'))
@section('breadcrumb', __('payrolls.hr_payroll_short'))

@section('content')
@php
    $monthName = \Carbon\Carbon::createFromDate($year, $month, 1)->format('F');

    $grandBasic = money($employees->sum('basic_amount'));
    $grandAbsentDeduction = money($employees->sum('deduction_amount'));
    $grandOvertime = money($employees->sum('overtime_amount'));
    $grandGross = money($employees->sum('gross_salary'));
    $grandAdvance = money($employees->sum('max_deduction'));
    $grandPreNet = money($employees->sum('pre_net_salary'));
    $grandNet = money($employees->sum(function ($row) {
        return max(0, money($row->pre_net_salary) - money($row->max_deduction));
    }));
@endphp

<div class="w-full px-1 sm:px-2 lg:px-3 space-y-4">

    {{-- Header --}}
    <div class="border border-slate-200 bg-white overflow-hidden">
        <div class="bg-slate-800 px-4 py-4 text-white">
            <div class="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
                <div>
                    <p class="text-[10px] uppercase tracking-wide text-white/70">{{ __('payrolls.payroll_preview') }}</p>
                    <h1 class="text-lg font-bold">
                        {{ $monthName }} {{ $year }} {{ __('payrolls.payroll') }}
                    </h1>
                </div>

                <div class="grid grid-cols-2 gap-2 sm:grid-cols-4 text-xs">
                    <div class="border border-white/20 px-2 py-1">
                        {{ __('payrolls.employees') }}<br><b>{{ $employees->count() }}</b>
                    </div>
                    <div class="border border-white/20 px-2 py-1">
                        {{ __('payrolls.month') }}<br><b>{{ $monthName }}</b>
                    </div>
                    <div class="border border-white/20 px-2 py-1">
                        {{ __('payrolls.year') }}<br><b>{{ $year }}</b>
                    </div>
                    <div class="border border-white/20 px-2 py-1">
                        {{ __('payrolls.date') }}<br><b>{{ \Carbon\Carbon::parse($payrollDate)->format('d M') }}</b>
                    </div>
                </div>
            </div>
        </div>

        {{-- Summary --}}
        <div class="p-3">
            <div class="grid grid-cols-2 md:grid-cols-6 gap-2 text-xs">
                <div class="border px-2 py-2">{{ __('payrolls.basic') }}<br><b>{{ money_format_bd($grandBasic) }}</b></div>
                <div class="border px-2 py-2 text-rose-600">{{ __('payrolls.absent') }}<br><b>{{ money_format_bd($grandAbsentDeduction) }}</b></div>
                <div class="border px-2 py-2 text-emerald-600">{{ __('payrolls.ot') }}<br><b>{{ money_format_bd($grandOvertime) }}</b></div>
                <div class="border px-2 py-2 text-indigo-600">{{ __('payrolls.gross') }}<br><b>{{ money_format_bd($grandGross) }}</b></div>
                <div class="border px-2 py-2 text-amber-600">{{ __('payrolls.advance') }}<br><b>{{ money_format_bd($grandAdvance) }}</b></div>
                <div class="border px-2 py-2 text-sky-600">{{ __('payrolls.net') }}<br><b>{{ money_format_bd($grandNet) }}</b></div>
            </div>
        </div>
    </div>

    @if($employees->isEmpty())
        <div class="border border-dashed border-slate-300 bg-white p-6 text-center text-xs">
            {{ __('payrolls.no_employee_data_found') }}
            <div class="mt-3">
                <a href="{{ route('user.hr.payrolls.create') }}"
                   class="border px-3 py-1 text-xs">{{ __('payrolls.back') }}</a>
            </div>
        </div>
    @else
        <form method="POST" action="{{ route('user.hr.payrolls.store') }}" class="space-y-4" id="generatePayrollForm">
            @csrf

            <input type="hidden" name="payroll_month" value="{{ $month }}" id="payroll_month_hidden">
            <input type="hidden" name="payroll_year" value="{{ $year }}" id="payroll_year_hidden">
            <input type="hidden" name="payroll_date" value="{{ $payrollDate }}">

            {{-- Actions --}}
            <div class="flex justify-between items-center">
                <h2 class="text-sm font-bold">{{ __('payrolls.employee_payroll') }}</h2>

                <div class="flex gap-2 items-center">
                    <a href="{{ route('user.hr.payrolls.create') }}"
                       class="border px-3 py-1 text-xs">{{ __('payrolls.back') }}</a>

                    <button type="submit"
                            id="generateBtnTop"
                            class="bg-slate-900 px-4 py-1 text-xs text-white disabled:opacity-50 disabled:cursor-not-allowed">
                        {{ __('payrolls.generate') }}
                    </button>
                </div>
            </div>

            <div id="payrollFinalizedMessageTop" class="hidden -mt-2 text-right">
                <span class="inline-block border border-rose-200 bg-rose-50 px-3 py-1 text-xs text-rose-700">
                    {{ __('PayrollController.payroll_already_finalized') }}
                </span>
            </div>

            {{-- Table --}}
            <div class="border border-slate-200 bg-white overflow-x-auto">
                <table class="min-w-[1500px] w-full text-xs">
                    <thead class="bg-slate-100">
                        <tr>
                            <th class="px-2 py-2">{{ __('payrolls.employee') }}</th>
                            <th class="px-2 py-2">{{ __('payrolls.type') }}</th>
                            <th class="px-2 py-2">{{ __('payrolls.present_short') }}</th>
                            <th class="px-2 py-2">{{ __('payrolls.absent_short') }}</th>
                            <th class="px-2 py-2">{{ __('payrolls.leave_short') }}</th>
                            <th class="px-2 py-2">{{ __('payrolls.holiday_short') }}</th>
                            <th class="px-2 py-2">{{ __('payrolls.ot_short') }}</th>
                            <th class="px-2 py-2">{{ __('payrolls.roz_short') }}</th>
                            <th class="px-2 py-2">{{ __('payrolls.basic') }}</th>
                            <th class="px-2 py-2">{{ __('payrolls.deduct') }}</th>
                            <th class="px-2 py-2">{{ __('payrolls.ot') }}</th>
                            <th class="px-2 py-2">{{ __('payrolls.gross') }}</th>
                            <th class="px-2 py-2">{{ __('payrolls.advance') }}</th>
                            <th class="px-2 py-2">{{ __('payrolls.deduct') }}</th>
                            <th class="px-2 py-2">{{ __('payrolls.net') }}</th>
                        </tr>
                    </thead>

                    <tbody>
                        @foreach($employees as $row)
                            @php
                                $defaultAdvance = money(old('advance_deductions.' . $row->employee->id, $row->max_deduction));
                                $defaultAdvance = min($defaultAdvance, money($row->max_deduction));
                                $netSalaryPreview = money(max(0, money($row->pre_net_salary) - $defaultAdvance));
                                $isMonthly = $row->employee->employee_type === 'monthly';
                            @endphp

                            <tr class="border-t">
                                <td class="px-2 py-2">
                                    <b>{{ $row->employee->name }}</b><br>
                                    <span class="text-[10px] text-slate-500">
                                        {{ $row->employee->employee_code }}
                                    </span>
                                </td>

                                <td class="px-2 py-2 text-center">
                                    {{ $isMonthly ? __('payrolls.monthly_short') : __('payrolls.roz_type_short') }}
                                </td>

                                <td class="px-2 py-2">{{ $row->total_present_days }}</td>
                                <td class="px-2 py-2 text-rose-600">{{ $row->total_absent_days }}</td>
                                <td class="px-2 py-2">{{ $row->total_leave_days }}</td>
                                <td class="px-2 py-2">{{ $row->total_holiday_days }}</td>
                                <td class="px-2 py-2">{{ $isMonthly ? $row->total_overtime_hours : '-' }}</td>
                                <td class="px-2 py-2">{{ !$isMonthly ? $row->total_roz : '-' }}</td>

                                <td class="px-2 py-2">{{ money_format_bd($row->basic_amount) }}</td>
                                <td class="px-2 py-2 text-rose-600">{{ money_format_bd($row->deduction_amount) }}</td>
                                <td class="px-2 py-2 text-emerald-600">{{ money_format_bd($row->overtime_amount) }}</td>
                                <td class="px-2 py-2 text-indigo-600">{{ money_format_bd($row->gross_salary) }}</td>
                                <td class="px-2 py-2 text-amber-600">{{ money_format_bd($row->outstanding_advance) }}</td>

                                <td class="px-2 py-2">
                                    <input type="number"
                                           name="advance_deductions[{{ $row->employee->id }}]"
                                           value="{{ $defaultAdvance }}"
                                           class="w-20 border px-1 py-1 text-xs">
                                </td>

                                <td class="px-2 py-2 font-bold">
                                    {{ money_format_bd($netSalaryPreview) }}
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>

            <div id="payrollFinalizedMessageBottom" class="hidden text-right">
                <span class="inline-block border border-rose-200 bg-rose-50 px-3 py-1 text-xs text-rose-700">
                    {{ __('PayrollController.payroll_already_finalized') }}
                </span>
            </div>

            {{-- Submit --}}
            <div class="flex justify-end">
                <button type="submit"
                        id="generatePayrollBtnBottom"
                        class="bg-slate-900 px-4 py-2 text-xs text-white disabled:opacity-50 disabled:cursor-not-allowed">
                    {{ __('payrolls.generate_payroll') }}
                </button>
            </div>
        </form>
    @endif
</div>

@if(!$employees->isEmpty())
<script>
document.addEventListener('DOMContentLoaded', function () {

    const form = document.getElementById('generatePayrollForm');
    const topBtn = document.getElementById('generateBtnTop');
    const bottomBtn = document.getElementById('generatePayrollBtnBottom');
    const topMsg = document.getElementById('payrollFinalizedMessageTop');
    const bottomMsg = document.getElementById('payrollFinalizedMessageBottom');

    const month = document.getElementById('payroll_month_hidden')?.value;
    const year = document.getElementById('payroll_year_hidden')?.value;

    function setFinalizedState(isFinalized) {
        if (topBtn) topBtn.disabled = isFinalized;
        if (bottomBtn) bottomBtn.disabled = isFinalized;

        if (topMsg) topMsg.classList.toggle('hidden', !isFinalized);
        if (bottomMsg) bottomMsg.classList.toggle('hidden', !isFinalized);
    }

    async function checkFinalized() {
        try {
            const res = await fetch("{{ route('user.hr.payrolls.check-finalized') }}", {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    'X-Requested-With': 'XMLHttpRequest',
                },
                body: JSON.stringify({
                    payroll_month: month,
                    payroll_year: year,
                }),
            });

            if (!res.ok) {
                setFinalizedState(false);
                return;
            }

            const data = await res.json();

            if (data.already_finalized) {
                setFinalizedState(true);
            } else {
                setFinalizedState(false);
            }

        } catch (e) {
            setFinalizedState(false);
        }
    }

    // 🔥 Initial check
    checkFinalized();

    // 🔥 Prevent submit if finalized
    form?.addEventListener('submit', async function (e) {

        const res = await fetch("{{ route('user.hr.payrolls.check-finalized') }}", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'X-Requested-With': 'XMLHttpRequest',
            },
            body: JSON.stringify({
                payroll_month: month,
                payroll_year: year,
            }),
        });

        if (!res.ok) return;

        const data = await res.json();

        if (data.already_finalized) {
            e.preventDefault();
            setFinalizedState(true);
            return false;
        }
    });

});
</script>
@endif
@endsection