@extends('layouts.admin')

@section('page-title', 'Client-wise Conveyance – ' . ($currentMonthLabel ?? ''))
@section('page-subtitle', 'Submitted conveyance grouped by client with filters and export')

@section('content')

{{-- FILTER CARD --}}
<div class="mb-6 bg-[color:var(--surface)] border border-[color:var(--border)] rounded-3xl shadow-sm p-4 md:p-5">
    <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-3 mb-4">
        <div>
            <h2 class="text-lg md:text-xl font-semibold">
                Filters – Client-wise Conveyance
            </h2>
            <p class="text-xs md:text-sm text-[color:var(--muted)] mt-1">
                Filter submitted conveyance by month, date range, session, and client. Export follows the same filters.
            </p>
        </div>

        <div class="flex gap-2">
            <a href="{{ route('admin.conveyance.clients.export', request()->query()) }}"
               class="inline-flex items-center gap-2 px-3 py-2 rounded-xl bg-emerald-600 text-white text-xs md:text-sm font-semibold hover:bg-emerald-700 transition shadow-sm">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M4 4v16h16V4H4zm4 5h8M8 12h5m-5 3h3"/>
                </svg>
                Export Summary (Excel)
            </a>
        </div>
    </div>

    <form method="GET" action="{{ route('admin.conveyance.clients') }}"
          class="space-y-3 md:space-y-0 md:grid md:grid-cols-10 md:gap-3">

        {{-- Month --}}
        <div class="md:col-span-2">
            <label class="block text-xs font-medium text-[color:var(--muted)] mb-1">
                Month (Exact)
            </label>
            <input type="month"
                   name="month"
                   value="{{ $month ?? '' }}"
                   class="w-full border border-[color:var(--border)] rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[color:var(--brand)] bg-white">
        </div>

        {{-- From Date --}}
        <div class="md:col-span-2">
            <label class="block text-xs font-medium text-[color:var(--muted)] mb-1">
                From date
            </label>
            <input type="date"
                   name="from_date"
                   value="{{ $fromDate ?? '' }}"
                   class="w-full border border-[color:var(--border)] rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[color:var(--brand)] bg-white">
        </div>

        {{-- To Date --}}
        <div class="md:col-span-2">
            <label class="block text-xs font-medium text-[color:var(--muted)] mb-1">
                To date
            </label>
            <input type="date"
                   name="to_date"
                   value="{{ $toDate ?? '' }}"
                   class="w-full border border-[color:var(--border)] rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[color:var(--brand)] bg-white">
        </div>

        {{-- Session --}}
        <div class="md:col-span-2">
            <label class="block text-xs font-medium text-[color:var(--muted)] mb-1">
                Session
            </label>
            <select name="session_id"
                    class="w-full border border-[color:var(--border)] rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[color:var(--brand)] bg-white">
                <option value="">All sessions</option>
                @foreach($sessions as $session)
                    <option value="{{ $session->id }}" {{ (int)($sessionId ?? 0) === $session->id ? 'selected' : '' }}>
                        {{ $session->name }}
                    </option>
                @endforeach
            </select>
        </div>

        {{-- Client --}}
        <div class="md:col-span-2">
            <label class="block text-xs font-medium text-[color:var(--muted)] mb-1">
                Client
            </label>
            <select name="client_id"
                    class="w-full border border-[color:var(--border)] rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[color:var(--brand)] bg-white">
                <option value="">All clients</option>
                @foreach($clients as $client)
                    <option value="{{ $client->id }}" {{ (int)($clientId ?? 0) === $client->id ? 'selected' : '' }}>
                        {{ $client->name }}
                    </option>
                @endforeach
            </select>
        </div>

        <div class="md:col-span-10 flex flex-wrap justify-end gap-2 pt-2">
            <a href="{{ route('admin.conveyance.clients') }}"
               class="px-3 py-2 rounded-xl border border-[color:var(--border)] text-xs md:text-sm text-[color:var(--muted)] hover:bg-slate-50">
                Clear all filters
            </a>
            <button type="submit"
                    class="px-4 py-2 rounded-xl bg-[color:var(--brand)] text-white text-xs md:text-sm font-semibold hover:bg-[color:var(--brand-dark)] shadow-sm">
                Apply Filters
            </button>
        </div>
    </form>
</div>

{{-- HEADER INFO --}}
@php
    $groups = $rows->groupBy('client_id');
@endphp

