<?php

namespace App\Http\Controllers\API\Investor;

use App\Http\Controllers\API\BaseApiController;
use App\Models\ExpressionOfInterest;
use App\Models\InvestmentOpportunity;
use App\Models\InvestmentProposal;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class InvestorDashboardController extends BaseApiController
{
    public function index(Request $request): JsonResponse
    {
        $user = $request->user();

        $proposals = InvestmentProposal::where('user_id', $user->id);

        $interests = ExpressionOfInterest::where('user_id', $user->id);

        $stats = [
            'total_proposals'     => (clone $proposals)->count(),
            'pending_review'      => (clone $proposals)->whereIn('status', ['submetido', 'em_analise'])->count(),
            'approved'            => (clone $proposals)->where('status', 'aprovado')->count(),
            'rejected'            => (clone $proposals)->where('status', 'rejeitado')->count(),
            'total_investment'    => (clone $proposals)->whereIn('status', ['aprovado', 'em_analise', 'submetido'])->sum('investment_value'),
            'total_interests'     => (clone $interests)->count(),
            'pending_interests'   => (clone $interests)->whereIn('status', ['nova', 'em_analise'])->count(),
            'unread_messages'     => $user->receivedMessages()->where('is_read', false)->count(),
            'unread_notifications'=> $user->unreadNotifications()->count(),
        ];

        $recentProposals = InvestmentProposal::where('user_id', $user->id)
            ->with(['province'])
            ->latest()
            ->take(5)
            ->get();

        $suggestedOpportunities = InvestmentOpportunity::where('status', 'pronto')
            ->where('is_featured', true)
            ->take(3)
            ->get(['id', 'code', 'title_pt', 'sector', 'min_investment', 'expected_return_rate', 'total_jobs']);

        return $this->successResponse([
            'stats'                   => $stats,
            'recent_proposals'        => $recentProposals,
            'suggested_opportunities' => $suggestedOpportunities,
        ]);
    }
}
