<?php

namespace App\Http\Controllers\App;

use App\Http\Controllers\Controller;
use App\Models\AffiliateCommission;
use App\Models\Lead;
use App\Models\Meeting;
use App\Models\PaymentRequest;
use App\Models\Project;
use App\Models\ProposalDocument;
use Illuminate\Http\Request;
use Illuminate\View\View;

class DashboardController extends Controller
{
    public function index(Request $request): View
    {
        $user = $request->user();

        $leadQuery = Lead::query();
        $proposalQuery = ProposalDocument::query();
        $projectQuery = Project::query();
        $meetingQuery = Meeting::query();
        $paymentQuery = PaymentRequest::query();
        $commissionQuery = AffiliateCommission::query();

        if ($user->isAffiliate()) {
            $leadQuery->where('affiliate_user_id', $user->id);
            $proposalQuery->where('affiliate_user_id', $user->id);
            $projectQuery->where('affiliate_user_id', $user->id);
            $meetingQuery->where('owner_user_id', $user->id);
            $paymentQuery->whereHas('project', fn ($query) => $query->where('affiliate_user_id', $user->id));
            $commissionQuery->where('affiliate_user_id', $user->id);
        } elseif ($user->isResident()) {
            $leadQuery->where('owner_user_id', $user->id);
            $proposalQuery->where('owner_user_id', $user->id);
            $projectQuery->where('owner_user_id', $user->id);
            $meetingQuery->where('owner_user_id', $user->id);
            $paymentQuery->whereHas('project', fn ($query) => $query->where('owner_user_id', $user->id));
        }

        return view('app.dashboard', [
            'metrics' => [
                'leads' => $leadQuery->count(),
                'meetings' => $meetingQuery->count(),
                'proposals' => $proposalQuery->count(),
                'projects' => $projectQuery->count(),
                'payments' => $paymentQuery->count(),
                'commissions' => $commissionQuery->sum('commission_amount'),
            ],
            'recentLeads' => $leadQuery->latest()->take(6)->get(),
            'recentProjects' => $projectQuery->latest()->take(4)->get(),
            'recentProposals' => $proposalQuery->latest()->take(4)->get(),
        ]);
    }
}
