@extends('layouts.app')

@section('title', 'Review tax declaration')
@section('heading', 'Review tax declaration')

@section('content')
@php
    $statusColors = [
        'draft' => 'bg-slate-100 text-slate-700',
        'submitted' => 'bg-amber-100 text-amber-800',
        'verified' => 'bg-emerald-100 text-emerald-800',
        'rejected' => 'bg-red-100 text-red-800',
    ];
    $canFinalVerify = $canFinalVerify ?? $declaration->allProofsApproved();
    $unapprovedCount = $declaration->unapprovedProofItems()->count();
@endphp

<div class="mx-auto max-w-5xl space-y-6">
    <div class="flex flex-wrap items-start justify-between gap-4">
        <div>
            <a href="{{ route('payroll.index', ['tab' => 'declaration', 'fy' => $declaration->financial_year]) }}" class="text-sm text-primary hover:underline">&larr; Back to declarations</a>
            <h1 class="mt-2 text-xl font-semibold text-slate-900">{{ $declaration->user?->name ?? 'Employee' }}</h1>
            <p class="mt-1 text-sm text-slate-600">FY {{ $declaration->financial_year }} · {{ strtoupper($declaration->regime) }} regime</p>
        </div>
        <span class="inline-flex rounded-full px-3 py-1 text-xs font-semibold uppercase {{ $statusColors[$declaration->status] ?? 'bg-slate-100' }}">
            {{ ucfirst($declaration->status) }}
        </span>
    </div>

    @if(session('success'))
        <div class="rounded-lg border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-800">{{ session('success') }}</div>
    @endif
    @if(session('error'))
        <div class="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800">{{ session('error') }}</div>
    @endif

    <div class="grid gap-4 sm:grid-cols-4">
        <x-card><p class="text-xs text-slate-500">Annual gross</p><p class="mt-1 text-lg font-semibold">₹{{ number_format((float) $declaration->gross_annual_estimate, 0) }}</p></x-card>
        <x-card><p class="text-xs text-slate-500">Deductions declared</p><p class="mt-1 text-lg font-semibold">₹{{ number_format((float) $declaration->total_deductions_declared, 0) }}</p></x-card>
        <x-card><p class="text-xs text-slate-500">Annual tax</p><p class="mt-1 text-lg font-semibold">₹{{ number_format((float) $projection['annual_tax'], 0) }}</p></x-card>
        <x-card><p class="text-xs text-slate-500">Monthly TDS</p><p class="mt-1 text-lg font-semibold text-primary">₹{{ number_format((float) $projection['monthly_tds'], 0) }}</p></x-card>
    </div>

    <x-card>
        <form action="{{ route('payroll.income-tax.admin.verify', $declaration) }}" method="post" class="space-y-5"
              x-data="{
                  canVerify: @js($canFinalVerify),
                  checkStatuses() {
                      const selects = this.$el.querySelectorAll('select[name*=\'[proof_status]\']');
                      if (selects.length === 0) { this.canVerify = true; return; }
                      this.canVerify = Array.from(selects).every(s => s.value === 'approved');
                  }
              }"
              x-init="checkStatuses()">
            @csrf

            @if($declaration->items->isNotEmpty())
                <div class="flex flex-wrap items-center justify-between gap-2">
                    <div>
                        <h2 class="text-sm font-semibold text-slate-900">Deduction lines &amp; proofs</h2>
                        @if($unapprovedCount > 0 && in_array($declaration->status, ['submitted', 'rejected'], true))
                            <p class="mt-1 text-xs text-amber-700">{{ $unapprovedCount }} line(s) not approved — use Approve all or set each status to Approved.</p>
                        @endif
                    </div>
                    @if(in_array($declaration->status, ['submitted', 'rejected'], true))
                        <div class="flex gap-2">
                            <button type="submit" name="action" value="bulk_approve" class="rounded-lg bg-emerald-50 px-3 py-1.5 text-xs font-medium text-emerald-800 hover:bg-emerald-100">Approve all</button>
                            <button type="submit" name="action" value="bulk_reject" class="rounded-lg bg-red-50 px-3 py-1.5 text-xs font-medium text-red-800 hover:bg-red-100">Reject all</button>
                        </div>
                    @endif
                </div>

                <div class="overflow-x-auto">
                    <table class="min-w-full text-sm">
                        <thead>
                            <tr class="border-b border-slate-200 text-left text-xs uppercase text-slate-500">
                                <th class="pb-2 pr-4">Section</th>
                                <th class="pb-2 pr-4">Declared</th>
                                <th class="pb-2 pr-4">Verified</th>
                                <th class="pb-2 pr-4">Proof</th>
                                <th class="pb-2">Status</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100">
                            @foreach($declaration->items as $item)
                                <tr>
                                    <td class="py-3 pr-4">
                                        <div class="font-medium text-slate-900">{{ $item->section_code }}</div>
                                        <div class="text-xs text-slate-500">{{ $item->section_name }}</div>
                                    </td>
                                    <td class="py-3 pr-4">₹{{ number_format((float) $item->declared_amount, 2) }}</td>
                                    <td class="py-3 pr-4">
                                        <input type="number" name="items[{{ $item->id }}][verified_amount]" min="0" step="0.01"
                                            value="{{ $item->verified_amount ?? $item->declared_amount }}"
                                            class="w-28 rounded border border-slate-300 px-2 py-1 text-sm"
                                            {{ $declaration->status === 'verified' ? 'readonly' : '' }}>
                                    </td>
                                    <td class="py-3 pr-4">
                                        @if($item->proof_path)
                                            <a href="{{ route('payroll.income-tax.proof.download', $item) }}" class="btn-icon-action btn-icon-action--view" title="View" aria-label="View"><i class="bi bi-eye"></i></a>
                                        @else
                                            <span class="text-amber-600">Missing</span>
                                        @endif
                                    </td>
                                    <td class="py-3">
                                        <select name="items[{{ $item->id }}][proof_status]"
                                            @change="checkStatuses()"
                                            class="rounded border border-slate-300 px-2 py-1 text-sm {{ $item->proof_status === 'approved' ? 'border-emerald-300 bg-emerald-50' : ($item->proof_status === 'rejected' ? 'border-red-300 bg-red-50' : 'border-amber-300 bg-amber-50') }}"
                                            {{ $declaration->status === 'verified' ? 'disabled' : '' }}>
                                            @foreach(['pending', 'approved', 'rejected'] as $ps)
                                                <option value="{{ $ps }}" {{ $item->proof_status === $ps ? 'selected' : '' }}>{{ ucfirst($ps) }}</option>
                                            @endforeach
                                        </select>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            @else
                <p class="text-sm text-slate-600">New regime — no Chapter VI-A deduction lines.</p>
            @endif

            <div>
                <label class="block text-sm font-medium text-slate-700">HR remarks</label>
                <textarea name="hr_remarks" rows="3" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" {{ $declaration->status === 'verified' ? 'readonly' : '' }}>{{ $declaration->hr_remarks }}</textarea>
            </div>

            @if(in_array($declaration->status, ['submitted', 'rejected'], true))
                <div class="flex flex-wrap items-center gap-2 border-t border-slate-100 pt-4">
                    <button type="submit" name="action" value="verify"
                        :disabled="!canVerify"
                        :class="canVerify ? 'bg-emerald-600 hover:bg-emerald-700' : 'cursor-not-allowed bg-slate-300'"
                        class="rounded-lg px-4 py-2 text-sm font-medium text-white">
                        Final approve (Verify declaration)
                    </button>
                    <button type="submit" name="action" value="reject" class="rounded-lg bg-red-600 px-4 py-2 text-sm font-medium text-white hover:bg-red-700">Reject</button>
                    <p x-show="!canVerify" x-cloak class="text-xs text-amber-700">Set every deduction line status to <strong>Approved</strong> to enable final approval.</p>
                </div>
            @elseif($declaration->status === 'verified')
                <a href="{{ route('payroll.income-tax.admin.form16', $declaration) }}?download=1" class="inline-flex rounded-lg bg-primary px-4 py-2 text-sm font-medium text-white">Download Form 16</a>
            @endif
        </form>
    </x-card>
</div>
@endsection
