@extends('layouts.app')

@section('title', 'Payroll Management')

@section('content')
<div class="space-y-6" x-data="{ loanEmployee: null }">
    <header class="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between"><div><p class="text-xs font-bold uppercase tracking-[.18em] text-emerald-600">Employees & HR</p><h1 class="mt-1 text-3xl font-bold text-slate-950">Payroll management</h1><p class="mt-1 text-sm text-slate-500">Attendance, leave, overtime, salary structures, loans, approval locks, WPS batches and accounting in one auditable flow.</p></div><div class="flex gap-2"><a href="{{ route('app.gratuity.index') }}" class="rounded-xl border border-slate-200 bg-white px-4 py-2.5 text-sm font-bold text-slate-700">Gratuity</a><a href="{{ route('app.attendance.index',['view'=>'monthly']) }}" class="rounded-xl bg-emerald-600 px-4 py-2.5 text-sm font-bold text-white">Attendance</a></div></header>

    <section class="grid gap-3 sm:grid-cols-2 xl:grid-cols-4"><div class="rounded-2xl border border-slate-200 bg-white p-5"><p class="text-xs font-semibold text-slate-500">Runs under review</p><p class="mt-2 text-3xl font-bold text-amber-600">{{ $stats['draft'] }}</p></div><div class="rounded-2xl border border-slate-200 bg-white p-5"><p class="text-xs font-semibold text-slate-500">Approved awaiting payment</p><p class="mt-2 text-3xl font-bold text-emerald-600">{{ $stats['approved'] }}</p></div><div class="rounded-2xl border border-slate-200 bg-white p-5"><p class="text-xs font-semibold text-slate-500">Latest approved net</p><p class="mt-2 text-2xl font-bold text-slate-950">AED {{ number_format((float)$stats['last_net'],2) }}</p></div><div class="rounded-2xl border border-slate-200 bg-white p-5"><p class="text-xs font-semibold text-slate-500">Active loan balance</p><p class="mt-2 text-2xl font-bold text-slate-950">AED {{ number_format((float)$stats['active_loans'],2) }}</p></div></section>

    @if(auth()->check() && auth()->user()->hasPermission('payroll.process'))
    <section class="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm"><h2 class="text-lg font-bold text-slate-950">Start payroll run</h2><p class="mt-1 text-xs text-slate-500">Missing salary structures block calculation. Bank, attendance, corrections and pending leave appear as validation warnings.</p><form method="POST" action="{{ route('app.payroll.store') }}" class="mt-4 grid gap-3 md:grid-cols-5">@csrf<label class="text-xs font-semibold text-slate-700">Period start<input type="date" name="period_start" value="{{ now()->startOfMonth()->format('Y-m-d') }}" required class="erp-input mt-1"></label><label class="text-xs font-semibold text-slate-700">Period end<input type="date" name="period_end" value="{{ now()->endOfMonth()->format('Y-m-d') }}" required class="erp-input mt-1"></label><label class="text-xs font-semibold text-slate-700">Branch<select name="branch_id" class="erp-input mt-1"><option value="">All permitted branches</option>@foreach($branches as $branch)<option value="{{ $branch->id }}">{{ $branch->name }}</option>@endforeach</select></label><label class="text-xs font-semibold text-slate-700">Payroll group<select name="payroll_group_id" class="erp-input mt-1"><option value="">All groups</option>@foreach($groups as $group)<option value="{{ $group->id }}">{{ $group->name }}</option>@endforeach</select></label><button class="self-end rounded-xl bg-emerald-600 px-4 py-3 text-sm font-bold text-white">Calculate payroll</button></form></section>
    @endif

    <section class="overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm"><div class="border-b border-slate-200 p-5"><h2 class="text-lg font-bold text-slate-950">Payroll runs</h2></div><div class="overflow-x-auto"><table class="erp-table"><thead><tr><th>Run</th><th>Period</th><th>Scope</th><th>Gross</th><th>Deductions</th><th>Net</th><th>Warnings</th><th>Status</th></tr></thead><tbody>@forelse($runs as $run)<tr class="cursor-pointer" onclick="window.location='{{ route('app.payroll.show',$run) }}'"><td><strong>{{ $run->run_number }}</strong><small>{{ $run->created_at->format('d M Y H:i') }}</small></td><td>{{ $run->period->period_name }}<small>{{ $run->period->period_start->format('d M') }}–{{ $run->period->period_end->format('d M Y') }}</small></td><td>{{ $run->branch?->name ?? 'All branches' }}<small>{{ $run->group?->name ?? 'All payroll groups' }}</small></td><td>AED {{ number_format((float)$run->gross_total,2) }}</td><td class="text-rose-700">AED {{ number_format((float)$run->deduction_total,2) }}</td><td class="font-bold text-emerald-700">AED {{ number_format((float)$run->net_total,2) }}</td><td>{{ count($run->validation_warnings ?? []) }}</td><td><span class="rounded-full bg-slate-100 px-2.5 py-1 text-[10px] font-bold uppercase">{{ str_replace('_',' ',$run->status) }}</span></td></tr>@empty<tr><td colspan="8" class="py-14 text-center"><strong>No payroll runs</strong><small>Calculate the first period once salaries and attendance are ready.</small></td></tr>@endforelse</tbody></table></div><div class="border-t border-slate-200 p-4">{{ $runs->links() }}</div></section>

    @if(auth()->check() && auth()->user()->hasPermission('payroll.salary.view'))
    <section class="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm"><div class="flex items-center justify-between"><div><h2 class="text-lg font-bold text-slate-950">Salary readiness</h2><p class="text-xs text-slate-500">Salary values remain hidden from users without salary permission.</p></div><span class="rounded-full bg-slate-100 px-3 py-1 text-xs font-bold">{{ $employees->count() }} active employees</span></div><div class="mt-4 grid gap-3 lg:grid-cols-2">@foreach($employees as $employee)<article class="rounded-xl border border-slate-200 p-4"><div class="flex items-start justify-between"><div><a href="{{ route('app.employees.show',$employee) }}" class="font-bold text-slate-900 hover:text-emerald-700">{{ $employee->full_name }}</a><p class="text-xs text-slate-500">{{ $employee->employee_code }} · {{ $employee->designation }}</p></div>@if($employee->currentSalary)<div class="text-right"><p class="font-bold text-emerald-700">AED {{ number_format((float)$employee->currentSalary->basic_salary,2) }}</p><p class="text-[10px] text-slate-400">Basic · effective {{ $employee->currentSalary->effective_from->format('d M Y') }}</p></div>@else<span class="rounded-full bg-rose-50 px-2 py-1 text-[10px] font-bold text-rose-700">Salary missing</span>@endif</div><div class="mt-3 flex gap-2"><a href="{{ route('app.employees.show',$employee) }}#salary" class="text-xs font-bold text-emerald-700">Salary & bank details</a>@if(auth()->check() && auth()->user()->hasPermission('payroll.process'))<button type="button" @click="loanEmployee = loanEmployee === {{ $employee->id }} ? null : {{ $employee->id }}" class="text-xs font-bold text-slate-600">Loan / advance</button>@endif</div>@if(auth()->check() && auth()->user()->hasPermission('payroll.process'))<form x-show="loanEmployee === {{ $employee->id }}" x-cloak method="POST" action="{{ route('app.employees.loans.store',$employee) }}" class="mt-3 grid gap-2 sm:grid-cols-3">@csrf<select name="type" class="erp-input"><option value="loan">Employee loan</option><option value="salary_advance">Salary advance</option></select><input type="number" step=".01" min=".01" name="amount" required class="erp-input" placeholder="Amount"><input type="number" step=".01" min=".01" name="installment_amount" required class="erp-input" placeholder="Installment"><input type="date" name="loan_date" value="{{ today()->format('Y-m-d') }}" required class="erp-input"><input type="date" name="start_month" value="{{ now()->addMonth()->startOfMonth()->format('Y-m-d') }}" required class="erp-input"><button class="rounded-xl bg-slate-900 text-xs font-bold text-white">Submit</button></form>@endif</article>@endforeach</div></section>
    @endif

    @if($loans->isNotEmpty())<section class="rounded-2xl border border-slate-200 bg-white p-5"><h2 class="text-lg font-bold text-slate-950">Loans and salary advances</h2><div class="mt-4 overflow-x-auto"><table class="erp-table"><thead><tr><th>Loan</th><th>Employee</th><th>Amount</th><th>Installment</th><th>Remaining</th><th>Status</th><th>Action</th></tr></thead><tbody>@foreach($loans as $loan)<tr><td><strong>{{ $loan->loan_number }}</strong><small>{{ ucfirst(str_replace('_',' ',$loan->type)) }}</small></td><td>{{ $loan->employee->full_name }}</td><td>AED {{ number_format((float)$loan->amount,2) }}</td><td>AED {{ number_format((float)$loan->installment_amount,2) }}</td><td>AED {{ number_format((float)$loan->remaining_amount,2) }}</td><td>{{ ucfirst($loan->status) }}</td><td>@if($loan->status==='requested') @if(auth()->check() && auth()->user()->hasPermission('payroll.approve'))<form method="POST" action="{{ route('app.loans.approve',$loan) }}">@csrf<button class="text-xs font-bold text-emerald-700">Approve</button></form>@endif @else<span class="text-xs text-slate-400">Payroll deduction active</span>@endif</td></tr>@endforeach</tbody></table></div></section>@endif
</div>
@endsection
