<?php

namespace App\Http\Controllers\API\Public;

use App\Http\Controllers\API\BaseApiController;
use App\Models\InvestmentOpportunity;
use App\Models\Province;
use App\Models\District;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class PublicOpportunityController extends BaseApiController
{
    public function index(Request $request): JsonResponse
    {
        $opportunities = InvestmentOpportunity::with(['province', 'district'])
            ->withCount('expressionsOfInterest')
            ->where('status', 'pronto')
            ->when($request->sector, fn($q) => $q->where('sector', $request->sector))
            ->when($request->province_id, fn($q) => $q->where('province_id', $request->province_id))
            ->when($request->search, fn($q) =>
                $q->where(fn($q2) =>
                    $q2->where('title_pt', 'like', "%{$request->search}%")
                       ->orWhere('description_pt', 'like', "%{$request->search}%")
                ))
            ->when($request->min_investment, fn($q) => $q->where('min_investment', '>=', $request->min_investment))
            ->when($request->max_investment, fn($q) => $q->where('min_investment', '<=', $request->max_investment))
            ->when($request->featured, fn($q) => $q->where('is_featured', true))
            ->when($request->project_stage, fn($q) => $q->where('project_stage', $request->project_stage))
            ->orderByDesc('is_featured')
            ->when(
                !$request->sort || $request->sort === 'newest',
                fn($q) => $q->orderByDesc('published_at'),
                fn($q) => $q->orderBy('published_at')
            )
            ->paginate(min(max((int)($request->per_page ?? 12), 1), 24));

        return $this->paginatedResponse($opportunities);
    }

    public function show(string $code): JsonResponse
    {
        $opportunity = InvestmentOpportunity::with(['province', 'district', 'creator:id,name'])
            ->withCount('expressionsOfInterest')
            ->where('code', $code)
            ->where('status', 'pronto')
            ->firstOrFail();

        return $this->successResponse($opportunity);
    }

    public function provinces(): JsonResponse
    {
        $provinces = Province::orderBy('name')->get();
        return $this->successResponse($provinces);
    }

    public function districts(int $provinceId): JsonResponse
    {
        $districts = District::where('province_id', $provinceId)->orderBy('name')->get();
        return $this->successResponse($districts);
    }

    public function stats(): JsonResponse
    {
        $stats = [
            'total_opportunities' => InvestmentOpportunity::where('status', 'pronto')->count(),
            'total_investment'    => InvestmentOpportunity::where('status', 'pronto')->sum('min_investment'),
            'avg_return_rate'     => InvestmentOpportunity::where('status', 'pronto')->avg('expected_return_rate'),
            'total_jobs'          => InvestmentOpportunity::where('status', 'pronto')->sum('total_jobs'),
            'sectors'             => InvestmentOpportunity::where('status', 'pronto')
                ->selectRaw('sector, count(*) as count')
                ->groupBy('sector')
                ->get(),
        ];

        return $this->successResponse($stats);
    }
}
