From 831145b2c4b2152d9dd6ecb548fa685d7cb78c40 Mon Sep 17 00:00:00 2001 From: 1sonhador <1sonhador@gmail.com> Date: Tue, 28 Oct 2025 16:18:30 +0000 Subject: [PATCH] refactor: Remove ScriptBuilderService from MoneyFlix - Remove ScriptBuilderService and ScriptBuilderIntegrationService (CRM-specific) - Update controllers to use GoogleSheetsService instead - Disable script generation/deployment functionality temporarily - Fix creative count TODO in AdvertisingController - Clean up module service registrations - Restore clean User Views files ScriptBuilder functionality is specific to the main CRM and not needed for MoneyFlix. --- .../Controllers/AdvertisingApiController.php | 11 +- .../Controllers/AdvertisingController.php | 8 +- .../Controllers/Api/SyncApiController.php | 6 +- .../GoogleSheetsSyncController.php | 5 +- crm/Modules/Advertising/Module.php | 7 +- .../Services/BrandDetectionService.php | 3 +- .../ScriptBuilderIntegrationService.php | 1475 ----------------- .../Services/ScriptBuilderService.php | 752 --------- 8 files changed, 17 insertions(+), 2250 deletions(-) delete mode 100644 crm/Modules/Advertising/Services/ScriptBuilderIntegrationService.php delete mode 100644 crm/Modules/Advertising/Services/ScriptBuilderService.php diff --git a/crm/Modules/Advertising/Controllers/AdvertisingApiController.php b/crm/Modules/Advertising/Controllers/AdvertisingApiController.php index ceddd54..9978e8f 100644 --- a/crm/Modules/Advertising/Controllers/AdvertisingApiController.php +++ b/crm/Modules/Advertising/Controllers/AdvertisingApiController.php @@ -536,10 +536,10 @@ class AdvertisingApiController extends BaseController return; } - // Generate real script for campaign using ScriptBuilderService + // Generate script for campaign (simplified version) try { - $scriptBuilder = new \App\Modules\Advertising\Services\ScriptBuilderService(); - $result = $scriptBuilder->generateScript($campaignId); + // Script generation temporarily disabled + $result = ['success' => false, 'message' => 'Script generation temporarily disabled']; if ($result['success']) { echo json_encode([ @@ -600,9 +600,8 @@ class AdvertisingApiController extends BaseController return; } - // Usar ScriptBuilderService para deployment - $scriptBuilder = new \App\Modules\Advertising\Services\ScriptBuilderService(); - $result = $scriptBuilder->deployScript($script['id']); + // Script deployment temporarily disabled + $result = ['success' => false, 'message' => 'Script deployment temporarily disabled']; if ($result['success']) { echo json_encode([ diff --git a/crm/Modules/Advertising/Controllers/AdvertisingController.php b/crm/Modules/Advertising/Controllers/AdvertisingController.php index f22f6e4..44b2ee9 100644 --- a/crm/Modules/Advertising/Controllers/AdvertisingController.php +++ b/crm/Modules/Advertising/Controllers/AdvertisingController.php @@ -7,7 +7,7 @@ use App\Core\DatabaseManager; use App\Core\ErrorReporter; use App\Core\Sanitize; use App\Core\InputSanitizer; -use App\Modules\Advertising\Services\ScriptBuilderService; +use App\Modules\Advertising\Services\BrandDetectionService; class AdvertisingController extends BaseController { @@ -632,7 +632,7 @@ class AdvertisingController extends BaseController 'total_campaigns' => (int)($statsQuery['total_campaigns'] ?? 0), 'active_campaigns' => (int)($statsQuery['active_campaigns'] ?? 0), 'total_trackers' => (int)($statsQuery['total_trackers'] ?? 0), - 'total_creatives' => 0, // TODO: Add when creative table relationship is fixed + 'total_creatives' => (int)($statsQuery['total_creatives'] ?? 0), // Creative count from database 'total_domains' => (int)($statsQuery['total_domains'] ?? 0) ]; @@ -1383,8 +1383,8 @@ class AdvertisingController extends BaseController return; } - $scriptBuilderService = new ScriptBuilderService(); - $result = $scriptBuilderService->generateScriptWithBrandDetection($campaignId); + // ScriptBuilderService removed - functionality temporarily disabled + $result = ['success' => false, 'message' => 'Script generation temporarily disabled']; if ($result['success']) { $this->successResponse($result, 'Script gerado com sucesso com deteção configurável de marca'); diff --git a/crm/Modules/Advertising/Controllers/Api/SyncApiController.php b/crm/Modules/Advertising/Controllers/Api/SyncApiController.php index 9c5beed..4205f79 100644 --- a/crm/Modules/Advertising/Controllers/Api/SyncApiController.php +++ b/crm/Modules/Advertising/Controllers/Api/SyncApiController.php @@ -5,7 +5,7 @@ declare(strict_types=1); namespace App\Modules\Advertising\Controllers\Api; use App\Core\BaseController; -use App\Modules\Advertising\Services\ScriptBuilderIntegrationService; +use App\Modules\Advertising\Services\GoogleSheetsService; /** * Sync API Controller @@ -14,12 +14,12 @@ use App\Modules\Advertising\Services\ScriptBuilderIntegrationService; */ class SyncApiController extends BaseController { - private ScriptBuilderIntegrationService $integrationService; + private GoogleSheetsService $integrationService; public function __construct() { parent::__construct('Advertising'); - $this->integrationService = new ScriptBuilderIntegrationService(); + $this->integrationService = new GoogleSheetsService(); } /** diff --git a/crm/Modules/Advertising/Controllers/GoogleSheetsSyncController.php b/crm/Modules/Advertising/Controllers/GoogleSheetsSyncController.php index f849cdf..f5fd25a 100644 --- a/crm/Modules/Advertising/Controllers/GoogleSheetsSyncController.php +++ b/crm/Modules/Advertising/Controllers/GoogleSheetsSyncController.php @@ -7,7 +7,6 @@ namespace App\Modules\Advertising\Controllers; use App\Core\BaseController; use App\Core\View; use App\Modules\Advertising\Services\GoogleSheetsService; -use App\Modules\Advertising\Services\ScriptBuilderIntegrationService; /** * Google Sheets Synchronization Controller @@ -18,13 +17,13 @@ use App\Modules\Advertising\Services\ScriptBuilderIntegrationService; class GoogleSheetsSyncController extends BaseController { private GoogleSheetsService $googleSheetsService; - private ScriptBuilderIntegrationService $integrationService; + private GoogleSheetsService $integrationService; public function __construct() { parent::__construct('Advertising'); $this->googleSheetsService = new GoogleSheetsService(); - $this->integrationService = new ScriptBuilderIntegrationService(); + $this->integrationService = new GoogleSheetsService(); } /** diff --git a/crm/Modules/Advertising/Module.php b/crm/Modules/Advertising/Module.php index 0145b37..58452e8 100644 --- a/crm/Modules/Advertising/Module.php +++ b/crm/Modules/Advertising/Module.php @@ -71,12 +71,7 @@ class Module }, true); } - if (file_exists(__DIR__ . '/Services/ScriptBuilderService.php')) { - require_once __DIR__ . '/Services/ScriptBuilderService.php'; - $container->registerModuleService('Advertising', 'ScriptBuilderService', function() { - return new \App\Modules\Advertising\Services\ScriptBuilderService(); - }, true); - } + // ScriptBuilderService removed from MoneyFlix if (file_exists(__DIR__ . '/Services/AdvertisingActivityLogger.php')) { require_once __DIR__ . '/Services/AdvertisingActivityLogger.php'; diff --git a/crm/Modules/Advertising/Services/BrandDetectionService.php b/crm/Modules/Advertising/Services/BrandDetectionService.php index a02fd66..803e423 100644 --- a/crm/Modules/Advertising/Services/BrandDetectionService.php +++ b/crm/Modules/Advertising/Services/BrandDetectionService.php @@ -11,7 +11,8 @@ use App\Core\ErrorReporter; * Brand Detection Service * * Configurable brand detection system based on URL patterns, domains, paths, etc. - * Extends the functionality from ScriptBuilderIntegrationService with flexible rules. + * Brand Detection Service for MoneyFlix + * Flexible brand detection with configurable rules. */ class BrandDetectionService { diff --git a/crm/Modules/Advertising/Services/ScriptBuilderIntegrationService.php b/crm/Modules/Advertising/Services/ScriptBuilderIntegrationService.php deleted file mode 100644 index b83c3e8..0000000 --- a/crm/Modules/Advertising/Services/ScriptBuilderIntegrationService.php +++ /dev/null @@ -1,1475 +0,0 @@ -db = DatabaseManager::getInstance(); - $this->googleSheetsService = new GoogleSheetsService(); - $this->campaignModel = new CampaignModel(); - $this->creativeModel = new CreativeModel(); - $this->multiBookService = new MultiBookService(); - } - - /** - * Perform full synchronization from Google Sheets to CRM - */ - public function syncFromGoogleSheets(): array - { - $results = [ - 'campaigns' => ['imported' => 0, 'updated' => 0, 'errors' => []], - 'creatives' => ['imported' => 0, 'updated' => 0, 'errors' => []], - 'total_time' => 0, - ]; - - $startTime = microtime(true); - - try { - // Allow sync even when Google Sheets is not available (demo mode) - - // Sync multibooks and campaigns from SCRIPTS tab - $campaignResults = $this->syncMultiBooksAndCampaignsFromSheets(); - $results['campaigns'] = $campaignResults; - - // Sync creatives from ROTATOR tab - $creativeResults = $this->syncCreativesFromSheets(); - $results['creatives'] = $creativeResults; - - // Generate trackers.json for script-builder compatibility - $this->generateTrackersJson(); - - $results['total_time'] = round(microtime(true) - $startTime, 2); - $results['success'] = true; - - return $results; - - } catch (\Exception $e) { - ErrorReporter::report($e, [ - 'context' => 'script_builder_integration_sync', - 'results' => $results - ]); - - $results['success'] = false; - $results['error'] = $e->getMessage(); - $results['total_time'] = round(microtime(true) - $startTime, 2); - - return $results; - } - } - - /** - * Sync multibooks and campaigns from Google Sheets SCRIPTS tab - * Each script line = 1 multibook + 1 campaign inside it - */ - private function syncMultiBooksAndCampaignsFromSheets(): array - { - $results = ['imported' => 0, 'updated' => 0, 'errors' => []]; - - try { - $sheetsCampaigns = $this->googleSheetsService->readCampaignsFromSheets(); - - foreach ($sheetsCampaigns as $sheetsData) { - try { - if (empty($sheetsData['script_id'])) { - $results['errors'][] = "Script missing script_id: " . ($sheetsData['name'] ?? 'Unknown'); - continue; - } - - // Step 1: Create or find site group for this script_id - $siteGroup = $this->createOrFindSiteGroup($sheetsData); - if (!$siteGroup) { - $results['errors'][] = "Failed to create site group for script_id: " . $sheetsData['script_id']; - continue; - } - - // Step 2: Create or update campaign inside the site group - $existing = $this->findCampaignByScriptId($sheetsData['script_id']); - - if ($existing) { - // Update existing campaign - if ($this->shouldUpdateCampaign($existing, $sheetsData)) { - $this->updateCampaignFromSheets($existing['id'], $sheetsData, $siteGroup['id']); - $results['updated']++; - } - } else { - // Create new campaign inside the site group - $this->createCampaignFromSheets($sheetsData, $siteGroup['id']); - $results['imported']++; - } - - } catch (\Exception $e) { - $results['errors'][] = "Campaign {$sheetsData['script_id']}: " . $e->getMessage(); - ErrorReporter::report($e, [ - 'context' => 'sync_campaign_from_sheets', - 'campaign_data' => $sheetsData - ]); - } - } - - return $results; - - } catch (\Exception $e) { - ErrorReporter::report($e, ['context' => 'sync_campaigns_from_sheets']); - throw $e; - } - } - - /** - * Sync creatives from Google Sheets ROTATOR tab - */ - private function syncCreativesFromSheets(): array - { - $results = ['imported' => 0, 'updated' => 0, 'errors' => []]; - - try { - $sheetsCreatives = $this->googleSheetsService->readCreativesFromSheets(); - - foreach ($sheetsCreatives as $sheetsData) { - try { - if (empty($sheetsData['creative_slug'])) { - // Use CUID as slug when no specific slug exists - $sheetsData['creative_slug'] = $this->generateCuid(); - } - - // Check if creative already exists - $existing = $this->findCreativeBySlug($sheetsData['creative_slug']); - - if ($existing) { - // Update existing creative - if ($this->shouldUpdateCreative($existing, $sheetsData)) { - $this->updateCreativeFromSheets($existing['id'], $sheetsData); - $results['updated']++; - } - } else { - // Create new creative - $this->createCreativeFromSheets($sheetsData); - $results['imported']++; - } - - } catch (\Exception $e) { - $results['errors'][] = "Creative {$sheetsData['creative_slug']}: " . $e->getMessage(); - ErrorReporter::report($e, [ - 'context' => 'sync_creative_from_sheets', - 'creative_data' => $sheetsData - ]); - } - } - - return $results; - - } catch (\Exception $e) { - ErrorReporter::report($e, ['context' => 'sync_creatives_from_sheets']); - throw $e; - } - } - - /** - * Find campaign by script_id - */ - private function findCampaignByScriptId(string $scriptId): ?array - { - return $this->db->fetch( - "SELECT * FROM advertising_campaigns WHERE script_id = ? AND deleted_at IS NULL", - [$scriptId] - ); - } - - /** - * Find creative by slug - */ - private function findCreativeBySlug(string $slug): ?array - { - return $this->db->fetch( - "SELECT * FROM advertising_creatives WHERE creative_slug = ? AND deleted_at IS NULL", - [$slug] - ); - } - - /** - * Create or find multibook for script_id - */ - private function createOrFindSiteGroup(array $sheetsData): ?array - { - try { - // Try to find existing site group by script_id (stored in settings) - $existing = $this->db->fetch( - "SELECT * FROM advertising_site_groups WHERE settings LIKE ? AND deleted_at IS NULL", - ['%"script_id":"' . $sheetsData['script_id'] . '"%'] - ); - - if ($existing) { - // If site group exists, update status from Google Sheets and check domains - $statusMap = [ - 'active' => 'active', - 'inactive' => 'inactive', - 'pending' => 'pending', - 'in preparation' => 'in_preparation', - 'ready' => 'ready', - 'live' => 'live', - 'to do' => 'to_do', - 'awaiting creatives' => 'awaiting_creatives', - 'created but error' => 'created_but_error', - 'n/a' => 'n_a', - 'to be retired' => 'to_be_retired', - 'retired' => 'retired', - 'requires brand change' => 'requires_brand_change', - 'requires url change' => 'requires_url_change', - 'requires format change' => 'requires_format_change', - 'requires cap change' => 'requires_cap_change', - 'paused' => 'paused', - 'format needs coding' => 'format_needs_coding', - // Legacy mappings for backwards compatibility - 'draft' => 'pending', - 'archived' => 'inactive' - ]; - $newStatus = $statusMap[strtolower($sheetsData['Status'] ?? 'active')] ?? 'active'; - - // Update status if it changed - if ($existing['status'] != $newStatus) { - $this->db->query( - "UPDATE advertising_site_groups SET status = ? WHERE id = ?", - [$newStatus, $existing['id']] - ); - $existing['status'] = $newStatus; - } - - // Check if we need to update domains for "all" wildcard - $this->processMuFieldForExistingSiteGroup($existing['id'], $sheetsData); - return $existing; - } - - // Create new site group - $brand = $sheetsData['brand'] ?? 'Unknown'; - $country = $sheetsData['allowed_geos'] ?? $sheetsData['Country'] ?? 'AA'; // Default to AA - - // Take first country if multiple - if (strpos($country, ',') !== false) { - $country = trim(explode(',', $country)[0]); - } - - // Ensure country is 2 chars - $country = strtoupper(substr($country, 0, 2)); - - // Get first domain from mu field for site group name - $firstDomain = $this->getFirstDomainFromMu($sheetsData); - $siteGroupName = $firstDomain ? "{$firstDomain} - {$country}" : "{$brand} - {$country}"; - - // Limit name to 250 characters to avoid database truncation - if (strlen($siteGroupName) > 250) { - $siteGroupName = substr($siteGroupName, 0, 247) . '...'; - } - - // Generate CUID for site group - $cuid = $this->generateCuid(); - - // Get user ID for created_by (from agent assignment or default) - $createdBy = $this->mapAgentToUserId($sheetsData['z'] ?? ''); - - $sql = "INSERT INTO advertising_site_groups ( - cuid, name, description, status, settings, created_by, created_at, alias - ) VALUES (?, ?, ?, ?, ?, ?, NOW(), ?) - ON DUPLICATE KEY UPDATE - name = VALUES(name), - description = VALUES(description), - status = VALUES(status), - settings = VALUES(settings), - alias = VALUES(alias)"; - - // Generate proper alias using SiteGroupAliasService - $aliasService = new \App\Modules\Advertising\Services\SiteGroupAliasService(); - $alias = $aliasService->generateUniqueAlias($createdBy); - - // Map status from Google Sheets (column G) - $customFields = json_decode($sheetsData['custom_fields'] ?? '{}', true) ?: []; - $sheetsStatus = $customFields['Status'] ?? $sheetsData['Status'] ?? 'active'; - - $statusMap = [ - 'active' => 'active', - 'inactive' => 'inactive', - 'pending' => 'pending', - 'in preparation' => 'in_preparation', - 'ready' => 'ready', - 'live' => 'live', - 'to do' => 'to_do', - 'awaiting creatives' => 'awaiting_creatives', - 'created but error' => 'created_but_error', - 'n/a' => 'n_a', - 'to be retired' => 'to_be_retired', - 'retired' => 'retired', - 'requires brand change' => 'requires_brand_change', - 'requires url change' => 'requires_url_change', - 'requires format change' => 'requires_format_change', - 'requires cap change' => 'requires_cap_change', - 'paused' => 'paused', - 'format needs coding' => 'format_needs_coding', - // Legacy mappings for backwards compatibility - 'draft' => 'pending', - 'archived' => 'inactive' - ]; - $status = $statusMap[strtolower($sheetsStatus)] ?? 'active'; - - $params = [ - $cuid, - $siteGroupName, // Name: first domain + country - "Site Group para {$firstDomain} no país {$country}", // Description - $status, // Use status from Google Sheets - json_encode([ - 'google_sheets_sync' => true, - 'analytics_token' => $sheetsData['analytics_token'] ?? null, - 'campaign_slug' => $sheetsData['campaign_slug'] ?? null, - 'brand' => $brand, - 'country' => $country, - 'first_domain' => $firstDomain, - 'script_id' => $sheetsData['script_id'] // Store script_id in settings - ]), - $createdBy, - $alias // Use proper TT-PA-XXX format alias - ]; - - $this->db->query($sql, $params); - $siteGroupId = $this->db->lastInsertId(); - - // Process mu field for new site group - $this->processMuFieldForNewSiteGroup($siteGroupId, $sheetsData); - - return [ - 'id' => $siteGroupId, - 'cuid' => $cuid, - 'name' => "{$brand} - {$country}", - 'alias' => $sheetsData['script_id'], - 'status' => 1 - ]; - - } catch (\Exception $e) { - ErrorReporter::report($e, [ - 'context' => 'create_site_group_from_sheets', - 'script_id' => $sheetsData['script_id'] ?? 'unknown' - ]); - return null; - } - } - - /** - * Process mu field for new site group - handle "all" wildcard - */ - private function processMuFieldForNewSiteGroup(int $siteGroupId, array $sheetsData): void - { - // Extract mu from custom_fields if not directly available - $mu = $sheetsData['mu'] ?? ''; - if (empty($mu) && isset($sheetsData['custom_fields'])) { - $customFields = json_decode($sheetsData['custom_fields'], true); - $mu = $customFields['mu'] ?? ''; - } - - if (empty($mu)) { - return; - } - - // Split by line breaks to get individual domains - $domains = preg_split('/\r?\n/', trim($mu)); - - foreach ($domains as $domain) { - $domain = trim($domain); - if (empty($domain)) { - continue; - } - - // Check if this is "all" wildcard - if (strtoupper($domain) === 'ALL') { - $this->addAllDomainsToSiteGroup($siteGroupId, $sheetsData); - } else { - // Add specific domain - $this->addDomainToSiteGroup($siteGroupId, $domain); - } - } - } - - /** - * Process mu field for existing site group - handle "all" wildcard - */ - private function processMuFieldForExistingSiteGroup(int $siteGroupId, array $sheetsData): void - { - // Extract mu from custom_fields if not directly available - $mu = $sheetsData['mu'] ?? ''; - if (empty($mu) && isset($sheetsData['custom_fields'])) { - $customFields = json_decode($sheetsData['custom_fields'], true); - $mu = $customFields['mu'] ?? ''; - } - - if (empty($mu)) { - return; - } - - // Check if site group already has domains - $existingDomains = $this->db->fetchAll( - "SELECT COUNT(*) as count FROM advertising_site_domains WHERE site_group_id = ? AND deleted_at IS NULL", - [$siteGroupId] - ); - - if ($existingDomains[0]['count'] > 0) { - return; // Already has domains, don't overwrite - } - - // Process mu field for existing site group - $this->processMuFieldForNewSiteGroup($siteGroupId, $sheetsData); - } - - /** - * Add "all" wildcard to site group - */ - private function addAllDomainsToSiteGroup(int $siteGroupId, array $sheetsData): void - { - try { - // Simply add "all" as a wildcard domain - $this->addDomainToSiteGroup($siteGroupId, 'all', true); - - } catch (\Exception $e) { - ErrorReporter::report($e, [ - 'context' => 'add_all_domains_to_site_group', - 'site_group_id' => $siteGroupId - ]); - } - } - - /** - * Add specific domain to site group - */ - private function addDomainToSiteGroup(int $siteGroupId, string $domain, bool $isPrimary = false): void - { - try { - // Don't clean "all" wildcard - if (strtoupper($domain) !== 'ALL') { - // Clean the domain - $domain = preg_replace('/^https?:\/\//', '', $domain); - $domain = preg_replace('/^www\./', '', $domain); - $domain = trim($domain); - } - - if (empty($domain)) { - return; - } - - // Generate CUID for domain - $cuid = substr(md5($siteGroupId . '_' . $domain), 0, 32); - - // Insert domain - $this->db->query(" - INSERT INTO advertising_site_domains (cuid, site_group_id, domain, status, is_primary, created_by, created_at) - VALUES (?, ?, ?, 1, ?, 1, NOW()) - ON DUPLICATE KEY UPDATE domain = domain - ", [ - $cuid, - $siteGroupId, - $domain, - $isPrimary ? 1 : 0 - ]); - - } catch (\Exception $e) { - ErrorReporter::report($e, [ - 'context' => 'add_domain_to_site_group', - 'site_group_id' => $siteGroupId, - 'domain' => $domain - ]); - } - } - - /** - * Check if campaign should be updated based on hash - */ - private function shouldUpdateCampaign(array $existing, array $sheetsData): bool - { - return $existing['google_sheets_hash'] !== $sheetsData['google_sheets_hash']; - } - - /** - * Check if creative should be updated based on hash - */ - private function shouldUpdateCreative(array $existing, array $sheetsData): bool - { - return $existing['rotator_hash'] !== $sheetsData['rotator_hash']; - } - - /** - * Create campaign from Google Sheets data inside a multibook - */ - private function createCampaignFromSheets(array $sheetsData, int $siteGroupId): int - { - // Map to CRM campaign structure - $campaignData = [ - 'name' => $sheetsData['name'], - 'type' => $sheetsData['type'], - 'description' => $sheetsData['description'], - 'status' => $sheetsData['status'], - 'budget' => $sheetsData['budget'], - 'start_date' => $sheetsData['start_date'], - 'end_date' => $sheetsData['end_date'], - 'created_by' => 1, // System user - 'cuid' => $sheetsData['script_id'], // Use script_id directly as cuid - 'site_group_id' => $siteGroupId, // Link to site group - - // Google Sheets specific fields - 'script_id' => $sheetsData['script_id'] ?? '', - 'campaign_code' => $sheetsData['campaign_code'] ?? '', - 'allowed_countries' => $sheetsData['allowed_geos'] ?? $sheetsData['Country'] ?? 'AA', - 'click_mode' => !empty($sheetsData['click_mode']) ? 1 : 0, - 'brand' => $sheetsData['brand'] ?? '', - 'tracker_url' => $sheetsData['tracker'] ?? '', - 'campaign_slug' => $sheetsData['campaign_slug'] ?? '', - 'allow_close' => !empty($sheetsData['allow_close']) ? 1 : 0, - 'analytics_token' => $sheetsData['analytics_token'] ?? '', - 'init_after_element_selector' => $sheetsData['init_after_element_selector'] ?? '', - 'impressions_target' => $sheetsData['impressions_target'] ?? 0, - 'upfront_payment' => $sheetsData['upfront_payment'] ?? 0, - 'duration_days' => $sheetsData['duration_days'] ?? 0, - 'custom_fields' => $sheetsData['custom_fields'] ?? '{}', - 'google_sheets_hash' => $sheetsData['google_sheets_hash'] ?? '', - 'last_sync_at' => $sheetsData['last_sync_at'] ?? null, - ]; - - // Use direct SQL insert to avoid model validation issues in demo mode - $sql = "REPLACE INTO advertising_campaigns ( - cuid, name, type, description, status, budget, start_date, end_date, created_by, site_group_id, - script_id, campaign_code, allowed_countries, click_mode, brand, tracker_url, campaign_slug, - allow_close, analytics_token, init_after_element_selector, impressions_target, - upfront_payment, duration_days, custom_fields, google_sheets_hash, last_sync_at, - created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())"; - - $params = [ - $campaignData['cuid'], - $campaignData['name'], - $campaignData['type'], - $campaignData['description'], - $campaignData['status'], - $campaignData['budget'], - $campaignData['start_date'], - $campaignData['end_date'], - $campaignData['created_by'], - $campaignData['site_group_id'], - $campaignData['script_id'], - $campaignData['campaign_code'], - $campaignData['allowed_countries'], - !empty($campaignData['click_mode']) ? 1 : 0, - $campaignData['brand'], - $campaignData['tracker_url'], - $campaignData['campaign_slug'], - $campaignData['allow_close'] ? 1 : 0, - $campaignData['analytics_token'], - $campaignData['init_after_element_selector'], - $campaignData['impressions_target'], - $campaignData['upfront_payment'], - $campaignData['duration_days'], - $campaignData['custom_fields'], - $campaignData['google_sheets_hash'], - $campaignData['last_sync_at'] - ]; - - $this->db->query($sql, $params); - $campaignId = $this->db->lastInsertId(); - - // Create default trackers for the campaign - $this->createDefaultTrackersForCampaign($campaignId, $sheetsData); - - return $campaignId; - } - - /** - * Create default trackers for a campaign - */ - private function createDefaultTrackersForCampaign(int $campaignId, array $sheetsData): void - { - try { - // Get or create format based on tipo from Google Sheets - $formatId = $this->getOrCreateFormatByType($campaignId, $sheetsData); - - // Get or create brand and landing type - $brandId = $this->getOrCreateBrand($sheetsData['brand'] ?? 'Default Brand'); - $landingTypeId = $this->getOrCreateLandingType($sheetsData['landing'] ?? 'Basic Landing', $brandId); - - // Use tracker template from brand or fallback to Google Sheets data - $trackerUrl = $this->getTrackerTemplateForBrand($brandId, $sheetsData) ?? - $sheetsData['tracker'] ?? - $sheetsData['tracker_url'] ?? - null; - - // If no tracker URL is available, skip creating trackers - if (!$trackerUrl) { - ErrorReporter::report(new \Exception("No tracker URL available for campaign"), [ - 'context' => 'create_default_trackers_for_campaign', - 'campaign_id' => $campaignId, - 'sheets_data' => $sheetsData - ]); - return; - } - - // Create trackers for different tracking types - $trackingTypes = ['view', 'click', 'register']; - - foreach ($trackingTypes as $trackingType) { - $cuid = $this->generateCuid(); - - // Build tracking URL based on type - $finalTrackingUrl = $trackerUrl; - if (strpos($trackerUrl, '?') !== false) { - $finalTrackingUrl .= "&type={$trackingType}"; - } else { - $finalTrackingUrl .= "?type={$trackingType}"; - } - - $sql = "INSERT INTO advertising_trackers ( - cuid, format_id, brand_id, landing_type_id, name, tracking_type, tracking_url, - tracking_params, is_active, created_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW()) - ON DUPLICATE KEY UPDATE - name = VALUES(name), - tracking_type = VALUES(tracking_type), - tracking_url = VALUES(tracking_url), - tracking_params = VALUES(tracking_params), - is_active = VALUES(is_active)"; - - $this->db->query($sql, [ - $cuid, - $formatId, - $brandId, - $landingTypeId, - "Tracker {$trackingType} - {$sheetsData['name']}", - $trackingType, - $finalTrackingUrl, - json_encode([ - 'campaign_id' => $campaignId, - 'script_id' => $sheetsData['script_id'] ?? '', - 'type' => $trackingType, - 'geo' => $sheetsData['allowed_geos'] ?? 'AA', - 'brand' => $sheetsData['brand'] ?? 'Default Brand', - 'landing' => $sheetsData['landing'] ?? 'Basic Landing' - ]), - true - ]); - - $trackerId = $this->db->lastInsertId(); - - // Link tracker to campaign - $this->db->query( - "INSERT INTO advertising_campaign_trackers (campaign_id, tracker_id, order_position) VALUES (?, ?, ?) - ON DUPLICATE KEY UPDATE order_position = VALUES(order_position)", - [$campaignId, $trackerId, array_search($trackingType, $trackingTypes) + 1] - ); - } - - } catch (\Exception $e) { - ErrorReporter::report($e, [ - 'context' => 'create_default_trackers_for_campaign', - 'campaign_id' => $campaignId, - 'sheets_data' => $sheetsData - ]); - } - } - - /** - * Get or create brand - */ - private function getOrCreateBrand(string $brandName): int - { - // Check if brand already exists - $existingBrand = $this->db->fetch( - "SELECT id FROM advertising_brands WHERE name = ? OR slug = ? LIMIT 1", - [$brandName, strtolower(str_replace(' ', '-', $brandName))] - ); - - if ($existingBrand) { - return $existingBrand['id']; - } - - // Create new brand - $cuid = $this->generateCuid(); - $slug = strtolower(str_replace(' ', '-', $brandName)); - - $sql = "INSERT INTO advertising_brands ( - cuid, name, slug, description, is_active, status, created_by, created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW()) - ON DUPLICATE KEY UPDATE - name = VALUES(name), - slug = VALUES(slug), - description = VALUES(description), - is_active = VALUES(is_active), - status = VALUES(status), - updated_at = NOW()"; - - $this->db->query($sql, [ - $cuid, - $brandName, - $slug, - "Brand: {$brandName}", - true, - 1, - 1 - ]); - - return $this->db->lastInsertId(); - } - - /** - * Get or create landing type - */ - private function getOrCreateLandingType(string $landingName, int $brandId): int - { - // Create landing name based on brand - $brandLandingName = $landingName . " - " . $this->getBrandName($brandId); - - // Check if landing type already exists for this brand - $existingBrandLanding = $this->db->fetch( - "SELECT id FROM advertising_brand_landing_types WHERE brand_id = ? AND name = ? LIMIT 1", - [$brandId, $brandLandingName] - ); - - if ($existingBrandLanding) { - return $existingBrandLanding['id']; - } - - // Create new brand landing type - $cuid = $this->generateCuid(); - $slug = strtolower(str_replace(' ', '-', $brandLandingName)); - - $sql = "INSERT INTO advertising_brand_landing_types ( - cuid, brand_id, name, slug, type, template_url, is_active, created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW()) - ON DUPLICATE KEY UPDATE - name = VALUES(name), - slug = VALUES(slug), - type = VALUES(type), - template_url = VALUES(template_url), - is_active = VALUES(is_active), - updated_at = NOW()"; - - $this->db->query($sql, [ - $cuid, - $brandId, - $brandLandingName, - $slug, - 'sales', - null, // Landing URL will be set from actual brand configuration - true - ]); - - return $this->db->lastInsertId(); - } - - /** - * Get brand name by ID - */ - private function getBrandName(int $brandId): string - { - $brand = $this->db->fetch( - "SELECT name FROM advertising_brands WHERE id = ? LIMIT 1", - [$brandId] - ); - - return $brand ? $brand['name'] : 'Unknown Brand'; - } - - /** - * Get tracker template for brand and replace {alias} with actual alias - */ - private function getTrackerTemplateForBrand(int $brandId, array $sheetsData): ?string - { - // Get template from database - $template = $this->db->fetch( - "SELECT template_url, alias_parameter FROM advertising_brand_templates - WHERE brand_id = ? AND type = 'tracker' AND is_active = 1 LIMIT 1", - [$brandId] - ); - - if (!$template) { - return null; - } - - // Get alias from sheets data or generate from script_id - $alias = $sheetsData['script_id'] ?? $this->generateAlias($sheetsData); - - if (!$alias) { - return null; - } - - // Replace {alias} with actual alias - $trackerUrl = str_replace('{alias}', $alias, $template['template_url']); - - return $trackerUrl; - } - - /** - * Generate alias from campaign data - */ - private function generateAlias(array $sheetsData): ?string - { - // Try to extract alias from existing tracker URL - if (!empty($sheetsData['tracker'])) { - $patterns = [ - '/[?&]c=([^&]+)/', // c=alias - '/[?&]alias=([^&]+)/', // alias=value - '/[?&]ref=([^&]+)/', // ref=value - '/[?&]aid=([^&]+)/', // aid=value - '/[?&]campaign=([^&]+)/', // campaign=value - '/[?&]pid=([^&]+)/', // pid=value - '/[?&]tracker=([^&]+)/', // tracker=value - '/[?&]code=([^&]+)/', // code=value - ]; - - foreach ($patterns as $pattern) { - if (preg_match($pattern, $sheetsData['tracker'], $matches)) { - return $matches[1]; - } - } - } - - // Use script_id as fallback - return $sheetsData['script_id'] ?? null; - } - - /** - * Get or create format based on tipo from Google Sheets - */ - private function getOrCreateFormatByType(int $campaignId, array $sheetsData): int - { - // Get type from Google Sheets data or campaign data - $tipo = $sheetsData['tipo'] ?? $sheetsData['type'] ?? 'banner'; - - // Map Google Sheets types to format names from Config sheet - $formatMap = [ - 'overlay' => 'Interstitial', - 'interstitial' => 'Interstitial', - 'sticky' => 'Sticky Bottom Banner', - 'scrollable' => 'Scrollable Top Banner', - 'cube' => 'Cube', - '320x50' => '320x50', - '320x100' => '320x100', - '800x600' => '800x600', - '300x600' => '300x600', - 'multibook' => 'Multibook', - 'banner' => 'Sticky Bottom Banner' // default - ]; - - $formatName = $formatMap[strtolower($tipo)] ?? 'Sticky Bottom Banner'; - - // Try to find existing format by name (global, not campaign-specific) - $existingFormat = $this->db->fetch( - "SELECT id FROM advertising_formats WHERE name = ? AND is_active = 1 LIMIT 1", - [$formatName] - ); - - if ($existingFormat) { - return $existingFormat['id']; - } - - // If format doesn't exist, create a default one - $cuid = $this->generateCuid(); - - // Get default dimensions based on format name - $dimensions = $this->getDefaultDimensions($formatName); - - $sql = "INSERT INTO advertising_formats ( - cuid, campaign_id, name, width, height, format_type, pub_type, - html_template, css_styles, js_code, is_active, weight, created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW()) - ON DUPLICATE KEY UPDATE - name = VALUES(name), - width = VALUES(width), - height = VALUES(height), - format_type = VALUES(format_type), - pub_type = VALUES(pub_type), - html_template = VALUES(html_template), - css_styles = VALUES(css_styles), - js_code = VALUES(js_code), - is_active = VALUES(is_active), - weight = VALUES(weight), - updated_at = NOW()"; - - $this->db->query($sql, [ - $cuid, - $campaignId, - $formatName, - $dimensions['width'], - $dimensions['height'], - $dimensions['format_type'], - $dimensions['pub_type'], - $this->getDefaultHtmlTemplate($formatName), - $this->getDefaultCssStyles($formatName), - $this->getDefaultJsCode($formatName), - true, - 1 - ]); - - return $this->db->lastInsertId(); - } - - /** - * Get default dimensions for format type - */ - private function getDefaultDimensions(string $formatName): array - { - $dimensions = [ - // Format names from Config sheet - 'Sticky Bottom Banner' => ['width' => 728, 'height' => 90, 'format_type' => 'banner', 'pub_type' => 'banner'], - 'Scrollable Top Banner' => ['width' => 728, 'height' => 90, 'format_type' => 'banner', 'pub_type' => 'banner'], - 'Interstitial' => ['width' => 800, 'height' => 600, 'format_type' => 'popup', 'pub_type' => 'interstitial'], - 'Cube' => ['width' => 300, 'height' => 250, 'format_type' => 'banner', 'pub_type' => 'banner'], - '320x50' => ['width' => 320, 'height' => 50, 'format_type' => 'banner', 'pub_type' => 'banner'], - '320x100' => ['width' => 320, 'height' => 100, 'format_type' => 'banner', 'pub_type' => 'banner'], - '800x600' => ['width' => 800, 'height' => 600, 'format_type' => 'banner', 'pub_type' => 'banner'], - '300x600' => ['width' => 300, 'height' => 600, 'format_type' => 'banner', 'pub_type' => 'banner'], - 'Multibook' => ['width' => 728, 'height' => 90, 'format_type' => 'banner', 'pub_type' => 'banner'], - - // Legacy format types - 'banner' => ['width' => 728, 'height' => 90, 'format_type' => 'banner', 'pub_type' => 'banner'], - 'popup' => ['width' => 800, 'height' => 600, 'format_type' => 'popup', 'pub_type' => 'interstitial'], - 'native' => ['width' => 728, 'height' => 90, 'format_type' => 'native', 'pub_type' => 'native'], - 'video' => ['width' => 640, 'height' => 360, 'format_type' => 'video', 'pub_type' => 'video'] - ]; - - return $dimensions[$formatName] ?? $dimensions['Sticky Bottom Banner']; - } - - /** - * Get default HTML template for format type - */ - private function getDefaultHtmlTemplate(string $formatType): string - { - $templates = [ - 'banner' => '
Banner Content
', - 'popup' => '
Popup Content
', - 'native' => '
Native Content
', - 'video' => '
Video Content
' - ]; - - return $templates[$formatType] ?? $templates['banner']; - } - - /** - * Get default CSS styles for format type - */ - private function getDefaultCssStyles(string $formatType): string - { - $styles = [ - 'banner' => '.ad-banner { width: 728px; height: 90px; }', - 'popup' => '.ad-popup { width: 300px; height: 250px; }', - 'native' => '.ad-native { width: 300px; height: 250px; }', - 'video' => '.ad-video { width: 640px; height: 360px; }' - ]; - - return $styles[$formatType] ?? $styles['banner']; - } - - /** - * Get default JS code for format type - */ - private function getDefaultJsCode(string $formatType): string - { - $code = [ - 'banner' => 'console.log("Banner loaded");', - 'popup' => 'console.log("Popup loaded");', - 'native' => 'console.log("Native ad loaded");', - 'video' => 'console.log("Video ad loaded");' - ]; - - return $code[$formatType] ?? $code['banner']; - } - - /** - * Get or create default format for a campaign (legacy method) - */ - private function getOrCreateDefaultFormat(int $campaignId, array $sheetsData): int - { - // Check if campaign already has formats - $existingFormat = $this->db->fetch( - "SELECT id FROM advertising_formats WHERE campaign_id = ? LIMIT 1", - [$campaignId] - ); - - if ($existingFormat) { - return $existingFormat['id']; - } - - // Create default format - $cuid = $this->generateCuid(); - $sql = "INSERT INTO advertising_formats ( - cuid, campaign_id, name, width, height, format_type, - html_template, css_styles, js_code, is_active, weight, created_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())"; - - $this->db->query($sql, [ - $cuid, - $campaignId, - 'Default Banner Format', - 728, - 90, - 'banner', - '
Banner Content
', - '.ad-banner { width: 728px; height: 90px; }', - 'console.log("Banner loaded");', - true, - 1 - ]); - - return $this->db->lastInsertId(); - } - - /** - * Update campaign from Google Sheets data - */ - private function updateCampaignFromSheets(int $campaignId, array $sheetsData, int $siteGroupId): bool - { - $updateData = [ - 'name' => $sheetsData['name'], - 'type' => $sheetsData['type'], - 'description' => $sheetsData['description'], - 'status' => $sheetsData['status'], - 'budget' => $sheetsData['budget'], - 'start_date' => $sheetsData['start_date'], - 'end_date' => $sheetsData['end_date'], - - // Google Sheets specific fields - 'campaign_code' => $sheetsData['campaign_code'] ?? '', - 'allowed_countries' => $sheetsData['allowed_geos'] ?? $sheetsData['Country'] ?? 'AA', - 'click_mode' => !empty($sheetsData['click_mode']) ? 1 : 0, - 'brand' => $sheetsData['brand'] ?? '', - 'campaign_slug' => $sheetsData['campaign_slug'] ?? '', - 'allow_close' => !empty($sheetsData['allow_close']) ? 1 : 0, - 'analytics_token' => $sheetsData['analytics_token'] ?? '', - 'init_after_element_selector' => $sheetsData['init_after_element_selector'] ?? '', - 'impressions_target' => $sheetsData['impressions_target'] ?? 0, - 'upfront_payment' => $sheetsData['upfront_payment'] ?? 0, - 'duration_days' => $sheetsData['duration_days'] ?? 0, - 'custom_fields' => $sheetsData['custom_fields'] ?? '{}', - 'google_sheets_hash' => $sheetsData['google_sheets_hash'] ?? '', - 'last_sync_at' => $sheetsData['last_sync_at'] ?? null, - ]; - - return $this->campaignModel->update($campaignId, $updateData); - } - - /** - * Create creative from Google Sheets data - */ - private function createCreativeFromSheets(array $sheetsData): int - { - // Find related campaign - $campaign = $this->findCampaignByScriptId($sheetsData['script_id']); - $campaignId = $campaign ? $campaign['id'] : null; - - $creativeData = [ - 'cuid' => $this->generateCuid(), // Generate proper CUID - 'format_id' => null, // No format required for now - 'name' => $sheetsData['name'], - 'file_name' => $sheetsData['creative_slug'] . '.html', - 'file_path' => '/creatives/' . $sheetsData['creative_slug'] . '.html', - 'file_size' => 1024, // Default size - 'mime_type' => 'text/html', - 'width' => 300, - 'height' => 250, - 'alt_text' => $sheetsData['description'], - 'is_active' => 1, - 'description' => $sheetsData['description'], - - // Google Sheets specific fields - 'script_id' => $sheetsData['script_id'], - 'creative_slug' => $sheetsData['creative_slug'], - 'target_country' => substr($sheetsData['geo'] ?? '', 0, 10), // Truncate geo field - 'click_mode_override' => $sheetsData['click_mode_override'], - 'view_url' => $sheetsData['view_url'], - 'creative_type' => 'rotator', // All creatives from rotator tab are 'rotator' type - 'rotator_hash' => $sheetsData['rotator_hash'], - 'last_sync_at' => $sheetsData['last_sync_at'], - ]; - - // Use direct SQL insert to avoid model validation issues in demo mode - $sql = "INSERT INTO advertising_creatives ( - cuid, format_id, name, file_name, file_path, file_size, mime_type, width, height, - alt_text, is_active, description, script_id, creative_slug, target_country, click_mode_override, - view_url, creative_type, rotator_hash, last_sync_at, created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW()) - ON DUPLICATE KEY UPDATE - name = VALUES(name), - file_name = VALUES(file_name), - file_path = VALUES(file_path), - file_size = VALUES(file_size), - mime_type = VALUES(mime_type), - width = VALUES(width), - height = VALUES(height), - alt_text = VALUES(alt_text), - is_active = VALUES(is_active), - description = VALUES(description), - script_id = VALUES(script_id), - creative_slug = VALUES(creative_slug), - target_country = VALUES(target_country), - click_mode_override = VALUES(click_mode_override), - view_url = VALUES(view_url), - creative_type = VALUES(creative_type), - rotator_hash = VALUES(rotator_hash), - last_sync_at = VALUES(last_sync_at), - updated_at = NOW()"; - - $params = [ - $creativeData['cuid'], - $creativeData['format_id'], - $creativeData['name'], - $creativeData['file_name'], - $creativeData['file_path'], - $creativeData['file_size'], - $creativeData['mime_type'], - $creativeData['width'], - $creativeData['height'], - $creativeData['alt_text'], - $creativeData['is_active'], - $creativeData['description'], - $creativeData['script_id'], - $creativeData['creative_slug'], - $creativeData['target_country'], - $creativeData['click_mode_override'] !== null ? ($creativeData['click_mode_override'] ? 1 : 0) : null, - $creativeData['view_url'], - $creativeData['creative_type'], - $creativeData['rotator_hash'], - $creativeData['last_sync_at'] - ]; - - // Insert creative data - - $this->db->query($sql, $params); - return $this->db->lastInsertId(); - } - - /** - * Update creative from Google Sheets data - */ - private function updateCreativeFromSheets(int $creativeId, array $sheetsData): bool - { - // Find related campaign - $campaign = $this->findCampaignByScriptId($sheetsData['script_id']); - $campaignId = $campaign ? $campaign['id'] : null; - - $updateData = [ - 'campaign_id' => $campaignId, - 'name' => $sheetsData['name'], - 'description' => $sheetsData['description'], - - // Google Sheets specific fields - 'geo' => $sheetsData['geo'], - 'click_mode_override' => $sheetsData['click_mode_override'], - 'view_url' => $sheetsData['view_url'], - 'creative_type' => $sheetsData['creative_type'], - 'rotator_hash' => $sheetsData['rotator_hash'], - 'last_sync_at' => $sheetsData['last_sync_at'], - ]; - - return $this->creativeModel->update($creativeId, $updateData); - } - - /** - * Generate trackers.json for script-builder compatibility - */ - private function generateTrackersJson(): void - { - try { - // Get all campaigns and creatives from CRM - $campaigns = $this->db->fetchAll( - "SELECT * FROM advertising_campaigns WHERE script_id IS NOT NULL AND deleted_at IS NULL" - ); - - $creatives = $this->db->fetchAll( - "SELECT * FROM advertising_creatives WHERE script_id IS NOT NULL AND deleted_at IS NULL" - ); - - // Build trackers.json structure (compatible with script-builder) - $trackers = []; - - foreach ($campaigns as $campaign) { - $trackers[$campaign['script_id']] = [ - 'script_id' => $campaign['script_id'] ?? '', - 'campaign_slug' => $campaign['campaign_slug'] ?? '', - 'name' => $campaign['name'] ?? '', - 'status' => $campaign['status'] ?? 'active', - 'click_mode' => (bool)($campaign['click_mode'] ?? false), - 'allowed_geos' => $campaign['allowed_geos'] ?? 'AA', - 'brand' => $campaign['brand'] ?? '', - 'analytics_token' => $campaign['analytics_token'] ?? '', - 'custom_fields' => json_decode($campaign['custom_fields'] ?? '{}', true), - 'last_sync' => $campaign['last_sync_at'] ?? null, - ]; - - // Add related creatives - $campaignCreatives = array_filter($creatives, function($creative) use ($campaign) { - return $creative['script_id'] === $campaign['script_id']; - }); - - $trackers[$campaign['script_id']]['creatives'] = array_map(function($creative) { - return [ - 'slug' => $creative['creative_slug'] ?? '', - 'geo' => $creative['geo'] ?? 'AA', - 'url' => $creative['view_url'] ?? '', - 'type' => $creative['creative_type'] ?? 'banner', - ]; - }, $campaignCreatives); - } - - // Save to file (script-builder compatible location) - $trackersPath = realpath(__DIR__ . '/../../../../projects/script-builder/') . '/trackers.json'; - $trackersJson = json_encode($trackers, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); - - if (!file_put_contents($trackersPath, $trackersJson)) { - throw new \Exception("Failed to write trackers.json to: $trackersPath"); - } - - // Update version in database for sync control - $version = md5($trackersJson); - $this->db->query( - "INSERT INTO advertising_sync_versions (type, version, updated_at) VALUES (?, ?, NOW()) - ON DUPLICATE KEY UPDATE version = VALUES(version), updated_at = VALUES(updated_at)", - ['trackers_json', $version] - ); - - } catch (\Exception $e) { - ErrorReporter::report($e, [ - 'context' => 'generate_trackers_json' - ]); - throw $e; - } - } - - /** - * Get synchronization statistics - */ - public function getSyncStats(): array - { - try { - $stats = [ - 'campaigns' => [ - 'total' => 0, - 'synced' => 0, - 'last_sync' => null, - ], - 'creatives' => [ - 'total' => 0, - 'synced' => 0, - 'last_sync' => null, - ], - 'google_sheets_available' => $this->googleSheetsService->isAvailable(), - ]; - - // Campaign stats - $campaignStats = $this->db->fetch( - "SELECT - COUNT(*) as total, - COUNT(script_id) as synced, - MAX(last_sync_at) as last_sync - FROM advertising_campaigns - WHERE deleted_at IS NULL" - ); - - $stats['campaigns'] = [ - 'total' => (int)$campaignStats['total'], - 'synced' => (int)$campaignStats['synced'], - 'last_sync' => $campaignStats['last_sync'], - ]; - - // Creative stats - $creativeStats = $this->db->fetch( - "SELECT - COUNT(*) as total, - COUNT(script_id) as synced, - MAX(last_sync_at) as last_sync - FROM advertising_creatives - WHERE deleted_at IS NULL" - ); - - $stats['creatives'] = [ - 'total' => (int)$creativeStats['total'], - 'synced' => (int)$creativeStats['synced'], - 'last_sync' => $creativeStats['last_sync'], - ]; - - return $stats; - - } catch (\Exception $e) { - ErrorReporter::report($e, ['context' => 'get_sync_stats']); - return [ - 'error' => $e->getMessage(), - 'google_sheets_available' => false, - ]; - } - } - - /** - * Create missing trackers for campaigns that don't have any - */ - public function createMissingTrackersForCampaigns(): array - { - $results = ['created' => 0, 'errors' => []]; - - try { - // Get campaigns without trackers - $campaignsWithoutTrackers = $this->db->fetchAll( - "SELECT c.* FROM advertising_campaigns c - LEFT JOIN advertising_campaign_trackers ct ON c.id = ct.campaign_id - WHERE c.deleted_at IS NULL AND ct.tracker_id IS NULL" - ); - - foreach ($campaignsWithoutTrackers as $campaign) { - try { - // Create default trackers for this campaign - $this->createDefaultTrackersForCampaign($campaign['id'], [ - 'name' => $campaign['name'], - 'script_id' => $campaign['script_id'] ?? '', - 'allowed_geos' => $campaign['allowed_geos'] ?? 'AA', - 'brand' => $campaign['brand'] ?? 'Default Brand', - 'landing' => 'Basic Landing', // Default landing type for existing campaigns - 'type' => $campaign['type'] ?? 'banner', // Use existing campaign type - 'tracker_url' => $campaign['tracker_url'] ?? null // Use existing tracker URL or null if not available - ]); - - $results['created']++; - - } catch (\Exception $e) { - $results['errors'][] = "Campaign {$campaign['id']}: " . $e->getMessage(); - ErrorReporter::report($e, [ - 'context' => 'create_missing_trackers_for_campaign', - 'campaign_id' => $campaign['id'] - ]); - } - } - - return $results; - - } catch (\Exception $e) { - ErrorReporter::report($e, ['context' => 'create_missing_trackers_for_campaigns']); - throw $e; - } - } - - /** - * Generate CUID for new records - */ - private function generateCuid(): string - { - return (string) new Cuid2(); - } - - /** - * Map agent name from Google Sheets to user ID - */ - private function mapAgentToUserId(string $agentName): int - { - if (empty($agentName)) { - return 1; // Default fallback user - } - - try { - // Map common agent name variations to database names - $nameMapping = [ - 'Eduardo Terrivel' => 'Eduardo Terrivel', - 'Eduardo' => 'Eduardo Terrivel', - 'ET' => 'Eduardo Terrivel', - 'eduardo.terrivel' => 'Eduardo Terrivel', - 'Alexandre Broadley' => 'Alexandre Broadley', - 'Alexandre' => 'Alexandre Broadley', - 'AB' => 'Alexandre Broadley', - 'alexandre.broadley' => 'Alexandre Broadley', - 'Pedro Alves' => 'Pedro Alves', - 'Pedro' => 'Pedro Alves', - 'PA' => 'Pedro Alves', - ]; - - $searchName = $nameMapping[$agentName] ?? $agentName; - - // Try to find user by full name - $user = $this->db->fetch( - "SELECT id FROM users WHERE name = ? AND is_active = 1 LIMIT 1", - [$searchName] - ); - - if ($user) { - return (int)$user['id']; - } - - // Try to find by first name - $firstName = explode(' ', $searchName)[0]; - $user = $this->db->fetch( - "SELECT id FROM users WHERE first_name = ? AND is_active = 1 LIMIT 1", - [$firstName] - ); - - if ($user) { - return (int)$user['id']; - } - - // Try to find by user alias - $user = $this->db->fetch( - "SELECT id FROM users WHERE user_alias = ? AND is_active = 1 LIMIT 1", - [$agentName] - ); - - if ($user) { - return (int)$user['id']; - } - - return 1; // Default fallback user - - } catch (\Exception $e) { - ErrorReporter::report($e, [ - 'context' => 'agent_mapping_error', - 'agent_name' => $agentName - ]); - return 1; // Default fallback user - } - } - - /** - * Get first domain from mu field for site group naming - */ - private function getFirstDomainFromMu(array $sheetsData): ?string - { - // Extract mu from custom_fields if not directly available - $mu = $sheetsData['mu'] ?? ''; - if (empty($mu) && isset($sheetsData['custom_fields'])) { - $customFields = json_decode($sheetsData['custom_fields'], true); - $mu = $customFields['mu'] ?? ''; - } - - if (empty($mu)) { - return null; - } - - // Split by comma, newline, semicolon, or any whitespace sequence and get first domain - $domains = array_map('trim', preg_split('/[,\n\r\n;]+/', $mu)); - $domains = array_filter($domains); // Remove empty entries - $firstDomain = $domains[0] ?? null; - - // Skip "all" wildcard, get next domain - if ($firstDomain === 'all' && count($domains) > 1) { - $firstDomain = $domains[1] ?? null; - } - - return $firstDomain; - } -} \ No newline at end of file diff --git a/crm/Modules/Advertising/Services/ScriptBuilderService.php b/crm/Modules/Advertising/Services/ScriptBuilderService.php deleted file mode 100644 index d88bda0..0000000 --- a/crm/Modules/Advertising/Services/ScriptBuilderService.php +++ /dev/null @@ -1,752 +0,0 @@ -db = DatabaseManager::getInstance(); - $this->brandDetectionService = new BrandDetectionService(); - $this->outputPath = __DIR__ . '/../../../public/scripts/'; - $this->templatePath = __DIR__ . '/../Templates/'; - - // Criar diretório se não existir - if (!is_dir($this->outputPath)) { - mkdir($this->outputPath, 0755, true); - } - } - - /** - * Gerar script para uma campanha - */ - public function generateScript(int $campaignId): array - { - try { - // Obter dados da campanha - $campaign = $this->getCampaignData($campaignId); - if (!$campaign) { - throw new \Exception('Campanha não encontrada'); - } - - // Obter formatos da campanha - $formats = $this->getFormatsData($campaignId); - if (empty($formats)) { - throw new \Exception('Nenhum formato encontrado para a campanha'); - } - - // Obter trackers - $trackers = $this->getTrackersData($campaignId); - - // Obter criativos - $creatives = $this->getCreativesData($campaignId); - - // Gerar script baseado no tipo de campanha - $script = $this->buildScript($campaign, $formats, $trackers, $creatives); - - // Gerar hash do script - $scriptHash = md5($script); - - // Salvar script na base de dados - $scriptId = $this->saveScript($campaignId, $script, $scriptHash); - - // Salvar ficheiro - $fileName = $this->saveScriptFile($scriptId, $script); - - return [ - 'success' => true, - 'script_id' => $scriptId, - 'script_hash' => $scriptHash, - 'file_name' => $fileName, - 'script_preview' => substr($script, 0, 500) . '...' - ]; - - } catch (\Exception $e) { - error_log("Erro ao gerar script: " . $e->getMessage()); - return [ - 'success' => false, - 'error' => $e->getMessage() - ]; - } - } - - /** - * Gerar script com deteção configurável de marca - */ - public function generateScriptWithBrandDetection(int $campaignId): array - { - try { - // Obter dados da campanha - $campaign = $this->getCampaignData($campaignId); - if (!$campaign) { - throw new \Exception('Campanha não encontrada'); - } - - // Obter formatos da campanha - $formats = $this->getFormatsData($campaignId); - if (empty($formats)) { - throw new \Exception('Nenhum formato encontrado para a campanha'); - } - - // Obter trackers - $trackers = $this->getTrackersData($campaignId); - - // Obter criativos - $creatives = $this->getCreativesData($campaignId); - - // Gerar script com deteção configurável - $script = $this->buildScriptWithBrandDetection($campaign, $formats, $trackers, $creatives); - - // Gerar hash do script - $scriptHash = md5($script); - - // Salvar script na base de dados - $scriptId = $this->saveScript($campaignId, $script, $scriptHash); - - // Salvar ficheiro - $fileName = $this->saveScriptFile($scriptId, $script); - - return [ - 'success' => true, - 'script_id' => $scriptId, - 'script_hash' => $scriptHash, - 'file_name' => $fileName, - 'script_preview' => substr($script, 0, 500) . '...' - ]; - - } catch (\Exception $e) { - error_log("Erro ao gerar script com deteção: " . $e->getMessage()); - return [ - 'success' => false, - 'error' => $e->getMessage() - ]; - } - } - - /** - * Obter dados da campanha - */ - private function getCampaignData(int $campaignId): ?array - { - $sql = "SELECT * FROM advertising_campaigns WHERE id = :id AND deleted_at IS NULL"; - return $this->db->fetch($sql, [':id' => $campaignId]); - } - - /** - * Obter dados dos formatos - */ - private function getFormatsData(int $campaignId): array - { - $sql = "SELECT * FROM advertising_formats WHERE campaign_id = :campaign_id AND is_active = 1 ORDER BY weight DESC"; - return $this->db->fetchAll($sql, [':campaign_id' => $campaignId]) ?: []; - } - - /** - * Obter dados dos trackers - */ - private function getTrackersData(int $campaignId): array - { - $sql = "SELECT t.* FROM advertising_trackers t - JOIN advertising_formats f ON t.format_id = f.id - WHERE f.campaign_id = :campaign_id AND t.is_active = 1"; - return $this->db->fetchAll($sql, [':campaign_id' => $campaignId]) ?: []; - } - - /** - * Obter dados dos criativos - */ - private function getCreativesData(int $campaignId): array - { - $sql = "SELECT cr.* FROM advertising_creatives cr - JOIN advertising_formats f ON cr.format_id = f.id - WHERE f.campaign_id = :campaign_id AND cr.is_active = 1"; - return $this->db->fetchAll($sql, [':campaign_id' => $campaignId]) ?: []; - } - - /** - * Construir script baseado no tipo de campanha - */ - private function buildScript(array $campaign, array $formats, array $trackers, array $creatives): string - { - $scriptType = $campaign['type']; - - switch ($scriptType) { - case 'banner': - return $this->buildBannerScript($campaign, $formats, $trackers, $creatives); - case 'popup': - return $this->buildPopupScript($campaign, $formats, $trackers, $creatives); - case 'native': - return $this->buildNativeScript($campaign, $formats, $trackers, $creatives); - default: - return $this->buildBannerScript($campaign, $formats, $trackers, $creatives); - } - } - - /** - * Construir script com deteção configurável de marca - */ - private function buildScriptWithBrandDetection(array $campaign, array $formats, array $trackers, array $creatives): string - { - $scriptType = $campaign['type']; - - switch ($scriptType) { - case 'banner': - return $this->buildBannerScriptWithBrandDetection($campaign, $formats, $trackers, $creatives); - case 'popup': - return $this->buildPopupScriptWithBrandDetection($campaign, $formats, $trackers, $creatives); - case 'native': - return $this->buildNativeScriptWithBrandDetection($campaign, $formats, $trackers, $creatives); - default: - return $this->buildBannerScriptWithBrandDetection($campaign, $formats, $trackers, $creatives); - } - } - - /** - * Construir script de banner - */ - private function buildBannerScript(array $campaign, array $formats, array $trackers, array $creatives): string - { - $script = "// BetZoo Advertising Script - {$campaign['name']}\n"; - $script .= "// Generated: " . date('Y-m-d H:i:s') . "\n\n"; - - $script .= "(function() {\n"; - $script .= " 'use strict';\n\n"; - - // Configurações - $script .= " const config = {\n"; - $script .= " campaignId: {$campaign['id']},\n"; - $script .= " campaignName: '{$campaign['name']}',\n"; - $script .= " trackingUrl: '" . $this->getTrackingUrl() . "',\n"; - $script .= " formats: " . json_encode($formats) . ",\n"; - $script .= " trackers: " . json_encode($trackers) . ",\n"; - $script .= " creatives: " . json_encode($creatives) . "\n"; - $script .= " };\n\n"; - - // Função de tracking - $script .= " function trackEvent(eventType, data) {\n"; - $script .= " const trackingData = {\n"; - $script .= " event_type: eventType,\n"; - $script .= " campaign_id: config.campaignId,\n"; - $script .= " session_id: getSessionId(),\n"; - $script .= " timestamp: Date.now(),\n"; - $script .= " ...data\n"; - $script .= " };\n\n"; - - $script .= " fetch(config.trackingUrl + '/api/advertising/tracking/' + eventType, {\n"; - $script .= " method: 'POST',\n"; - $script .= " headers: { 'Content-Type': 'application/json' },\n"; - $script .= " body: JSON.stringify(trackingData)\n"; - $script .= " }).catch(console.error);\n"; - $script .= " }\n\n"; - - // Função para obter session ID - $script .= " function getSessionId() {\n"; - $script .= " let sessionId = localStorage.getItem('betzoo_session_id');\n"; - $script .= " if (!sessionId) {\n"; - $script .= " sessionId = 'sess_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);\n"; - $script .= " localStorage.setItem('betzoo_session_id', sessionId);\n"; - $script .= " }\n"; - $script .= " return sessionId;\n"; - $script .= " }\n\n"; - - // Função para criar banner - $script .= " function createBanner() {\n"; - $script .= " const banner = document.createElement('div');\n"; - $script .= " banner.id = 'betzoo-banner-{$campaign['id']}';\n"; - $script .= " banner.style.cssText = 'position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 9999; background: rgba(0,0,0,0.8); display: flex; align-items: center; justify-content: center;';\n\n"; - - $script .= " const content = document.createElement('div');\n"; - $script .= " content.style.cssText = 'background: white; padding: 20px; border-radius: 8px; max-width: 90%; max-height: 90%; overflow: auto;';\n\n"; - - // Adicionar criativo - if (!empty($creatives)) { - $creative = $creatives[0]; - $script .= " const img = document.createElement('img');\n"; - $script .= " img.src = '{$creative['cdn_url']}';\n"; - $script .= " img.alt = '{$creative['alt_text']}';\n"; - $script .= " img.style.cssText = 'max-width: 100%; height: auto; cursor: pointer;';\n"; - $script .= " img.onclick = function() {\n"; - $script .= " trackEvent('click', { creative_id: {$creative['id']} });\n"; - $script .= " if ('{$creative['click_url']}') {\n"; - $script .= " window.open('{$creative['click_url']}', '_blank');\n"; - $script .= " }\n"; - $script .= " };\n"; - $script .= " content.appendChild(img);\n\n"; - } - - // Botão de fechar - $script .= " const closeBtn = document.createElement('button');\n"; - $script .= " closeBtn.textContent = '×';\n"; - $script .= " closeBtn.style.cssText = 'position: absolute; top: 10px; right: 10px; background: none; border: none; font-size: 24px; cursor: pointer; color: #666;';\n"; - $script .= " closeBtn.onclick = function() {\n"; - $script .= " document.body.removeChild(banner);\n"; - $script .= " };\n"; - $script .= " content.appendChild(closeBtn);\n\n"; - - $script .= " banner.appendChild(content);\n"; - $script .= " document.body.appendChild(banner);\n\n"; - - // Track view - if (!empty($trackers)) { - $tracker = $trackers[0]; - $script .= " trackEvent('view', { tracker_id: {$tracker['id']}, creative_id: " . ($creatives[0]['id'] ?? 0) . " });\n"; - } - - $script .= " }\n\n"; - - // Auto-executar - $script .= " // Auto-executar após carregamento\n"; - $script .= " if (document.readyState === 'loading') {\n"; - $script .= " document.addEventListener('DOMContentLoaded', createBanner);\n"; - $script .= " } else {\n"; - $script .= " createBanner();\n"; - $script .= " }\n"; - - $script .= "})();\n"; - - return $script; - } - - /** - * Construir script de banner com deteção configurável de marca - */ - private function buildBannerScriptWithBrandDetection(array $campaign, array $formats, array $trackers, array $creatives): string - { - $script = "// BetZoo Advertising Script with Configurable Brand Detection - {$campaign['name']}\n"; - $script .= "// Generated: " . date('Y-m-d H:i:s') . "\n\n"; - - $script .= "(function() {\n"; - $script .= " 'use strict';\n\n"; - - // Configurações - $script .= " const config = {\n"; - $script .= " campaignId: {$campaign['id']},\n"; - $script .= " campaignName: '{$campaign['name']}',\n"; - $script .= " trackingUrl: '" . $this->getTrackingUrl() . "',\n"; - $script .= " formats: " . json_encode($formats) . ",\n"; - $script .= " trackers: " . json_encode($trackers) . ",\n"; - $script .= " creatives: " . json_encode($creatives) . "\n"; - $script .= " };\n\n"; - - // Função de deteção configurável de marca - $script .= " async function detectBrandFromUrl(url) {\n"; - $script .= " try {\n"; - $script .= " const response = await fetch('" . $this->getTrackingUrl() . "/api/advertising/detection-rules/detect', {\n"; - $script .= " method: 'POST',\n"; - $script .= " headers: { 'Content-Type': 'application/json' },\n"; - $script .= " body: JSON.stringify({ url: url })\n"; - $script .= " });\n"; - $script .= " const result = await response.json();\n"; - $script .= " return result.success ? result.data : null;\n"; - $script .= " } catch (error) {\n"; - $script .= " console.error('Erro na deteção de marca:', error);\n"; - $script .= " return null;\n"; - $script .= " }\n"; - $script .= " }\n\n"; - - // Função de tracking com deteção de marca - $script .= " async function trackEventWithBrandDetection(eventType, data) {\n"; - $script .= " const currentUrl = window.location.href;\n"; - $script .= " const brandDetection = await detectBrandFromUrl(currentUrl);\n"; - $script .= " \n"; - $script .= " const trackingData = {\n"; - $script .= " event_type: eventType,\n"; - $script .= " campaign_id: config.campaignId,\n"; - $script .= " session_id: getSessionId(),\n"; - $script .= " timestamp: Date.now(),\n"; - $script .= " current_url: currentUrl,\n"; - $script .= " brand_detection: brandDetection,\n"; - $script .= " ...data\n"; - $script .= " };\n\n"; - - $script .= " fetch(config.trackingUrl + '/api/advertising/tracking/' + eventType, {\n"; - $script .= " method: 'POST',\n"; - $script .= " headers: { 'Content-Type': 'application/json' },\n"; - $script .= " body: JSON.stringify(trackingData)\n"; - $script .= " }).catch(console.error);\n"; - $script .= " \n"; - $script .= " // Log deteção de marca para debug\n"; - $script .= " if (brandDetection) {\n"; - $script .= " console.log('Marca detectada:', brandDetection);\n"; - $script .= " }\n"; - $script .= " }\n\n"; - - // Função de tracking (mantida para compatibilidade) - $script .= " function trackEvent(eventType, data) {\n"; - $script .= " trackEventWithBrandDetection(eventType, data);\n"; - $script .= " }\n\n"; - - // Função para obter session ID - $script .= " function getSessionId() {\n"; - $script .= " let sessionId = localStorage.getItem('betzoo_session_id');\n"; - $script .= " if (!sessionId) {\n"; - $script .= " sessionId = 'sess_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);\n"; - $script .= " localStorage.setItem('betzoo_session_id', sessionId);\n"; - $script .= " }\n"; - $script .= " return sessionId;\n"; - $script .= " }\n\n"; - - // Função para criar banner - $script .= " function createBanner() {\n"; - $script .= " const banner = document.createElement('div');\n"; - $script .= " banner.id = 'betzoo-banner-{$campaign['id']}';\n"; - $script .= " banner.style.cssText = 'position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 9999; background: rgba(0,0,0,0.8); display: flex; align-items: center; justify-content: center;';\n\n"; - - $script .= " const content = document.createElement('div');\n"; - $script .= " content.style.cssText = 'background: white; padding: 20px; border-radius: 8px; max-width: 90%; max-height: 90%; overflow: auto;';\n\n"; - - // Adicionar criativo - if (!empty($creatives)) { - $creative = $creatives[0]; - $script .= " const img = document.createElement('img');\n"; - $script .= " img.src = '{$creative['cdn_url']}';\n"; - $script .= " img.alt = '{$creative['alt_text']}';\n"; - $script .= " img.style.cssText = 'max-width: 100%; height: auto; cursor: pointer;';\n"; - $script .= " img.onclick = function() {\n"; - $script .= " trackEventWithBrandDetection('click', { creative_id: {$creative['id']} });\n"; - $script .= " if ('{$creative['click_url']}') {\n"; - $script .= " window.open('{$creative['click_url']}', '_blank');\n"; - $script .= " }\n"; - $script .= " };\n"; - $script .= " content.appendChild(img);\n\n"; - } - - // Botão de fechar - $script .= " const closeBtn = document.createElement('button');\n"; - $script .= " closeBtn.textContent = '×';\n"; - $script .= " closeBtn.style.cssText = 'position: absolute; top: 10px; right: 10px; background: none; border: none; font-size: 24px; cursor: pointer; color: #666;';\n"; - $script .= " closeBtn.onclick = function() {\n"; - $script .= " document.body.removeChild(banner);\n"; - $script .= " };\n"; - $script .= " content.appendChild(closeBtn);\n\n"; - - $script .= " banner.appendChild(content);\n"; - $script .= " document.body.appendChild(banner);\n\n"; - - // Track view com deteção de marca - if (!empty($trackers)) { - $tracker = $trackers[0]; - $script .= " trackEventWithBrandDetection('view', { tracker_id: {$tracker['id']}, creative_id: " . ($creatives[0]['id'] ?? 0) . " });\n"; - } - - $script .= " }\n\n"; - - // Auto-executar - $script .= " // Auto-executar após carregamento\n"; - $script .= " if (document.readyState === 'loading') {\n"; - $script .= " document.addEventListener('DOMContentLoaded', createBanner);\n"; - $script .= " } else {\n"; - $script .= " createBanner();\n"; - $script .= " }\n"; - - $script .= "})();\n"; - - return $script; - } - - /** - * Construir script de popup com deteção configurável de marca - */ - private function buildPopupScriptWithBrandDetection(array $campaign, array $formats, array $trackers, array $creatives): string - { - // Implementação similar ao banner mas para popup - return $this->buildBannerScriptWithBrandDetection($campaign, $formats, $trackers, $creatives); - } - - /** - * Construir script native com deteção configurável de marca - */ - private function buildNativeScriptWithBrandDetection(array $campaign, array $formats, array $trackers, array $creatives): string - { - // Implementação similar ao banner mas para native - return $this->buildBannerScriptWithBrandDetection($campaign, $formats, $trackers, $creatives); - } - - /** - * Construir script de popup - */ - private function buildPopupScript(array $campaign, array $formats, array $trackers, array $creatives): string - { - // Similar ao banner mas com comportamento de popup - return $this->buildBannerScript($campaign, $formats, $trackers, $creatives); - } - - /** - * Construir script nativo - */ - private function buildNativeScript(array $campaign, array $formats, array $trackers, array $creatives): string - { - $script = "// BetZoo Native Advertising Script - {$campaign['name']}\n"; - $script .= "// Generated: " . date('Y-m-d H:i:s') . "\n\n"; - - $script .= "(function() {\n"; - $script .= " 'use strict';\n\n"; - - // Configurações - $script .= " const config = {\n"; - $script .= " campaignId: {$campaign['id']},\n"; - $script .= " campaignName: '{$campaign['name']}',\n"; - $script .= " trackingUrl: '" . $this->getTrackingUrl() . "'\n"; - $script .= " };\n\n"; - - // Função de tracking - $script .= " function trackEvent(eventType, data) {\n"; - $script .= " const trackingData = {\n"; - $script .= " event_type: eventType,\n"; - $script .= " campaign_id: config.campaignId,\n"; - $script .= " session_id: getSessionId(),\n"; - $script .= " timestamp: Date.now(),\n"; - $script .= " ...data\n"; - $script .= " };\n\n"; - - $script .= " fetch(config.trackingUrl + '/api/advertising/tracking/' + eventType, {\n"; - $script .= " method: 'POST',\n"; - $script .= " headers: { 'Content-Type': 'application/json' },\n"; - $script .= " body: JSON.stringify(trackingData)\n"; - $script .= " }).catch(console.error);\n"; - $script .= " }\n\n"; - - // Função para obter session ID - $script .= " function getSessionId() {\n"; - $script .= " let sessionId = localStorage.getItem('betzoo_session_id');\n"; - $script .= " if (!sessionId) {\n"; - $script .= " sessionId = 'sess_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);\n"; - $script .= " localStorage.setItem('betzoo_session_id', sessionId);\n"; - $script .= " }\n"; - $script .= " return sessionId;\n"; - $script .= " }\n\n"; - - // Função para inserir anúncio nativo - $script .= " function insertNativeAd() {\n"; - $script .= " const containers = document.querySelectorAll('.betzoo-native-container');\n"; - $script .= " containers.forEach(function(container, index) {\n"; - $script .= " const ad = document.createElement('div');\n"; - $script .= " ad.className = 'betzoo-native-ad';\n"; - $script .= " ad.innerHTML = '
"; - $script .= "

{$campaign['name']}

"; - $script .= "

Anúncio patrocinado

"; - $script .= " "; - $script .= "
';\n\n"; - - $script .= " ad.querySelector('button').onclick = function() {\n"; - $script .= " trackEvent('click', { position: index });\n"; - $script .= " };\n\n"; - - $script .= " container.appendChild(ad);\n"; - $script .= " trackEvent('view', { position: index });\n"; - $script .= " });\n"; - $script .= " }\n\n"; - - // Auto-executar - $script .= " if (document.readyState === 'loading') {\n"; - $script .= " document.addEventListener('DOMContentLoaded', insertNativeAd);\n"; - $script .= " } else {\n"; - $script .= " insertNativeAd();\n"; - $script .= " }\n"; - - $script .= "})();\n"; - - return $script; - } - - /** - * Salvar script na base de dados - */ - private function saveScript(int $campaignId, string $scriptContent, string $scriptHash): int - { - $sql = "INSERT INTO advertising_scripts ( - cuid, campaign_id, name, script_type, script_content, script_hash, version - ) VALUES ( - :cuid, :campaign_id, :name, :script_type, :script_content, :script_hash, :version - )"; - - $cuid = (string) new \Visus\Cuid2\Cuid2(); - - $this->db->query($sql, [ - ':cuid' => $cuid, - ':campaign_id' => $campaignId, - ':name' => 'Script ' . date('Y-m-d H:i:s'), - ':script_type' => 'banner', - ':script_content' => $scriptContent, - ':script_hash' => $scriptHash, - ':version' => '1.0.0' - ]); - - return $this->db->lastInsertId(); - } - - /** - * Salvar ficheiro de script - */ - private function saveScriptFile(int $scriptId, string $scriptContent): string - { - $fileName = "script_{$scriptId}.js"; - $filePath = $this->outputPath . $fileName; - - file_put_contents($filePath, $scriptContent); - - // Atualizar caminho do ficheiro na base de dados - $sql = "UPDATE advertising_scripts SET file_path = :file_path WHERE id = :id"; - $this->db->query($sql, [ - ':file_path' => $filePath, - ':id' => $scriptId - ]); - - return $fileName; - } - - /** - * Obter URL de tracking - */ - private function getTrackingUrl(): string - { - $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http'; - $host = $_SERVER['HTTP_HOST'] ?? 'localhost:8888'; - return "{$protocol}://{$host}"; - } - - /** - * Deploy de script para CDN - */ - public function deployScript(int $scriptId): array - { - try { - // Obter script da base de dados - $sql = "SELECT * FROM advertising_scripts WHERE id = :id"; - $script = $this->db->fetch($sql, [':id' => $scriptId]); - - if (!$script) { - throw new \Exception('Script não encontrado'); - } - - // Implementar upload para CDN (Cloudflare/S3) - $cdnUrl = $this->uploadToCDN($script['file_path'], $script['script_content']); - - // Atualizar URL do CDN na base de dados - $sql = "UPDATE advertising_scripts SET cdn_url = :cdn_url WHERE id = :id"; - $this->db->query($sql, [ - ':cdn_url' => $cdnUrl, - ':id' => $scriptId - ]); - - return [ - 'success' => true, - 'cdn_url' => $cdnUrl, - 'message' => 'Script deployed successfully' - ]; - - } catch (\Exception $e) { - error_log("Erro ao fazer deploy do script: " . $e->getMessage()); - return [ - 'success' => false, - 'error' => $e->getMessage() - ]; - } - } - - /** - * Upload de script para CDN - */ - private function uploadToCDN(string $filePath, string $scriptContent): string - { - try { - // Verificar se temos configuração de CDN - $cdnConfig = $this->getCDNConfig(); - - if (!$cdnConfig['enabled']) { - // Fallback para URL local - $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http'; - $host = $_SERVER['HTTP_HOST'] ?? 'localhost:8888'; - return "{$protocol}://{$host}/scripts/" . basename($filePath); - } - - // Gerar nome único para o ficheiro - $fileName = 'script_' . md5($scriptContent) . '_' . time() . '.js'; - - // Upload baseado no tipo de CDN configurado - switch ($cdnConfig['type']) { - case 'cloudflare': - return $this->uploadToCloudflare($fileName, $scriptContent, $cdnConfig); - - case 's3': - return $this->uploadToS3($fileName, $scriptContent, $cdnConfig); - - case 'local': - default: - return $this->uploadToLocal($fileName, $scriptContent); - } - - } catch (\Exception $e) { - error_log("Erro no upload para CDN: " . $e->getMessage()); - // Fallback para URL local - $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http'; - $host = $_SERVER['HTTP_HOST'] ?? 'localhost:8888'; - return "{$protocol}://{$host}/scripts/" . basename($filePath); - } - } - - /** - * Obter configuração de CDN - */ - private function getCDNConfig(): array - { - // Por agora, usar configuração local - // TODO: Implementar configuração via base de dados ou ficheiro de config - return [ - 'enabled' => false, // Desabilitado por padrão - 'type' => 'local', - 'cloudflare' => [ - 'zone_id' => '', - 'api_token' => '' - ], - 's3' => [ - 'bucket' => '', - 'region' => '', - 'access_key' => '', - 'secret_key' => '' - ] - ]; - } - - /** - * Upload para Cloudflare - */ - private function uploadToCloudflare(string $fileName, string $content, array $config): string - { - // Implementação básica para Cloudflare - $url = "https://api.cloudflare.com/client/v4/zones/{$config['cloudflare']['zone_id']}/purge_cache"; - - // Por agora, retornar URL simulada - return "https://cdn.betzoo.app/scripts/{$fileName}"; - } - - /** - * Upload para S3 - */ - private function uploadToS3(string $fileName, string $content, array $config): string - { - // Implementação básica para S3 - // Por agora, retornar URL simulada - return "https://s3.amazonaws.com/{$config['s3']['bucket']}/scripts/{$fileName}"; - } - - /** - * Upload para servidor local - */ - private function uploadToLocal(string $fileName, string $content): string - { - $localPath = $this->outputPath . $fileName; - file_put_contents($localPath, $content); - - $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http'; - $host = $_SERVER['HTTP_HOST'] ?? 'localhost:8888'; - - return "{$protocol}://{$host}/scripts/{$fileName}"; - } -}