<?php

namespace App\Http\Controllers\API\Investor;

use App\Helpers\Helper;
use App\Http\Controllers\API\BaseApiController;
use App\Models\InvestmentProposal;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class InvestorProposalController extends BaseApiController
{
    public function index(Request $request): JsonResponse
    {
        $proposals = InvestmentProposal::where('user_id', $request->user()->id)
            ->with(['province', 'district'])
            ->when($request->status, fn($q) => $q->where('status', $request->status))
            ->orderByDesc('updated_at')
            ->paginate(15);

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

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'name'                     => 'required|string|max:255',
            'sector'                   => 'required|in:infraestrutura,agricultura,turismo,energia,pescas,tecnologia,comercio,industria,mineracao,saude,educacao',
            'description'              => 'required|string|min:50',
            'investment_value'         => 'required|numeric|min:1',
            'jobs_to_create'           => 'required|integer|min:0',
            'start_date'               => 'nullable|date|after:today',
            'duration_months'          => 'nullable|integer|min:1',
            'own_capital_pct'          => 'required|numeric|min:0|max:100',
            'bank_credit_pct'          => 'required|numeric|min:0|max:100',
            'external_investor_pct'    => 'required|numeric|min:0|max:100',
            'province_id'              => 'nullable|exists:provinces,id',
            'district_id'              => 'nullable|exists:districts,id',
            'address'                  => 'nullable|string|max:500',
            'is_special_economic_zone' => 'boolean',
            'opportunity_id'           => 'nullable|exists:investment_opportunities,id',
            'business_plan_url'        => 'nullable|string',
            'financial_projections_url'=> 'nullable|string',
        ]);

        $total = ($data['own_capital_pct'] ?? 0) + ($data['bank_credit_pct'] ?? 0) + ($data['external_investor_pct'] ?? 0);
        if (abs($total - 100) > 0.01) {
            return $this->errorResponse('As fontes de financiamento devem somar 100%', 422);
        }

        $proposal = InvestmentProposal::create([
            ...$data,
            'code'    => Helper::generateCode(10, 'investment_proposals'),
            'user_id' => $request->user()->id,
            'status'  => 'rascunho',
        ]);

        return $this->successResponse($proposal->load(['province', 'district']), 'Proposta criada com sucesso', 201);
    }

    public function show(Request $request, int $id): JsonResponse
    {
        $proposal = InvestmentProposal::where('user_id', $request->user()->id)
            ->with(['province', 'district', 'opportunity'])
            ->findOrFail($id);

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

    public function update(Request $request, int $id): JsonResponse
    {
        $proposal = InvestmentProposal::where('user_id', $request->user()->id)->findOrFail($id);

        if (!in_array($proposal->status, ['rascunho', 'em_revisao'])) {
            return $this->errorResponse('Não é possível editar uma proposta com o estado actual', 422);
        }

        $data = $request->validate([
            'name'                     => 'sometimes|string|max:255',
            'sector'                   => 'sometimes|in:infraestrutura,agricultura,turismo,energia,pescas,tecnologia,comercio,industria,mineracao,saude,educacao',
            'description'              => 'sometimes|string|min:50',
            'investment_value'         => 'sometimes|numeric|min:1',
            'jobs_to_create'           => 'sometimes|integer|min:0',
            'start_date'               => 'sometimes|nullable|date',
            'duration_months'          => 'sometimes|nullable|integer|min:1',
            'own_capital_pct'          => 'sometimes|numeric|min:0|max:100',
            'bank_credit_pct'          => 'sometimes|numeric|min:0|max:100',
            'external_investor_pct'    => 'sometimes|numeric|min:0|max:100',
            'province_id'              => 'sometimes|nullable|exists:provinces,id',
            'district_id'              => 'sometimes|nullable|exists:districts,id',
            'address'                  => 'sometimes|nullable|string|max:500',
            'is_special_economic_zone' => 'sometimes|boolean',
            'business_plan_url'        => 'sometimes|nullable|string',
            'financial_projections_url'=> 'sometimes|nullable|string',
        ]);

        $proposal->update($data);

        return $this->successResponse($proposal->fresh(['province', 'district']), 'Proposta actualizada');
    }

    public function destroy(Request $request, int $id): JsonResponse
    {
        $proposal = InvestmentProposal::where('user_id', $request->user()->id)->findOrFail($id);

        if ($proposal->status !== 'rascunho') {
            return $this->errorResponse('Apenas rascunhos podem ser eliminados', 422);
        }

        $proposal->delete();

        return $this->successResponse(null, 'Proposta eliminada');
    }

    public function submit(Request $request, int $id): JsonResponse
    {
        $proposal = InvestmentProposal::where('user_id', $request->user()->id)->findOrFail($id);

        if (!in_array($proposal->status, ['rascunho', 'em_revisao'])) {
            return $this->errorResponse('Esta proposta já foi submetida', 422);
        }

        if (!$proposal->business_plan_url || !$proposal->financial_projections_url) {
            return $this->errorResponse('É necessário carregar o Plano de Negócios e as Projecções Financeiras', 422);
        }

        $proposal->update([
            'status'       => 'submetido',
            'submitted_at' => now(),
        ]);

        activity('proposals')->performedOn($proposal)
            ->causedBy($request->user())
            ->log('Proposta submetida: ' . $proposal->code);

        return $this->successResponse($proposal, 'Proposta submetida com sucesso');
    }

    public function withdraw(Request $request, int $id): JsonResponse
    {
        $proposal = InvestmentProposal::where('user_id', $request->user()->id)->findOrFail($id);

        if ($proposal->status !== 'submetido') {
            return $this->errorResponse('Apenas propostas submetidas podem ser retiradas', 422);
        }

        $proposal->update(['status' => 'rascunho', 'submitted_at' => null]);

        return $this->successResponse($proposal, 'Proposta retirada com sucesso');
    }
}
