detectionService = new BrandDetectionService(); } /** * List detection rules for a brand */ public function index(): void { try { $this->requireAuth(); View::render('layouts/main.php', [ 'title' => 'Regras de Deteção de Marca', 'page_content' => function() { View::render('layouts/page-title.php', [ 'pagetitle' => 'Publicidade', 'title' => 'Regras de Deteção de Marca' ]); View::render('@advertising/detection-rules'); } ]); } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'detection_rules_index']); $this->errorResponse('Erro interno do servidor', 500); } } /** * Create new detection rule */ public function create(): void { try { $this->requireAuth(); $data = [ 'brand_id' => (int)InputSanitizer::get('brand_id', 'POST', 0), 'name' => InputSanitizer::get('name', 'POST', ''), 'description' => InputSanitizer::get('description', 'POST', ''), 'rule_type' => InputSanitizer::get('rule_type', 'POST', ''), 'rule_pattern' => InputSanitizer::get('rule_pattern', 'POST', ''), 'priority' => (int)InputSanitizer::get('priority', 'POST', 0), 'is_active' => (bool)InputSanitizer::get('is_active', 'POST', true), 'rule_conditions' => json_decode(InputSanitizer::get('rule_conditions', 'POST', '{}'), true) ?: [], 'extraction_rules' => json_decode(InputSanitizer::get('extraction_rules', 'POST', '{}'), true) ?: [], 'fallback_data' => json_decode(InputSanitizer::get('fallback_data', 'POST', '{}'), true) ?: [] ]; // Validation if (empty($data['brand_id']) || empty($data['name']) || empty($data['rule_type']) || empty($data['rule_pattern'])) { $this->errorResponse('Todos os campos obrigatórios devem ser preenchidos', 422); return; } $ruleId = $this->detectionService->createDetectionRule($data); $this->successResponse([ 'rule_id' => $ruleId, 'message' => 'Regra de deteção criada com sucesso' ]); } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'detection_rules_create']); $this->errorResponse('Erro ao criar regra de deteção', 500); } } /** * Update detection rule */ public function update(int $ruleId): void { try { $this->requireAuth(); $data = [ 'brand_id' => (int)InputSanitizer::get('brand_id', 'POST', 0), 'name' => InputSanitizer::get('name', 'POST', ''), 'description' => InputSanitizer::get('description', 'POST', ''), 'rule_type' => InputSanitizer::get('rule_type', 'POST', ''), 'rule_pattern' => InputSanitizer::get('rule_pattern', 'POST', ''), 'priority' => (int)InputSanitizer::get('priority', 'POST', 0), 'is_active' => (bool)InputSanitizer::get('is_active', 'POST', true), 'rule_conditions' => json_decode(InputSanitizer::get('rule_conditions', 'POST', '{}'), true) ?: [], 'extraction_rules' => json_decode(InputSanitizer::get('extraction_rules', 'POST', '{}'), true) ?: [], 'fallback_data' => json_decode(InputSanitizer::get('fallback_data', 'POST', '{}'), true) ?: [] ]; // Validation if (empty($data['brand_id']) || empty($data['name']) || empty($data['rule_type']) || empty($data['rule_pattern'])) { $this->errorResponse('Todos os campos obrigatórios devem ser preenchidos', 422); return; } $success = $this->detectionService->updateDetectionRule($ruleId, $data); if ($success) { $this->successResponse(['message' => 'Regra de deteção atualizada com sucesso']); } else { $this->errorResponse('Regra de deteção não encontrada', 404); } } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'detection_rules_update']); $this->errorResponse('Erro ao atualizar regra de deteção', 500); } } /** * Delete detection rule */ public function delete(int $ruleId): void { try { $this->requireAuth(); $success = $this->detectionService->deleteDetectionRule($ruleId); if ($success) { $this->successResponse(['message' => 'Regra de deteção eliminada com sucesso']); } else { $this->errorResponse('Regra de deteção não encontrada', 404); } } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'detection_rules_delete']); $this->errorResponse('Erro ao eliminar regra de deteção', 500); } } /** * Test detection rule against URL */ public function test(int $ruleId): void { try { $this->requireAuth(); $url = InputSanitizer::get('url', 'POST', ''); if (empty($url)) { $this->errorResponse('URL é obrigatória', 422); return; } $result = $this->detectionService->testDetectionRule($ruleId, $url); if ($result['success']) { $this->successResponse($result); } else { $this->errorResponse($result['error'], 400); } } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'detection_rules_test']); $this->errorResponse('Erro ao testar regra de deteção', 500); } } /** * Detect brand from URL using all rules */ public function detect(): void { try { $this->requireAuth(); $url = InputSanitizer::get('url', 'POST', ''); if (empty($url)) { $this->errorResponse('URL é obrigatória', 422); return; } $result = $this->detectionService->detectBrandFromUrl($url); if ($result) { $this->successResponse($result); } else { $this->successResponse([ 'detected' => false, 'message' => 'Nenhuma marca detectada para esta URL' ]); } } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'detection_rules_detect']); $this->errorResponse('Erro ao detectar marca', 500); } } /** * Get rule types and examples */ public function getRuleTypes(): void { try { $this->requireAuth(); $ruleTypes = [ 'regex' => [ 'name' => 'Expressão Regular', 'description' => 'Usar regex para deteção avançada', 'example' => '/hollywoodbets\.com.*\?c=([^&]+)/', 'example_url' => 'https://hollywoodbets.com/register?c=AFF001' ], 'domain' => [ 'name' => 'Domínio', 'description' => 'Deteção por domínio ou subdomínio', 'example' => '*.hollywoodbets.com', 'example_url' => 'https://pt.hollywoodbets.com' ], 'path' => [ 'name' => 'Caminho', 'description' => 'Deteção por caminho da URL', 'example' => '/register/*', 'example_url' => null ], 'parameter' => [ 'name' => 'Parâmetro', 'description' => 'Deteção por parâmetro de query string', 'example' => 'c', 'example_url' => null ], 'custom' => [ 'name' => 'Expressão Customizada', 'description' => 'Expressão PHP personalizada', 'example' => 'strpos($host, "hollywoodbets") !== false', 'example_url' => 'https://hollywoodbets.com' ] ]; $this->successResponse($ruleTypes); } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'detection_rules_types']); $this->errorResponse('Erro ao obter tipos de regras', 500); } } /** * Get validation rules */ public function getValidationRules(): void { try { $this->requireAuth(); $validationRules = [ 'required' => 'Campo obrigatório', 'min_length' => 'Comprimento mínimo', 'max_length' => 'Comprimento máximo', 'pattern' => 'Padrão regex', 'in' => 'Valor deve estar na lista', 'not_in' => 'Valor não deve estar na lista', 'starts_with' => 'Deve começar com', 'ends_with' => 'Deve terminar com', 'contains' => 'Deve conter' ]; $this->successResponse($validationRules); } catch (\Exception $e) { ErrorReporter::report($e, ['context' => 'detection_rules_validation']); $this->errorResponse('Erro ao obter regras de validação', 500); } } }