<?php

namespace Modules\CRMAvancado\Controllers;

use Gestoreasy\Core\Http\Request;
use Gestoreasy\Core\Http\Response;
use Gestoreasy\Core\Tenant\ConnectionManager;
use Modules\CRMAvancado\Services\LeadScoringService;
use PDO;

class LeadScoringController {
    public function listLeads(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $pdo = ConnectionManager::forTenant();
            
            $page = max(1, (int)($req->query['page'] ?? 1));
            $per = min(100, max(1, (int)($req->query['per_page'] ?? 20)));
            $offset = ($page - 1) * $per;

            $where = ['ls.tenant_id = ?'];
            $params = [$tenantId];

            if (!empty($req->query['classificacao'])) {
                $where[] = 'ls.classificacao = ?';
                $params[] = $req->query['classificacao'];
            }

            if (!empty($req->query['score_min'])) {
                $where[] = 'ls.score_total >= ?';
                $params[] = $req->query['score_min'];
            }

            $whereSql = implode(' AND ', $where);

            $sql = "SELECT ls.*, l.company, l.contact_name, l.email, l.phone, l.value_cents
                    FROM lead_scores ls
                    INNER JOIN crm_leads l ON ls.lead_id = l.id
                    WHERE {$whereSql}
                    ORDER BY ls.score_total DESC
                    LIMIT ? OFFSET ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute(array_merge($params, [$per, $offset]));
            $leads = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // Total
            $countSql = "SELECT COUNT(*) FROM lead_scores ls WHERE {$whereSql}";
            $countStmt = $pdo->prepare($countSql);
            $countStmt->execute($params);
            $total = (int)$countStmt->fetchColumn();

            return Response::json([
                'data' => $leads,
                'pagination' => [
                    'page' => $page,
                    'per_page' => $per,
                    'total' => $total,
                    'total_pages' => (int)ceil($total / $per)
                ]
            ]);
        } catch (\Exception $e) {
            return new Response(500, ['error' => ['code' => 'error', 'message' => $e->getMessage()]]);
        }
    }

    public function getLeadScore(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $leadId = (int)($req->get('params')[0] ?? 0);

            $service = new LeadScoringService($tenantId);
            $score = $service->calcularScore($leadId);

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

    public function calcularScore(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $body = is_array($req->body) ? $req->body : [];
            $leadId = (int)($body['lead_id'] ?? 0);

            if (!$leadId) {
                return new Response(422, ['error' => ['code' => 'validation_error', 'message' => 'lead_id é obrigatório']]);
            }

            $service = new LeadScoringService($tenantId);
            $score = $service->calcularScore($leadId);

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

    public function updateConfig(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $pdo = ConnectionManager::forTenant();
            $body = is_array($req->body) ? $req->body : [];

            // Verificar se existe
            $stmt = $pdo->prepare('SELECT id FROM lead_scoring_config WHERE tenant_id = ?');
            $stmt->execute([$tenantId]);
            $exists = $stmt->fetch();

            $allowedFields = [
                'peso_demografia', 'peso_comportamento', 'peso_engajamento', 'peso_historico',
                'limite_quente', 'limite_morno', 'limite_frio',
                'atualizacao_automatica', 'intervalo_atualizacao_horas'
            ];

            if ($exists) {
                // Atualizar
                $updates = [];
                $params = [];
                foreach ($allowedFields as $field) {
                    if (isset($body[$field])) {
                        $updates[] = "{$field} = ?";
                        $params[] = $body[$field];
                    }
                }
                if (!empty($updates)) {
                    $params[] = $tenantId;
                    $sql = 'UPDATE lead_scoring_config SET ' . implode(', ', $updates) . ' WHERE tenant_id = ?';
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute($params);
                }
            } else {
                // Criar
                $fields = [];
                $values = [];
                $params = [];
                foreach ($allowedFields as $field) {
                    if (isset($body[$field])) {
                        $fields[] = $field;
                        $values[] = '?';
                        $params[] = $body[$field];
                    }
                }
                if (!empty($fields)) {
                    $params[] = $tenantId;
                    $sql = 'INSERT INTO lead_scoring_config (tenant_id, ' . implode(', ', $fields) . ') VALUES (?, ' . implode(', ', $values) . ')';
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute($params);
                }
            }

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

