<?php

namespace Modules\CRMAvancado\Controllers;

use Gestoreasy\Core\Http\Request;
use Gestoreasy\Core\Http\Response;
use Modules\CRMAvancado\Services\FunnelService;

class FunnelController {
    public function getFunil(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $dataInicio = $req->query['data_inicio'] ?? null;
            $dataFim = $req->query['data_fim'] ?? null;

            $service = new FunnelService($tenantId);
            $funil = $service->getFunil($dataInicio, $dataFim);

            return Response::json(['data' => $funil]);
        } catch (\Exception $e) {
            return new Response(500, ['error' => ['code' => 'error', 'message' => $e->getMessage()]]);
        }
    }

    public function getMetricas(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $dataInicio = $req->query['data_inicio'] ?? null;
            $dataFim = $req->query['data_fim'] ?? null;

            $service = new FunnelService($tenantId);
            $metricas = $service->getMetricas($dataInicio, $dataFim);

            return Response::json(['data' => $metricas]);
        } catch (\Exception $e) {
            return new Response(500, ['error' => ['code' => 'error', 'message' => $e->getMessage()]]);
        }
    }

    public function getPrevisao(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $dias = (int)($req->query['dias'] ?? 30);

            $service = new FunnelService($tenantId);
            $previsao = $service->getPrevisao($dias);

            return Response::json(['data' => $previsao]);
        } catch (\Exception $e) {
            return new Response(500, ['error' => ['code' => 'error', 'message' => $e->getMessage()]]);
        }
    }
}