<div class="mb-4 space-y-1">
    <h2 class="text-2xl font-extrabold tracking-tight mb-1">
        Client-wise Conveyance – {{ $currentMonthLabel ?? '' }}
    </h2>
    <p class="text-sm text-[color:var(--muted)]">
        Showing <span class="font-semibold">submitted</span> entries between
        <span class="font-semibold">
            {{ $monthStart ? $monthStart->format('d M Y') : '—' }}
        </span>
        and
        <span class="font-semibold">
            {{ $monthEnd ? $monthEnd->format('d M Y') : '—' }}
        </span>.
    </p>
    <p class="text-xs md:text-sm text-[color:var(--muted)]">
        Clients: <span class="font-semibold">{{ $groups->count() }}</span>
        &nbsp;•&nbsp;
        Grand Total:
        <span class="font-semibold text-emerald-700">
            ₹ {{ number_format($grandTotal ?? 0, 2) }}
        </span>
    </p>
</div>

@if($rows->isEmpty())
    <div class="rounded-3xl bg-[color:var(--surface)] border border-[color:var(--border)] shadow-sm p-6 text-sm text-[color:var(--muted)]">
        No submitted conveyance entries found for selected filters.
    </div>
@else
    <div class="rounded-3xl bg-[color:var(--surface)] border border-[color:var(--border)] shadow-sm p-4">
        <div class="overflow-x-auto rounded-2xl border border-[color:var(--border)] bg-white">
            <table class="w-full text-sm">
                <thead class="bg-slate-50 text-[11px] uppercase tracking-wide text-[color:var(--muted)]">
                    <tr>
                        <th class="p-3 text-left font-semibold">Client</th>
                        <th class="p-3 text-right font-semibold">Total Amount (₹)</th>
                        <th class="p-3 text-center font-semibold">Entries</th>
                        <th class="p-3 text-center font-semibold">Employees</th>
                        <th class="p-3 text-center font-semibold">Verification</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-[color:var(--border)]">
                    @foreach($groups as $clientId => $items)
                        @php
                            $client         = optional($items->first()->client);
                            $clientName     = $client->name ?? 'No Client Selected';

                            // Effective total per client (onward + return/custom)
                            $totalAmount    = $items->sum(function($c) {
                                $onward = (float) $c->amount;
                                if ($c->is_return) {
                                    $return = $c->return_amount !== null
                                        ? (float) $c->return_amount
                                        : $onward;
                                    return $onward + $return;
                                }
                                return $onward;
                            });

                            $entryCount     = $items->count();
                            $employeeGroups = $items->groupBy('user_id');
                            $employeeCount  = $employeeGroups->count();
                        @endphp
                        <tr class="align-top hover:bg-slate-50 transition">
                            <td class="p-3">
                                <div class="font-semibold text-[color:var(--text)]">
                                    {{ $clientName }}
                                </div>
                                <div class="text-[11px] text-[color:var(--muted)]">
                                    Client ID: {{ $clientId ?? 'N/A' }}
                                </div>
                            </td>

                            <td class="p-3 text-right font-extrabold text-emerald-700 whitespace-nowrap">
                                ₹ {{ number_format($totalAmount, 2) }}
                            </td>
                            <td class="p-3 text-center">
                                {{ $entryCount }}
                            </td>
                            <td class="p-3 text-center">
                                {{ $employeeCount }}
                            </td>
                            <td class="p-3 text-center">
                                @if($clientId)
                                    <a href="{{ route('admin.conveyance.clientEmployees', array_merge(['client' => $clientId], request()->query())) }}"
                                       class="inline-flex items-center gap-1 px-3 py-1.5 rounded-xl
                                              bg-[color:var(--bg-2)] border border-[color:var(--border)]
                                              text-[11px] font-semibold text-[color:var(--text)]
                                              hover:bg-slate-100 transition">
                                        🔎
                                        <span>Open Verification View</span>
                                    </a>
                                @else
                                    <span class="text-[11px] text-[color:var(--muted)]">
                                        No client linked
                                    </span>
                                @endif
                            </td>
                        </tr>
                    @endforeach
                </tbody>
                <tfoot class="bg-slate-50 border-t border-[color:var(--border)]">
                    <tr>
                        <td class="p-3 text-right font-bold">
                            Grand Total
                        </td>
                        <td class="p-3 text-right font-extrabold text-emerald-800 whitespace-nowrap">
                            ₹ {{ number_format($grandTotal ?? 0, 2) }}
                        </td>
                        <td class="p-3 text-center text-[11px] text-[color:var(--muted)]" colspan="3">
                            (All clients in this view)
                        </td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
@endif

@endsection
