db = DatabaseManager::getInstance(); $this->logger = new Logger('debug'); } /** * Adicionar MB para uma marca em ZA uma vez em cada 24h */ public function addMultiBookForBrand(string $brandName, string $country = 'ZA'): array { try { // Verificar se já existe um MB para esta marca no país nas últimas 24h $existingMB = $this->db->fetch( "SELECT id, created_at FROM advertising_multibooks WHERE brand_name = ? AND country = ? AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR) ORDER BY created_at DESC LIMIT 1", [Sanitize::string($brandName), Sanitize::string($country)] ); if ($existingMB) { $this->logger->info('MB já existe para marca no país nas últimas 24h', [ 'brand_name' => $brandName, 'country' => $country, 'existing_id' => $existingMB['id'], 'created_at' => $existingMB['created_at'] ]); return [ 'success' => false, 'message' => "MB já existe para {$brandName} em {$country} nas últimas 24h", 'existing_mb' => $existingMB, 'next_available' => date('Y-m-d H:i:s', strtotime($existingMB['created_at'] . ' +24 hours')) ]; } // Gerar MB único $mbId = $this->generateMultiBookId($brandName, $country); // Criar MB $result = $this->db->query( "INSERT INTO advertising_multibooks ( mb_id, brand_name, country, status, settings, created_by, created_at ) VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)", [ $mbId, Sanitize::string($brandName), Sanitize::string($country), 'active', json_encode([ 'auto_generated' => true, 'generated_at' => date('Y-m-d H:i:s'), 'brand_original' => $brandName, 'country_target' => $country ]), \App\Core\Auth::getUserId() ?? 1 ] ); if (!$result) { throw new \Exception('Failed to create multibook'); } $mbId = $this->db->lastInsertId(); $this->logger->info('MB criado com sucesso para marca em país', [ 'brand_name' => $brandName, 'country' => $country, 'mb_id' => $mbId, 'generated_id' => $mbId ]); return [ 'success' => true, 'message' => "MB criado com sucesso para {$brandName} em {$country}", 'mb_id' => $mbId, 'generated_id' => $mbId, 'next_available' => date('Y-m-d H:i:s', strtotime('+24 hours')) ]; } catch (\Exception $e) { $this->logger->error('Erro ao criar MB para marca: ' . $e->getMessage(), [ 'brand_name' => $brandName, 'country' => $country, 'error' => $e->getMessage() ]); ErrorReporter::report($e); return [ 'success' => false, 'message' => 'Erro ao criar MB: ' . $e->getMessage() ]; } } /** * Gerar ID único para MultiBook */ private function generateMultiBookId(string $brandName, string $country): string { // Normalizar brand name $normalizedBrand = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $brandName)); // Criar prefixo baseado na marca e país $prefix = substr($normalizedBrand, 0, 3) . '-' . strtolower($country); // Adicionar timestamp para garantir unicidade $timestamp = time(); // Gerar sufixo aleatório $suffix = substr(md5(uniqid()), 0, 8); return $prefix . '-' . $timestamp . '-' . $suffix; } /** * Obter MBs de uma marca */ public function getMultiBooksByBrand(string $brandName, int $limit = 50): array { try { $results = $this->db->fetchAll( "SELECT * FROM advertising_multibooks WHERE brand_name = ? ORDER BY created_at DESC LIMIT ?", [Sanitize::string($brandName), $limit] ) ?: []; // Decodificar settings JSON foreach ($results as &$result) { if (!empty($result['settings'])) { $result['settings'] = json_decode($result['settings'], true); } } return $results; } catch (\Exception $e) { $this->logger->error('Erro ao obter MBs da marca: ' . $e->getMessage(), [ 'brand_name' => $brandName, 'error' => $e->getMessage() ]); return []; } } /** * Obter MBs por país */ public function getMultiBooksByCountry(string $country, int $limit = 50): array { try { $results = $this->db->fetchAll( "SELECT * FROM advertising_multibooks WHERE country = ? ORDER BY created_at DESC LIMIT ?", [Sanitize::string($country), $limit] ) ?: []; // Decodificar settings JSON foreach ($results as &$result) { if (!empty($result['settings'])) { $result['settings'] = json_decode($result['settings'], true); } } return $results; } catch (\Exception $e) { $this->logger->error('Erro ao obter MBs do país: ' . $e->getMessage(), [ 'country' => $country, 'error' => $e->getMessage() ]); return []; } } /** * Verificar se pode criar MB para marca em país */ public function canCreateMultiBook(string $brandName, string $country = 'ZA'): array { try { $existingMB = $this->db->fetch( "SELECT id, created_at FROM advertising_multibooks WHERE brand_name = ? AND country = ? AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR) ORDER BY created_at DESC LIMIT 1", [Sanitize::string($brandName), Sanitize::string($country)] ); if ($existingMB) { $nextAvailable = date('Y-m-d H:i:s', strtotime($existingMB['created_at'] . ' +24 hours')); $timeRemaining = strtotime($nextAvailable) - time(); return [ 'can_create' => false, 'reason' => 'MB já existe nas últimas 24h', 'existing_mb' => $existingMB, 'next_available' => $nextAvailable, 'time_remaining_hours' => round($timeRemaining / 3600, 2) ]; } return [ 'can_create' => true, 'reason' => 'Pode criar novo MB', 'next_available' => 'Agora' ]; } catch (\Exception $e) { $this->logger->error('Erro ao verificar se pode criar MB: ' . $e->getMessage(), [ 'brand_name' => $brandName, 'country' => $country, 'error' => $e->getMessage() ]); return [ 'can_create' => false, 'reason' => 'Erro ao verificar: ' . $e->getMessage() ]; } } /** * Obter estatísticas de MBs */ public function getMultiBookStatistics(?string $brandName = null, ?string $country = null): array { try { $whereClause = "WHERE 1=1"; $params = []; if ($brandName) { $whereClause .= " AND brand_name = ?"; $params[] = Sanitize::string($brandName); } if ($country) { $whereClause .= " AND country = ?"; $params[] = Sanitize::string($country); } // Estatísticas gerais $stats = $this->db->fetch( "SELECT COUNT(*) as total_mbs, COUNT(DISTINCT brand_name) as unique_brands, COUNT(DISTINCT country) as unique_countries, COUNT(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR) THEN 1 END) as last_24h, COUNT(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as last_7_days, COUNT(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 END) as last_30_days FROM advertising_multibooks {$whereClause}", $params ); // Top marcas $topBrands = $this->db->fetchAll( "SELECT brand_name, COUNT(*) as count FROM advertising_multibooks {$whereClause} GROUP BY brand_name ORDER BY count DESC LIMIT 10", $params ); // Top países $topCountries = $this->db->fetchAll( "SELECT country, COUNT(*) as count FROM advertising_multibooks {$whereClause} GROUP BY country ORDER BY count DESC LIMIT 10", $params ); return [ 'statistics' => $stats, 'top_brands' => $topBrands, 'top_countries' => $topCountries ]; } catch (\Exception $e) { $this->logger->error('Erro ao obter estatísticas de MBs: ' . $e->getMessage(), [ 'brand_name' => $brandName, 'country' => $country, 'error' => $e->getMessage() ]); return [ 'statistics' => [], 'top_brands' => [], 'top_countries' => [] ]; } } /** * Criar tabela de multibooks se não existir */ public function ensureMultiBooksTable(): bool { try { $sql = "CREATE TABLE IF NOT EXISTS advertising_multibooks ( id BIGINT AUTO_INCREMENT PRIMARY KEY, mb_id VARCHAR(100) NOT NULL, brand_name VARCHAR(255) NOT NULL, country VARCHAR(2) NOT NULL, status ENUM('active', 'inactive', 'paused') DEFAULT 'active' NOT NULL, settings JSON NULL, created_by BIGINT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL, deleted_at TIMESTAMP NULL, INDEX idx_mb_id (mb_id), INDEX idx_brand_name (brand_name), INDEX idx_country (country), INDEX idx_created_at (created_at), INDEX idx_status (status), UNIQUE KEY unique_mb_id (mb_id) )"; $this->db->query($sql); return true; } catch (\Exception $e) { $this->logger->error('Erro ao criar tabela de multibooks: ' . $e->getMessage(), [ 'error' => $e->getMessage() ]); return false; } } /** * Limpar MBs antigos (mais de 30 dias) - soft delete */ public function cleanupOldMultiBooks(int $daysToKeep = 30): int { try { $sql = "UPDATE advertising_multibooks SET status = '-1', updated_at = CURRENT_TIMESTAMP WHERE created_at < DATE_SUB(NOW(), INTERVAL ? DAY) AND status >= 0"; $affectedRows = $this->db->query($sql, [$daysToKeep]); $this->logger->info('MBs antigos limpos (soft delete)', [ 'days_to_keep' => $daysToKeep, 'deleted_records' => $affectedRows ]); return $affectedRows; } catch (\Exception $e) { $this->logger->error('Erro ao limpar MBs antigos: ' . $e->getMessage(), [ 'days_to_keep' => $daysToKeep, 'error' => $e->getMessage() ]); return 0; } } }