@extends('layouts.admin')

@section('title', 'Staff Management')

@section('content')
@php
    $staffCount = $users->total();
    $assignedCount = collect($staffWithStats)->filter(fn ($row) => $row['user']->stores->isNotEmpty())->count();
@endphp

<div class="tw-migrated staff-page space-y-4">
    <x-ui.page-header
        title="Staff Management"
        subtitle="Store access, roles, and sales performance"
    >
        <x-slot:actions>
            @can('staff.create')
                <a href="{{ route('admin.users.create') }}" class="tw-btn-primary">
                    <i class="bi bi-person-plus"></i> Add Staff
                </a>
            @endcan
        </x-slot:actions>
    </x-ui.page-header>

    @if(session('success'))
        <x-ui.alert type="success">{{ session('success') }}</x-ui.alert>
    @endif

    <div class="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
        <x-ui.stat-card
            compact
            tone="primary"
            label="Today Sales"
            :value="'₹'.number_format($todaySales, 0)"
            hint="All staff combined"
            icon="bi bi-calendar-day"
        />
        <x-ui.stat-card
            compact
            tone="info"
            label="This Week"
            :value="'₹'.number_format($thisWeekSales, 0)"
            hint="Paid orders with staff"
            icon="bi bi-calendar-week"
        />
        <x-ui.stat-card
            compact
            tone="success"
            label="This Month"
            :value="'₹'.number_format($thisMonthSales, 0)"
            hint="Avg ₹{{ number_format($avgOrderValue, 0) }} / order"
            icon="bi bi-calendar-month"
        />
        <x-ui.stat-card
            compact
            tone="warning"
            label="Month Orders"
            :value="number_format($thisMonthOrders)"
            hint="{{ $staffCount }} staff on this list"
            icon="bi bi-cart-check"
        />
    </div>

    <x-ui.card>
        <form method="get" action="{{ route('admin.users.staff') }}" class="row g-2 align-items-end justify-content-end mb-3">
            <div class="col-md-3 col-lg-3">
                <label for="staffSearch" class="admin-form-label">Search</label>
                <div class="products-search-wrap">
                    <i class="bi bi-search"></i>
                    <input
                        type="search"
                        name="q"
                        id="staffSearch"
                        class="form-control admin-form-control"
                        value="{{ request('q') }}"
                        placeholder="Name, mobile, email, staff number"
                    >
                </div>
            </div>
            @if(($storeLocations ?? collect())->count())
            <div class="col-md-3 col-lg-3">
                <label for="staffLocationFilter" class="admin-form-label">Store / Warehouse</label>
                <select name="location_id" id="staffLocationFilter" class="form-select admin-form-control">
                    <option value="">All locations</option>
                    @foreach($storeLocations as $loc)
                        <option value="{{ $loc->id }}" @selected(($locationFilter ?? '') == $loc->id)>
                            {{ $loc->name }} ({{ $loc->type }})
                        </option>
                    @endforeach
                </select>
            </div>
            @endif
            <div class="col-auto">
                <label class="admin-form-label">&nbsp;</label>
                <div class="d-flex gap-2">
                    <button type="submit" class="tw-btn-primary">
                        <i class="bi bi-funnel"></i> Filter
                    </button>
                    @if(request()->hasAny(['q', 'location_id']))
                        <a href="{{ route('admin.users.staff') }}" class="tw-btn-outline">Reset</a>
                    @endif
                </div>
            </div>
        </form>

        <div class="tw-table-wrap">
            <table class="tw-table align-middle staff-table">
                <thead>
                    <tr>
                        <th>Staff</th>
                        <th>Contact</th>
                        <th>Roles</th>
                        <th>Access</th>
                        <th class="text-end">Sales</th>
                        <th class="text-end">Orders</th>
                        <th>Last sale</th>
                        <th>Status</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($staffWithStats as $staffData)
                        @php
                            $user = $staffData['user'];
                            $initial = strtoupper(substr((string) $user->name, 0, 1)) ?: 'S';
                            $stores = $user->stores;
                            $storeCount = $stores->count();
                            $hasWarehouse = $stores->contains(fn ($s) => $s->type === 'warehouse');
                            $hasStore = $stores->contains(fn ($s) => $s->type === 'store');
                        @endphp
                        <tr>
                            <td>
                                <div class="d-flex align-items-center gap-2">
                                    <div class="staff-avatar">{{ $initial }}</div>
                                    <div class="min-w-0">
                                        <div class="fw-semibold text-truncate">{{ $user->name }}</div>
                                        <div class="small text-muted">
                                            #{{ $user->id }}
                                            @if($user->staff_number)
                                                · <span class="font-monospace">{{ $user->staff_number }}</span>
                                            @endif
                                        </div>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <div class="small">{{ $user->mobile }}</div>
                                <div class="small text-muted text-truncate" style="max-width: 160px;">{{ $user->email ?: '—' }}</div>
                            </td>
                            <td>
                                <div class="d-flex flex-wrap gap-1">
                                    @forelse($user->roles as $role)
                                        <x-ui.badge :variant="$role->name === 'admin' ? 'danger' : ($role->name === 'staff' ? 'warning' : 'primary')">
                                            {{ ucwords(str_replace('_', ' ', $role->name)) }}
                                        </x-ui.badge>
                                    @empty
                                        <span class="text-muted small">—</span>
                                    @endforelse
                                </div>
                            </td>
                            <td style="min-width: 200px; max-width: 280px;">
                                @if($storeCount)
                                    <div class="d-flex flex-wrap gap-1 mb-1">
                                        @foreach($stores->take(4) as $store)
                                            <span class="staff-loc-chip {{ $store->type === 'warehouse' ? 'is-wh' : 'is-store' }}">
                                                {{ $store->type === 'warehouse' ? 'WH' : 'ST' }}
                                                {{ \Illuminate\Support\Str::limit($store->name, 18) }}
                                                @if((int) $user->default_location_id === (int) $store->id)
                                                    <i class="bi bi-star-fill" title="Default"></i>
                                                @endif
                                            </span>
                                        @endforeach
                                        @if($storeCount > 4)
                                            <span class="staff-loc-chip">+{{ $storeCount - 4 }}</span>
                                        @endif
                                    </div>
                                    <div class="small text-muted">
                                        @if($storeCount === 1)
                                            Single location
                                        @elseif($hasWarehouse && $hasStore)
                                            Warehouse + {{ $stores->where('type', 'store')->count() }} store(s)
                                        @elseif($hasWarehouse)
                                            Warehouse access
                                        @else
                                            {{ $storeCount }} stores
                                        @endif
                                        @if($user->defaultLocation)
                                            · Default: {{ $user->defaultLocation->name }}
                                        @endif
                                    </div>
                                @else
                                    <x-ui.badge variant="danger">No locations</x-ui.badge>
                                @endif
                            </td>
                            <td class="text-end">
                                <span class="fw-semibold text-success">₹{{ number_format($staffData['total_sales'], 0) }}</span>
                            </td>
                            <td class="text-end">
                                <x-ui.badge variant="primary">{{ $staffData['total_orders'] }}</x-ui.badge>
                                <div class="small text-muted">Avg ₹{{ number_format($staffData['avg_order_value'], 0) }}</div>
                            </td>
                            <td class="small text-nowrap">
                                @if($staffData['last_order_date'])
                                    {{ \Carbon\Carbon::parse($staffData['last_order_date'])->format('M d, Y') }}
                                @else
                                    <span class="text-muted">No sales</span>
                                @endif
                            </td>
                            <td>
                                @if($user->banned_at)
                                    <x-ui.badge variant="danger">
                                        <span class="d-inline-flex align-items-center gap-1">
                                            <x-ui.status-dot color="danger" /> Banned
                                        </span>
                                    </x-ui.badge>
                                @else
                                    <x-ui.badge variant="success">
                                        <span class="d-inline-flex align-items-center gap-1">
                                            <x-ui.status-dot color="success" /> Active
                                        </span>
                                    </x-ui.badge>
                                @endif
                            </td>
                            <td class="text-end">
                                @can('staff.update')
                                    <a href="{{ route('admin.users.edit', $user->id) }}" class="tw-btn-outline tw-btn-sm">
                                        <i class="bi bi-person-gear"></i> Manage
                                    </a>
                                @endcan
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="9">
                                <x-ui.empty-state
                                    title="No staff members found"
                                    description="Try clearing filters or add a new staff member with store/warehouse access."
                                />
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 pt-3 mt-3 border-top">
            <div class="small text-muted">
                Showing <strong>{{ $users->firstItem() ?? 0 }}</strong>–<strong>{{ $users->lastItem() ?? 0 }}</strong>
                of <strong>{{ $users->total() }}</strong> staff
                @if($assignedCount)
                    · {{ $assignedCount }} with locations on this page
                @endif
            </div>
            @if($users->hasPages())
                <div>{{ $users->links('vendor.pagination.admin-categories') }}</div>
            @endif
        </div>
    </x-ui.card>
