<x-app-layout>
    <x-slot name="header">
        <div class="flex flex-col gap-1">
            <h2 class="text-xl font-semibold text-slate-900 leading-tight">Dashboard</h2>
            <p class="text-sm text-slate-500">Smart overview with agent-wise filters, finance, and recruitment performance.</p>
        </div>
    </x-slot>

    @php
        $filters = [
            'agent_id' => request('agent_id'),
            'company_id' => request('company_id'),
            'destination_country' => request('destination_country'),
            'from_date' => request('from_date'),
            'to_date' => request('to_date'),
        ];

        $agents = \App\Models\Agent::orderBy('name')->get(['id', 'name']);
        $companies = \App\Models\Company::orderBy('name')->get(['id', 'name']);
        $destinations = \App\Models\Candidate::query()
            ->whereNotNull('destination_country')
            ->where('destination_country', '!=', '')
            ->distinct()
            ->orderBy('destination_country')
            ->pluck('destination_country');

        $applyCandidateFilters = function ($query) use ($filters) {
            return $query
                ->when($filters['agent_id'], fn ($q, $v) => $q->where('agent_id', $v))
                ->when($filters['company_id'], fn ($q, $v) => $q->where('company_id', $v))
                ->when($filters['destination_country'], fn ($q, $v) => $q->where('destination_country', $v))
                ->when($filters['from_date'], fn ($q, $v) => $q->whereDate('created_at', '>=', $v))
                ->when($filters['to_date'], fn ($q, $v) => $q->whereDate('created_at', '<=', $v));
        };

        $candidateBase = $applyCandidateFilters(\App\Models\Candidate::query());
        $caseBase = \App\Models\RecruitmentCase::query()->whereHas('candidate', fn ($q) => $applyCandidateFilters($q));
        $paymentBase = \App\Models\Payment::query()->whereHas('case.candidate', fn ($q) => $applyCandidateFilters($q));
        $expenseBase = \App\Models\Expense::query()->whereHas('recruitmentCase.candidate', fn ($q) => $applyCandidateFilters($q));

        $totalCandidates = (clone $candidateBase)->count();
        $todayCandidates = (clone $candidateBase)->whereDate('created_at', now()->toDateString())->count();
        $totalCases = (clone $caseBase)->count();
        $closedCases = (clone $caseBase)->where('is_closed', true)->count();
        $openCases = max($totalCases - $closedCases, 0);
        $totalPrice = (float) (clone $caseBase)->sum('total_price');
        $totalPaid = (float) (clone $paymentBase)->sum('amount');
        $totalDue = max($totalPrice - $totalPaid, 0);
        $totalExpense = (float) (clone $expenseBase)->sum('amount');
        $profitAfterExpense = $totalPaid - $totalExpense;
        $avgPackage = $totalCases > 0 ? $totalPrice / $totalCases : 0;
        $collectionRate = $totalPrice > 0 ? round(($totalPaid / $totalPrice) * 100, 1) : 0;
        $expenseRate = $totalPaid > 0 ? round(($totalExpense / $totalPaid) * 100, 1) : 0;
        $activeAgents = (clone $candidateBase)->whereNotNull('agent_id')->distinct('agent_id')->count('agent_id');

        $salaryPaid = 0.0;
        $salaryTotal = 0.0;
        if (\Illuminate\Support\Facades\Schema::hasTable('staff_salaries')) {
            $salaryTotal = (float) \Illuminate\Support\Facades\DB::table('staff_salaries')->sum('net_salary');
        }
        if (\Illuminate\Support\Facades\Schema::hasTable('staff_salary_payments')) {
            $salaryPaid = (float) \Illuminate\Support\Facades\DB::table('staff_salary_payments')->sum('amount');
        } elseif (\Illuminate\Support\Facades\Schema::hasTable('staff_salaries')) {
            $salaryPaid = (float) \Illuminate\Support\Facades\DB::table('staff_salaries')->sum('paid_amount');
        }
        $salaryDue = max($salaryTotal - $salaryPaid, 0);
        $profitAfterSalary = $profitAfterExpense - $salaryPaid;

        $topAgents = \App\Models\Candidate::query()
            ->select('agent_id', \Illuminate\Support\Facades\DB::raw('COUNT(*) as candidates_count'))
            ->whereNotNull('agent_id')
            ->when($filters['company_id'], fn ($q, $v) => $q->where('company_id', $v))
            ->when($filters['destination_country'], fn ($q, $v) => $q->where('destination_country', $v))
            ->when($filters['from_date'], fn ($q, $v) => $q->whereDate('created_at', '>=', $v))
            ->when($filters['to_date'], fn ($q, $v) => $q->whereDate('created_at', '<=', $v))
            ->with('agent:id,name')
            ->groupBy('agent_id')
            ->orderByDesc('candidates_count')
            ->limit(5)
            ->get();

        $recentCandidates = (clone $candidateBase)
            ->with(['agent:id,name', 'company:id,name'])
            ->latest()
            ->limit(5)
            ->get();
    @endphp

    <style>
        .dash-hero{background:linear-gradient(135deg,#0f172a 0%,#0ea5e9 52%,#22c55e 100%);border-radius:28px;color:white;box-shadow:0 24px 70px rgba(15,23,42,.24);overflow:hidden;position:relative}.dash-hero:before{content:"";position:absolute;inset:0;background:radial-gradient(circle at 20% 20%,rgba(255,255,255,.28),transparent 34%),radial-gradient(circle at 90% 10%,rgba(255,255,255,.2),transparent 26%)}.dash-hero>*{position:relative}.dash-card{border:1px solid rgba(148,163,184,.22);background:rgba(255,255,255,.92);border-radius:24px;box-shadow:0 18px 45px rgba(15,23,42,.09);transition:.18s ease}.dash-card:hover{transform:translateY(-2px);box-shadow:0 24px 55px rgba(15,23,42,.13)}.dash-stat-icon{width:46px;height:46px;border-radius:16px;display:flex;align-items:center;justify-content:center;background:linear-gradient(135deg,#e0f2fe,#dcfce7);color:#0f172a;font-weight:800}.dash-filter-input{width:100%;border-radius:16px;border:1px solid #dbe3ef;background:white;padding:10px 13px;font-size:14px;color:#1e293b;outline:none}.dash-filter-input:focus{border-color:#38bdf8;box-shadow:0 0 0 4px rgba(14,165,233,.12)}.dash-mini{background:linear-gradient(180deg,#fff,#f8fafc);border:1px solid #e2e8f0;border-radius:20px}.progress-line{height:9px;border-radius:999px;background:#e2e8f0;overflow:hidden}.progress-line span{display:block;height:100%;border-radius:999px;background:linear-gradient(90deg,#0ea5e9,#22c55e)}
    </style>

    <div class="max-w-7xl mx-auto sm:px-6 lg:px-8 px-4 space-y-6">
        <div class="dash-hero p-6 md:p-8">
            <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-6">
                <div>
                    <div class="inline-flex items-center gap-2 rounded-full bg-white/15 px-3 py-1 text-xs font-semibold ring-1 ring-white/20">Admin Analytics</div>
                    <h1 class="mt-3 text-3xl md:text-4xl font-extrabold tracking-tight">Recruitment Performance Dashboard</h1>
                    <p class="mt-2 max-w-2xl text-sm md:text-base text-white/80">Filter by agent, company, destination country, or date range to view exact business performance.</p>
                </div>
                <div class="grid grid-cols-2 gap-3 min-w-[280px]">
                    <div class="rounded-2xl bg-white/15 p-4 ring-1 ring-white/20"><div class="text-xs text-white/70">Collection Rate</div><div class="text-2xl font-bold">{{ $collectionRate }}%</div></div>
                    <div class="rounded-2xl bg-white/15 p-4 ring-1 ring-white/20"><div class="text-xs text-white/70">Active Agents</div><div class="text-2xl font-bold">{{ $activeAgents }}</div></div>
                </div>
            </div>
        </div>

        <form method="GET" action="{{ route('dashboard') }}" class="dash-card p-5">
            <div class="flex flex-col md:flex-row md:items-end md:justify-between gap-4 mb-4">
                <div>
                    <h3 class="text-lg font-bold text-slate-900">Smart Filters</h3>
                    <p class="text-sm text-slate-500">Admin can find reports agent-wise and by more options.</p>
                </div>
                <div class="flex flex-wrap gap-2">
                    <a href="{{ route('dashboard', ['from_date' => now()->toDateString(), 'to_date' => now()->toDateString()]) }}" class="btn-soft">Today</a>
                    <a href="{{ route('dashboard', ['from_date' => now()->startOfMonth()->toDateString(), 'to_date' => now()->toDateString()]) }}" class="btn-soft">This Month</a>
                    <a href="{{ route('dashboard') }}" class="btn-soft">Reset</a>
                    <button type="submit" class="btn-primary">Apply Filter</button>
                </div>
            </div>
            <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-5 gap-3">
                <div><label class="text-xs font-semibold text-slate-600">Agent</label><select name="agent_id" class="dash-filter-input mt-1"><option value="">All Agents</option>@foreach($agents as $agent)<option value="{{ $agent->id }}" @selected((string)$filters['agent_id'] === (string)$agent->id)>{{ $agent->name }}</option>@endforeach</select></div>
                <div><label class="text-xs font-semibold text-slate-600">Company</label><select name="company_id" class="dash-filter-input mt-1"><option value="">All Companies</option>@foreach($companies as $company)<option value="{{ $company->id }}" @selected((string)$filters['company_id'] === (string)$company->id)>{{ $company->name }}</option>@endforeach</select></div>
                <div><label class="text-xs font-semibold text-slate-600">Destination</label><select name="destination_country" class="dash-filter-input mt-1"><option value="">All Countries</option>@foreach($destinations as $destination)<option value="{{ $destination }}" @selected($filters['destination_country'] === $destination)>{{ $destination }}</option>@endforeach</select></div>
                <div><label class="text-xs font-semibold text-slate-600">From Date</label><input type="date" name="from_date" value="{{ $filters['from_date'] }}" class="dash-filter-input mt-1"></div>
                <div><label class="text-xs font-semibold text-slate-600">To Date</label><input type="date" name="to_date" value="{{ $filters['to_date'] }}" class="dash-filter-input mt-1"></div>
            </div>
        </form>

        <div class="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
            @foreach([
                ['Total Candidates', number_format($totalCandidates), 'Filtered candidate count', '👥'],
                ['Today Candidates', number_format($todayCandidates), now()->format('d M Y'), '📅'],
                ['Total Package', number_format($totalPrice, 2), 'All filtered cases', '💼'],
                ['Total Paid', number_format($totalPaid, 2), 'Received amount', '💳'],
                ['Total Due', number_format($totalDue, 2), 'Package - paid', '⚠️'],
                ['Total Expense', number_format($totalExpense, 2), 'Case expenses', '🧾'],
                ['Profit After Expense', number_format($profitAfterExpense, 2), 'Paid - expense', '📈'],
                ['Profit After Salary', number_format($profitAfterSalary, 2), 'After salary paid', '🏦'],
            ] as $stat)
                <div class="dash-card p-5">
                    <div class="flex items-start justify-between gap-4"><div><div class="text-sm text-slate-500">{{ $stat[0] }}</div><div class="mt-2 text-2xl md:text-3xl font-extrabold text-slate-950">{{ $stat[1] }}</div><div class="mt-2 text-xs text-slate-500">{{ $stat[2] }}</div></div><div class="dash-stat-icon">{{ $stat[3] }}</div></div>
                </div>
            @endforeach
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <div class="lg:col-span-2 dash-card p-6">
                <div class="flex items-center justify-between gap-4 mb-5"><div><h3 class="text-lg font-bold text-slate-900">Pipeline Summary</h3><p class="text-sm text-slate-500">Quick health check for selected filter.</p></div><span class="badge-info">{{ $totalCases }} Cases</span></div>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div class="dash-mini p-4"><div class="text-sm text-slate-500">Open Cases</div><div class="mt-1 text-2xl font-bold text-slate-900">{{ $openCases }}</div></div>
                    <div class="dash-mini p-4"><div class="text-sm text-slate-500">Closed Cases</div><div class="mt-1 text-2xl font-bold text-slate-900">{{ $closedCases }}</div></div>
                    <div class="dash-mini p-4"><div class="text-sm text-slate-500">Average Package</div><div class="mt-1 text-2xl font-bold text-slate-900">{{ number_format($avgPackage, 2) }}</div></div>
                </div>
                <div class="mt-6 space-y-4">
                    <div><div class="flex justify-between text-sm mb-2"><span class="font-semibold text-slate-700">Payment Collection</span><span class="text-slate-500">{{ $collectionRate }}%</span></div><div class="progress-line"><span style="width: {{ min($collectionRate, 100) }}%"></span></div></div>
                    <div><div class="flex justify-between text-sm mb-2"><span class="font-semibold text-slate-700">Expense vs Paid</span><span class="text-slate-500">{{ $expenseRate }}%</span></div><div class="progress-line"><span style="width: {{ min($expenseRate, 100) }}%"></span></div></div>
                </div>
            </div>

            <div class="dash-card p-6">
                <h3 class="text-lg font-bold text-slate-900">Salary Overview</h3>
                <div class="mt-4 space-y-3">
                    <div class="dash-mini p-4"><div class="text-sm text-slate-500">Salary Paid</div><div class="mt-1 text-xl font-bold text-slate-900">{{ number_format($salaryPaid, 2) }}</div></div>
                    <div class="dash-mini p-4"><div class="text-sm text-slate-500">Due Salary</div><div class="mt-1 text-xl font-bold text-slate-900">{{ number_format($salaryDue, 2) }}</div></div>
                </div>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <div class="dash-card overflow-hidden">
                <div class="card-header"><div><div class="card-title">Top Agents</div><div class="text-xs text-slate-500">Based on filtered candidates.</div></div><a href="{{ route('admin.agents.index') }}" class="badge-neutral">View Agents</a></div>
                <div class="p-5 space-y-3">
                    @forelse($topAgents as $row)
                        <div class="flex items-center justify-between rounded-2xl border border-slate-200 p-4"><div class="font-semibold text-slate-900">{{ $row->agent?->name ?? 'No Agent' }}</div><div class="badge-success">{{ $row->candidates_count }} candidates</div></div>
                    @empty
                        <div class="text-sm text-slate-500">No agent data found for this filter.</div>
                    @endforelse
                </div>
            </div>

            <div class="dash-card overflow-hidden">
                <div class="card-header"><div><div class="card-title">Recent Candidates</div><div class="text-xs text-slate-500">Latest records from selected filter.</div></div><a href="{{ route('admin.candidates.index') }}" class="badge-neutral">Open List</a></div>
                <div class="overflow-x-auto">
                    <table class="table">
                        <thead class="thead"><tr><th>Name</th><th>Agent</th><th>Country</th><th>Date</th></tr></thead>
                        <tbody class="tbody">
                            @forelse($recentCandidates as $candidate)
                                <tr class="row-hover"><td class="font-semibold text-slate-900">{{ $candidate->full_name }}</td><td>{{ $candidate->agent?->name ?? 'N/A' }}</td><td>{{ $candidate->destination_country ?: 'N/A' }}</td><td>{{ $candidate->created_at?->format('d M Y') }}</td></tr>
                            @empty
                                <tr><td colspan="4" class="text-slate-500">No candidates found.</td></tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="dash-card p-6">
            <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
                <div><h3 class="text-lg font-bold text-slate-900">Quick Actions</h3><p class="text-sm text-slate-500">Common tasks for admin and manager.</p></div>
                <div class="flex flex-wrap gap-3"><a href="{{ route('admin.candidates.create') }}" class="btn-primary">+ Add Candidate</a><a href="{{ route('admin.candidates.index') }}" class="btn-soft">Open Candidates</a><a href="{{ route('admin.agents.index') }}" class="btn-soft">Manage Agents</a><a href="{{ route('profile.edit') }}" class="btn-soft">My Profile</a></div>
            </div>
        </div>
    </div>
</x-app-layout>
