<?php

namespace App\Http\Controllers\Agent;

use App\Http\Controllers\Controller;
use App\Models\Agent;
use App\Models\Candidate;
use App\Models\RecruitmentCase;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class AgentDashboardController extends Controller
{
    public function index()
    {
        $agent = Agent::where('user_id', Auth::id())->firstOrFail();

        // Aggregate finance stats across all cases under this agent.
        // Paid = sum(payments.amount)
        // Due  = sum(max(total_price - paid_per_case, 0))
        $paymentSub = DB::table('payments')
            ->selectRaw('recruitment_case_id, SUM(amount) as paid')
            ->groupBy('recruitment_case_id');

        $allowedCompanyIds = (Schema::hasTable('agent_company') && Schema::hasColumn('candidates', 'company_id'))
            ? $agent->allowedCompanies()->pluck('companies.id')->all()
            : null;

        $financeQuery = RecruitmentCase::query()
            ->join('candidates', 'candidates.id', '=', 'recruitment_cases.candidate_id')
            ->leftJoinSub($paymentSub, 'p', function ($join) {
                $join->on('p.recruitment_case_id', '=', 'recruitment_cases.id');
            })
            ->where('candidates.agent_id', $agent->id);

        if ($allowedCompanyIds !== null) {
            $financeQuery->whereIn('candidates.company_id', $allowedCompanyIds ?: [0]);
        }

        $finance = $financeQuery
            ->selectRaw('COALESCE(SUM(p.paid), 0) as paid_total')
            ->selectRaw('COALESCE(SUM(GREATEST(COALESCE(recruitment_cases.total_price,0) - COALESCE(p.paid,0), 0)), 0) as due_total')
            ->first();

        $paidTotal = (float) ($finance->paid_total ?? 0);
        $dueTotal  = (float) ($finance->due_total ?? 0);

        $candidateQuery = Candidate::query()->where('agent_id', $agent->id);
        if ($allowedCompanyIds !== null) {
            $candidateQuery->whereIn('company_id', $allowedCompanyIds ?: [0]);
        }

        $candidates = (clone $candidateQuery)
            ->with(['company', 'recruitmentCase.currentStep'])
            ->orderByDesc('id')
            ->paginate(20);

        $total = (clone $candidateQuery)->count();

        return view('agent.dashboard', compact('agent', 'candidates', 'total', 'paidTotal', 'dueTotal'));
    }
}