</div>

<style>
.staff-page .staff-avatar {
    width: 2.35rem;
    height: 2.35rem;
    border-radius: 999px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-weight: 700;
    font-size: 0.85rem;
    color: #fff;
    background: linear-gradient(135deg, var(--admin-primary, #0f766e), #14b8a6);
    flex-shrink: 0;
}
.staff-page .staff-loc-chip {
    display: inline-flex;
    align-items: center;
    gap: 0.25rem;
    padding: 0.2rem 0.5rem;
    border-radius: 999px;
    font-size: 0.72rem;
    font-weight: 600;
    border: 1px solid var(--color-border, #e4e0d8);
    background: #fff;
    color: var(--color-text, #161b26);
}
.staff-page .staff-loc-chip.is-wh {
    background: color-mix(in srgb, var(--admin-primary, #0f766e) 10%, #fff);
    border-color: color-mix(in srgb, var(--admin-primary, #0f766e) 28%, #e4e0d8);
    color: var(--admin-primary-dark, #0d5f59);
}
.staff-page .staff-loc-chip.is-store {
    background: #f8fafc;
}
.staff-page .staff-loc-chip .bi-star-fill {
    color: #d97706;
    font-size: 0.65rem;
}
.staff-page .staff-table td {
    vertical-align: middle;
}
</style>
@endsection
