<?php

namespace App\Http\Controllers\API\Admin;

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

class AdminDashboardController extends BaseApiController
{
    public function index(): JsonResponse
    {
        $stats = [
            'total_opportunities'  => InvestmentOpportunity::count(),
            'active_opportunities' => InvestmentOpportunity::where('status', 'pronto')->count(),
            'total_eoi'            => ExpressionOfInterest::count(),
            'pending_eoi'          => ExpressionOfInterest::where('status', 'nova')->count(),
            'total_investors'      => User::whereHas('roles', fn($q) => $q->where('name', 'investor'))->count(),
            'total_proposals'      => InvestmentProposal::count(),
            'total_investment'     => (float) InvestmentProposal::whereNotNull('investment_value')->sum('investment_value'),
        ];

        // Monthly chart: last 12 months
        $chartData = collect(range(0, 11))->map(function (int $offset) {
            $date = Carbon::now()->subMonths(11 - $offset);
            return [
                'month'         => $date->locale('pt')->isoFormat('MMM'),
                'opportunities' => InvestmentOpportunity::whereYear('created_at', $date->year)
                    ->whereMonth('created_at', $date->month)
                    ->count(),
                'proposals'     => InvestmentProposal::whereYear('created_at', $date->year)
                    ->whereMonth('created_at', $date->month)
                    ->count(),
                'eoi'           => ExpressionOfInterest::whereYear('created_at', $date->year)
                    ->whereMonth('created_at', $date->month)
                    ->count(),
            ];
        })->values();

        $recentInterests = ExpressionOfInterest::with([
            'investor:id,uid,name,email,company_name',
            'opportunity:id,code,title_pt',
        ])
            ->where('status', 'nova')
            ->latest()
            ->take(7)
            ->get();

        $recentProposals = InvestmentProposal::with(['user:id,uid,name,email', 'province:id,name'])
            ->latest('updated_at')
            ->take(5)
            ->get();

        return $this->successResponse([
            'stats'           => $stats,
            'chart_data'      => $chartData,
            'recent_interests' => $recentInterests,
            'recent_proposals' => $recentProposals,
        ]);
    }
}
