- Fix storage permissions to use 'www' user instead of 'www-data' - Fix UserModel getAllForAdmin query to avoid placeholders in LIMIT/OFFSET - Import missing modules: Advertising, Dashboard, Analytics - Update deploy script to copy files to public directory
1401 lines
50 KiB
PHP
1401 lines
50 KiB
PHP
<?php
|
|
namespace App\Modules\Advertising\Controllers;
|
|
|
|
use App\Core\BaseController;
|
|
use App\Core\View;
|
|
use App\Core\DatabaseManager;
|
|
use App\Core\ErrorReporter;
|
|
use App\Core\Sanitize;
|
|
use App\Core\InputSanitizer;
|
|
use App\Modules\Advertising\Services\ScriptBuilderService;
|
|
|
|
class AdvertisingController extends BaseController
|
|
{
|
|
public function __construct()
|
|
{
|
|
parent::__construct('Advertising');
|
|
}
|
|
|
|
public function dashboard(): void
|
|
{
|
|
try {
|
|
// Get dashboard data
|
|
$campaignModel = $this->resolveModuleService('model.CampaignModel');
|
|
$campaigns = $campaignModel->getAll(['status' => 'active'], 10);
|
|
|
|
// Get campaign statistics
|
|
$stats = $campaignModel->getStats();
|
|
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Dashboard de Publicidade',
|
|
'page_name' => 'advertising-dashboard',
|
|
'page_content' => function() use ($campaigns, $stats) {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Publicidade',
|
|
'title' => 'Dashboard'
|
|
]);
|
|
View::render('@advertising/dashboard', [
|
|
'campaigns' => $campaigns,
|
|
'stats' => $stats
|
|
]);
|
|
}
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_dashboard']);
|
|
http_response_code(500);
|
|
echo 'Erro interno do servidor';
|
|
}
|
|
}
|
|
|
|
public function campaigns(): void
|
|
{
|
|
try {
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Campanhas - Publicidade',
|
|
'page_name' => 'advertising-campaigns',
|
|
'page_content' => function() {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Publicidade',
|
|
'title' => 'Campanhas'
|
|
]);
|
|
View::render('@advertising/campaigns.php');
|
|
}
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_campaigns']);
|
|
http_response_code(500);
|
|
echo 'Erro interno do servidor';
|
|
}
|
|
}
|
|
|
|
public function campaignCreate(): void
|
|
{
|
|
try {
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Nova Campanha',
|
|
'page_content' => function() {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Publicidade',
|
|
'title' => 'Nova Campanha'
|
|
]);
|
|
View::render('@advertising/campaign-create');
|
|
}
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_campaign_create']);
|
|
http_response_code(500);
|
|
echo 'Erro interno do servidor';
|
|
}
|
|
}
|
|
|
|
public function editCampaign(int $id): void
|
|
{
|
|
try {
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Editar Campanha',
|
|
'page_content' => function() {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Publicidade',
|
|
'title' => 'Editar Campanha'
|
|
]);
|
|
View::render('@advertising/campaign-edit');
|
|
}
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_edit_campaign', 'id' => $id]);
|
|
http_response_code(500);
|
|
echo 'Erro interno do servidor';
|
|
}
|
|
}
|
|
|
|
public function campaignView(int $id): void
|
|
{
|
|
try {
|
|
// Validar ID
|
|
if ($id <= 0) {
|
|
http_response_code(400);
|
|
echo 'ID da campanha inválido';
|
|
return;
|
|
}
|
|
|
|
$campaignModel = $this->resolveModuleService('model.CampaignModel');
|
|
|
|
$campaign = $campaignModel->find($id);
|
|
|
|
if (!$campaign) {
|
|
http_response_code(404);
|
|
echo "Campanha não encontrada.";
|
|
return;
|
|
}
|
|
|
|
$stats = $campaignModel->getCampaignStats($id);
|
|
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Detalhes da Campanha',
|
|
'page_content' => function() use ($campaign, $stats) {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Publicidade',
|
|
'title' => 'Detalhes da Campanha'
|
|
]);
|
|
View::render('@advertising/campaign-view', [
|
|
'campaign' => $campaign,
|
|
'stats' => $stats
|
|
]);
|
|
}
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_campaign_view', 'id' => $id]);
|
|
http_response_code(500);
|
|
echo 'Erro interno do servidor';
|
|
}
|
|
}
|
|
|
|
public function creatives(): void
|
|
{
|
|
try {
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Gestão de Criativos',
|
|
'page_content' => function() {
|
|
View::render('@advertising/creatives');
|
|
}
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_creatives']);
|
|
http_response_code(500);
|
|
echo 'Erro interno do servidor';
|
|
}
|
|
}
|
|
|
|
public function createCreative(): void
|
|
{
|
|
try {
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Novo Criativo - Publicidade',
|
|
'page_content' => function() {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Publicidade',
|
|
'title' => 'Novo Criativo'
|
|
]);
|
|
View::render('@advertising/creative-create.php');
|
|
}
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_create_creative']);
|
|
http_response_code(500);
|
|
echo 'Erro interno do servidor';
|
|
}
|
|
}
|
|
|
|
public function viewCreative(int $id): void
|
|
{
|
|
try {
|
|
// Validar ID
|
|
if ($id <= 0) {
|
|
http_response_code(400);
|
|
echo 'ID do criativo inválido';
|
|
return;
|
|
}
|
|
|
|
// Buscar dados do criativo
|
|
$db = DatabaseManager::getInstance();
|
|
$creative = $db->fetch("
|
|
SELECT
|
|
c.id AS creative_id,
|
|
c.name AS creative_name,
|
|
c.description AS creative_description,
|
|
c.creative_type AS creative_type,
|
|
c.format_id AS format_id,
|
|
c.file_name AS file_name,
|
|
c.file_path AS file_path,
|
|
c.width AS width,
|
|
c.height AS height,
|
|
c.alt_text AS alt_text,
|
|
c.mime_type AS mime_type,
|
|
c.is_active AS is_active,
|
|
c.created_at AS created_date,
|
|
c.updated_at AS updated_date
|
|
FROM
|
|
advertising_creatives c
|
|
WHERE
|
|
c.id = ?
|
|
", [$id]);
|
|
|
|
if (!$creative) {
|
|
http_response_code(404);
|
|
echo 'Criativo não encontrado';
|
|
return;
|
|
}
|
|
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Detalhes do Criativo',
|
|
'page_name' => 'apps/advertising/creative-view',
|
|
'page_content' => function() use ($creative) {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Advertising',
|
|
'title' => 'Detalhes do Criativo'
|
|
]);
|
|
View::render('@advertising/creative-view', ['creative' => $creative]);
|
|
}
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_view_creative', 'id' => $id]);
|
|
http_response_code(500);
|
|
echo 'Erro interno do servidor';
|
|
}
|
|
}
|
|
|
|
public function editCreative(int $id): void
|
|
{
|
|
try {
|
|
// Validar ID
|
|
if ($id <= 0) {
|
|
http_response_code(400);
|
|
echo 'ID do criativo inválido';
|
|
return;
|
|
}
|
|
|
|
// Buscar dados do criativo
|
|
$db = DatabaseManager::getInstance();
|
|
$creative = $db->fetch("
|
|
SELECT
|
|
c.id AS creative_id,
|
|
c.name AS creative_name,
|
|
c.description AS creative_description,
|
|
c.creative_type AS creative_type,
|
|
c.format_id AS format_id,
|
|
c.file_name AS file_name,
|
|
c.file_path AS file_path,
|
|
c.width AS width,
|
|
c.height AS height,
|
|
c.alt_text AS alt_text,
|
|
c.mime_type AS mime_type,
|
|
c.is_active AS is_active,
|
|
c.created_at AS created_date,
|
|
c.updated_at AS updated_date
|
|
FROM
|
|
advertising_creatives c
|
|
WHERE
|
|
c.id = ?
|
|
", [$id]);
|
|
|
|
if (!$creative) {
|
|
header('Location: /advertising/creatives?error=not_found&id=' . $id);
|
|
exit;
|
|
}
|
|
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Editar Criativo',
|
|
'page_name' => 'apps/advertising/creative-edit',
|
|
'page_content' => function() use ($id) {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Advertising',
|
|
'title' => 'Editar Criativo'
|
|
]);
|
|
View::render('@advertising/creative-edit');
|
|
}
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_edit_creative', 'id' => $id]);
|
|
http_response_code(500);
|
|
echo 'Erro interno do servidor';
|
|
}
|
|
}
|
|
|
|
public function tracking(): void
|
|
{
|
|
try {
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Sistema de Tracking',
|
|
'page_content' => function() {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Publicidade',
|
|
'title' => 'Tracking'
|
|
]);
|
|
View::render('@advertising/tracking');
|
|
}
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_tracking']);
|
|
http_response_code(500);
|
|
echo 'Erro interno do servidor';
|
|
}
|
|
}
|
|
|
|
public function trackingView(int $id): void
|
|
{
|
|
try {
|
|
// Validar ID
|
|
if ($id <= 0) {
|
|
http_response_code(400);
|
|
echo 'ID do tracker inválido';
|
|
return;
|
|
}
|
|
|
|
$trackingModel = $this->resolveModuleService('model.TrackingModel');
|
|
|
|
$tracker = $trackingModel->find($id);
|
|
|
|
if (!$tracker) {
|
|
http_response_code(404);
|
|
echo "Tracker não encontrado.";
|
|
return;
|
|
}
|
|
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Detalhes do Tracker',
|
|
'page_name' => 'apps/advertising/tracker-view',
|
|
'page_content' => function() use ($tracker) {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Advertising',
|
|
'title' => 'Detalhes do Tracker'
|
|
]);
|
|
View::render('@advertising/tracker-view', [
|
|
'tracker' => $tracker
|
|
]);
|
|
}
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_tracking_view', 'tracker_id' => $id]);
|
|
header('Location: /advertising/trackers?error=view_failed&id=' . $id);
|
|
exit;
|
|
}
|
|
}
|
|
|
|
public function scripts(): void
|
|
{
|
|
try {
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Script Builder',
|
|
'page_content' => function() {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Publicidade',
|
|
'title' => 'Script Builder'
|
|
]);
|
|
View::render('@advertising/scripts');
|
|
}
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_scripts']);
|
|
http_response_code(500);
|
|
echo 'Erro interno do servidor';
|
|
}
|
|
}
|
|
|
|
public function reports(): void
|
|
{
|
|
try {
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Relatórios',
|
|
'page_content' => function() {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Publicidade',
|
|
'title' => 'Relatórios'
|
|
]);
|
|
View::render('@advertising/reports');
|
|
}
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_reports']);
|
|
http_response_code(500);
|
|
echo 'Erro interno do servidor';
|
|
}
|
|
}
|
|
|
|
public function createTracker(): void
|
|
{
|
|
try {
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Novo Tracker - Publicidade',
|
|
'page_content' => function() {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Publicidade',
|
|
'title' => 'Novo Tracker'
|
|
]);
|
|
View::render('@advertising/tracker-create.php');
|
|
}
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_create_tracker']);
|
|
http_response_code(500);
|
|
echo 'Erro interno do servidor';
|
|
}
|
|
}
|
|
|
|
public function editTracker(int $id): void
|
|
{
|
|
try {
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Editar Tracker',
|
|
'page_content' => function() {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Publicidade',
|
|
'title' => 'Editar Tracker'
|
|
]);
|
|
View::render('@advertising/tracker-edit');
|
|
}
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_edit_tracker', 'id' => $id]);
|
|
http_response_code(500);
|
|
echo 'Erro interno do servidor';
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Landing Types management page
|
|
*/
|
|
public function landingTypes(): void
|
|
{
|
|
try {
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Tipos de Landing Page',
|
|
'page_content' => function() {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Publicidade',
|
|
'title' => 'Tipos de Landing Page'
|
|
]);
|
|
View::render('@advertising/landing-types-simple');
|
|
}
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_landing_types']);
|
|
http_response_code(500);
|
|
echo 'Erro interno do servidor';
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Gestão de Marcas
|
|
*/
|
|
public function brands(): void
|
|
{
|
|
try {
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Gestão de Marcas',
|
|
'page_content' => function() {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Publicidade',
|
|
'title' => 'Gestão de Marcas'
|
|
]);
|
|
View::render('@advertising/brands');
|
|
}
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_brands']);
|
|
http_response_code(500);
|
|
echo 'Erro interno do servidor';
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Site Groups (Multisites) - Lista
|
|
*/
|
|
public function siteGroups(): void
|
|
{
|
|
try {
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Site Groups (Multisites)',
|
|
'page_content' => function() {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Publicidade',
|
|
'title' => 'Site Groups (Multisites)'
|
|
]);
|
|
View::render('@advertising/site-groups.php');
|
|
}
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_site_groups']);
|
|
http_response_code(500);
|
|
echo 'Erro interno do servidor';
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Site Groups (Multisites) - Criar
|
|
*/
|
|
public function createSiteGroup(): void
|
|
{
|
|
try {
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Criar Site Group',
|
|
'page_content' => function() {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Publicidade',
|
|
'title' => 'Criar Site Group'
|
|
]);
|
|
View::render('@advertising/site-group-create.php');
|
|
}
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_create_site_group']);
|
|
http_response_code(500);
|
|
echo 'Erro interno do servidor';
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Site Groups (Multisites) - Editar
|
|
*/
|
|
public function editSiteGroup(int $id): void
|
|
{
|
|
try {
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Buscar dados do site group
|
|
$siteGroup = $db->fetch("
|
|
SELECT
|
|
sg.id AS site_group_id,
|
|
sg.name AS site_group_name,
|
|
sg.description AS site_group_description,
|
|
sg.status AS site_group_status,
|
|
sg.settings AS site_group_settings,
|
|
sg.created_at AS created_date,
|
|
sg.updated_at AS updated_date
|
|
FROM
|
|
advertising_site_groups sg
|
|
WHERE
|
|
sg.id = ? AND sg.status >= 0
|
|
", [$id]);
|
|
|
|
if (!$siteGroup) {
|
|
// ✅ CORRECT: Redirect to list page and let Alpine.js handle the error display
|
|
header('Location: /advertising/site-groups?error=not_found&id=' . $id);
|
|
exit;
|
|
}
|
|
|
|
// Buscar campanhas do site group
|
|
$campaigns = $db->fetchAll("
|
|
SELECT
|
|
c.*,
|
|
COUNT(DISTINCT ct.tracker_id) AS tracker_count,
|
|
0 AS creative_count
|
|
FROM
|
|
advertising_campaigns c
|
|
LEFT JOIN
|
|
advertising_campaign_trackers ct ON c.id = ct.campaign_id
|
|
WHERE
|
|
c.site_group_id = ? AND c.status >= 0
|
|
GROUP BY
|
|
c.id
|
|
ORDER BY
|
|
c.created_at DESC
|
|
", [$id]) ?: [];
|
|
|
|
// Buscar trackers do site group
|
|
$trackers = $db->fetchAll("
|
|
SELECT
|
|
t.*,
|
|
c.name AS campaign_name,
|
|
'active' AS status
|
|
FROM
|
|
advertising_trackers t
|
|
JOIN
|
|
advertising_campaign_trackers ct ON t.id = ct.tracker_id
|
|
JOIN
|
|
advertising_campaigns c ON ct.campaign_id = c.id
|
|
WHERE
|
|
c.site_group_id = ? AND t.is_active = 1 AND c.status >= 0
|
|
ORDER BY
|
|
t.created_at DESC
|
|
", [$id]) ?: [];
|
|
|
|
// Buscar domínios do site group
|
|
$domains = $db->fetchAll("
|
|
SELECT
|
|
d.*
|
|
FROM
|
|
advertising_site_domains d
|
|
WHERE
|
|
d.site_group_id = ? AND d.status >= 0
|
|
ORDER BY
|
|
d.is_primary DESC, d.domain ASC
|
|
", [$id]) ?: [];
|
|
|
|
// ✅ PERFORMANCE: Calculate stats in MySQL, not PHP
|
|
$statsQuery = $db->fetch("
|
|
SELECT
|
|
COUNT(DISTINCT c.id) AS total_campaigns,
|
|
SUM(IF(c.status = 1, 1, 0)) AS active_campaigns,
|
|
COUNT(DISTINCT ct.tracker_id) AS total_trackers,
|
|
COUNT(DISTINCT d.id) AS total_domains
|
|
FROM
|
|
advertising_campaigns c
|
|
LEFT JOIN
|
|
advertising_campaign_trackers ct ON c.id = ct.campaign_id
|
|
LEFT JOIN
|
|
advertising_site_domains d ON d.site_group_id = c.site_group_id AND d.status >= 0
|
|
WHERE
|
|
c.site_group_id = ? AND c.status >= 0
|
|
", [$id]);
|
|
|
|
$stats = [
|
|
'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_domains' => (int)($statsQuery['total_domains'] ?? 0)
|
|
];
|
|
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Editar Site Group - ' . $siteGroup['site_group_name'],
|
|
'page_name' => 'apps/advertising/site-group-edit',
|
|
'page_content' => function() use ($siteGroup, $campaigns, $trackers, $domains, $stats) {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Publicidade',
|
|
'title' => 'Editar Site Group'
|
|
]);
|
|
View::render('@advertising/site-group-edit', [
|
|
'siteGroup' => $siteGroup,
|
|
'campaigns' => $campaigns,
|
|
'trackers' => $trackers,
|
|
'domains' => $domains,
|
|
'stats' => $stats
|
|
]);
|
|
}
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_edit_site_group', 'id' => $id]);
|
|
http_response_code(500);
|
|
echo 'Erro interno do servidor';
|
|
}
|
|
}
|
|
|
|
// --- PUBLIC INTERFACE METHODS ---
|
|
// Estes métodos fornecem uma interface pública para funcionalidades do módulo Advertising
|
|
|
|
/**
|
|
* Renders the public analytics dashboard.
|
|
* Interface pública para analytics de campanhas.
|
|
*/
|
|
public function publicAnalytics(string $slug): void
|
|
{
|
|
try {
|
|
$branding = \App\Core\Branding::get();
|
|
$page_title = ($branding['company_name'] ?? 'Analytics') . ' - Campaign Dashboard';
|
|
|
|
\App\Core\View::render('layouts/public.php', [
|
|
'title' => $page_title,
|
|
'page_name' => 'public-analytics',
|
|
'branding' => $branding,
|
|
'slug' => $slug,
|
|
'page_content' => function() use ($slug) {
|
|
\App\Core\View::render('@public/analytics', ['slug' => $slug]);
|
|
}
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_public_analytics', 'slug' => $slug]);
|
|
http_response_code(500);
|
|
echo 'Erro interno do servidor';
|
|
}
|
|
}
|
|
|
|
/**
|
|
* API endpoint: Get campaign stats by slug and optional filters.
|
|
* Interface pública da API para dados de campanhas.
|
|
*/
|
|
public function getPublicCampaignStats(string $slug): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
if (empty($slug)) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'Missing campaign slug']);
|
|
return;
|
|
}
|
|
|
|
// Get query parameters
|
|
$startDate = Sanitize::string($_GET['startDate'] ?? date('Y-m-d', strtotime('-30 days')));
|
|
$endDate = Sanitize::string($_GET['endDate'] ?? date('Y-m-d'));
|
|
$domain = Sanitize::string($_GET['domain'] ?? '');
|
|
|
|
// Buscar campanha por cuid (slug)
|
|
$campaign = $this->getCampaignByCuid($slug);
|
|
if (!$campaign) {
|
|
http_response_code(404);
|
|
echo json_encode(['success' => false, 'message' => 'Campaign not found']);
|
|
return;
|
|
}
|
|
|
|
// Buscar dados reais da campanha
|
|
$data = $this->getRealCampaignData($campaign['id'], $startDate, $endDate, $domain);
|
|
|
|
echo json_encode(['success' => true, 'data' => $data]);
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_public_campaign_stats', 'slug' => $slug]);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Error fetching campaign data']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* API: Obter lista de campanhas com filtros e paginação
|
|
*/
|
|
public function apiCampaigns(): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
$page = (int)($_GET['page'] ?? 1);
|
|
$limit = (int)($_GET['limit'] ?? 20);
|
|
$search = InputSanitizer::get('search', 'GET', '');
|
|
$status = InputSanitizer::get('status', 'GET', '');
|
|
$region = InputSanitizer::get('region', 'GET', '');
|
|
|
|
// Get real campaign data from database
|
|
$campaignModel = new \App\Modules\Advertising\Models\CampaignModel();
|
|
$campaigns = $campaignModel->getAll([
|
|
'search' => $search,
|
|
'status' => $status,
|
|
'region' => $region
|
|
], $limit, ($page - 1) * $limit);
|
|
|
|
$total = $campaignModel->getCount([
|
|
'search' => $search,
|
|
'status' => $status,
|
|
'region' => $region
|
|
]);
|
|
|
|
// Calculate stats from real data
|
|
$stats = $campaignModel->getStats();
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => [
|
|
'campaigns' => $campaigns,
|
|
'stats' => $stats,
|
|
'pagination' => [
|
|
'page' => $page,
|
|
'limit' => $limit,
|
|
'total' => $total,
|
|
'pages' => ceil($total / $limit)
|
|
]
|
|
],
|
|
'timestamp' => date('c')
|
|
]);
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'api_campaigns']);
|
|
http_response_code(500);
|
|
echo json_encode([
|
|
'success' => false,
|
|
'error' => 'Erro ao carregar campanhas',
|
|
'timestamp' => date('c')
|
|
]);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* API: Obter detalhes de uma campanha específica
|
|
*/
|
|
public function apiCampaignDetails(int $id): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
if ($id <= 0) {
|
|
http_response_code(400);
|
|
echo json_encode([
|
|
'success' => false,
|
|
'error' => 'ID da campanha inválido'
|
|
]);
|
|
return;
|
|
}
|
|
|
|
// Get real campaign data from database
|
|
$campaignModel = new \App\Modules\Advertising\Models\CampaignModel();
|
|
$campaign = $campaignModel->find($id);
|
|
|
|
if (!$campaign) {
|
|
http_response_code(404);
|
|
echo json_encode([
|
|
'success' => false,
|
|
'error' => 'Campanha não encontrada'
|
|
]);
|
|
return;
|
|
}
|
|
|
|
// Get real stats from database
|
|
$stats = $campaignModel->getCampaignStats($id);
|
|
|
|
// Get real spend data from database
|
|
$spend = $campaignModel->getCampaignSpend($id);
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => [
|
|
'campaign' => $campaign,
|
|
'stats' => $stats,
|
|
'spend' => $spend,
|
|
'formatted' => [
|
|
'status_class' => $this->getStatusClass($campaign['status']),
|
|
'status_display' => $this->getStatusDisplay($campaign['status']),
|
|
'start_date_formatted' => $campaign['start_date'] ? date('d/m/Y', strtotime($campaign['start_date'])) : 'N/A',
|
|
'end_date_formatted' => $campaign['end_date'] ? date('d/m/Y', strtotime($campaign['end_date'])) : 'Sem data fim'
|
|
]
|
|
],
|
|
'timestamp' => date('c')
|
|
]);
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'api_campaign_details', 'id' => $id]);
|
|
http_response_code(500);
|
|
echo json_encode([
|
|
'success' => false,
|
|
'error' => 'Erro ao carregar detalhes da campanha',
|
|
'timestamp' => date('c')
|
|
]);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* API: Obter dados do dashboard de advertising
|
|
*/
|
|
public function apiDashboard(): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
// Get real campaigns data from database
|
|
$db = DatabaseManager::getInstance();
|
|
$campaigns = $db->fetchAll("SELECT id, name, status, created_at FROM advertising_campaigns WHERE status >= 0 ORDER BY created_at DESC LIMIT 10");
|
|
|
|
if (empty($campaigns)) {
|
|
$campaigns = [
|
|
[
|
|
'id' => 0,
|
|
'name' => 'No campaigns available',
|
|
'description' => 'No campaigns found',
|
|
'status' => 'inactive',
|
|
'category' => 'none',
|
|
'created_at' => date('Y-m-d H:i:s')
|
|
]
|
|
];
|
|
}
|
|
|
|
// Get real stats from database
|
|
$stats = [
|
|
'total_campaigns' => $db->fetch("SELECT COUNT(*) as count FROM advertising_campaigns WHERE status >= 0")['count'] ?? 0,
|
|
'active_campaigns' => $db->fetch("SELECT COUNT(*) as count FROM advertising_campaigns WHERE status = 'active'")['count'] ?? 0,
|
|
'paused_campaigns' => $db->fetch("SELECT COUNT(*) as count FROM advertising_campaigns WHERE status = 'paused'")['count'] ?? 0,
|
|
'draft_campaigns' => $db->fetch("SELECT COUNT(*) as count FROM advertising_campaigns WHERE status = 'draft'")['count'] ?? 0
|
|
];
|
|
|
|
// Get real types data from database
|
|
$types = $db->fetchAll("SELECT type, COUNT(*) as count FROM advertising_campaigns WHERE status >= 0 GROUP BY type");
|
|
|
|
if (empty($types)) {
|
|
$types = [
|
|
['type' => 'none', 'count' => 0]
|
|
];
|
|
}
|
|
|
|
// Get real performance data from database
|
|
// Get real performance data from database
|
|
$performanceResult = $db->fetch("
|
|
SELECT
|
|
SUM(total_impressions) as total_impressions,
|
|
SUM(total_clicks) as total_clicks,
|
|
CASE
|
|
WHEN SUM(total_impressions) > 0
|
|
THEN ROUND(SUM(total_clicks) * 100.0 / SUM(total_impressions), 2)
|
|
ELSE 0
|
|
END as ctr
|
|
FROM advertising_campaigns
|
|
WHERE status >= 0
|
|
");
|
|
|
|
$performance = [
|
|
'total_impressions' => (int)($performanceResult['total_impressions'] ?? 0),
|
|
'total_clicks' => (int)($performanceResult['total_clicks'] ?? 0),
|
|
'ctr' => (float)($performanceResult['ctr'] ?? 0)
|
|
];
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => [
|
|
'campaigns' => $campaigns,
|
|
'stats' => $stats,
|
|
'types' => $types,
|
|
'performance' => $performance,
|
|
'formatted' => [
|
|
'campaigns' => array_map(function($campaign) {
|
|
return [
|
|
'id' => $campaign['id'],
|
|
'name' => $campaign['name'],
|
|
'description' => $campaign['description'] ?? '',
|
|
'status' => $campaign['status'],
|
|
'status_class' => $this->getStatusClass($campaign['status']),
|
|
'category' => ucfirst($campaign['category'] ?? 'N/A'),
|
|
'created_at' => date('d/m/Y', strtotime($campaign['created_at']))
|
|
];
|
|
}, $campaigns)
|
|
]
|
|
],
|
|
'timestamp' => date('c')
|
|
]);
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'api_advertising_dashboard']);
|
|
http_response_code(500);
|
|
echo json_encode([
|
|
'success' => false,
|
|
'error' => 'Erro ao carregar dashboard',
|
|
'timestamp' => date('c')
|
|
]);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get campaign by cuid (slug)
|
|
*/
|
|
private function getCampaignByCuid(string $cuid): ?array
|
|
{
|
|
// Get real campaign data from database
|
|
$campaignModel = new \App\Modules\Advertising\Models\CampaignModel();
|
|
return $campaignModel->findByCuid($cuid);
|
|
}
|
|
|
|
/**
|
|
* Get real campaign data from database
|
|
*/
|
|
private function getRealCampaignData(int $campaignId, string $startDate, string $endDate, string $domain): array
|
|
{
|
|
// Buscar formatos da campanha
|
|
$formats = $this->getCampaignFormats($campaignId);
|
|
|
|
// Buscar estatísticas reais
|
|
$stats = $this->getCampaignStatsData($campaignId, $startDate, $endDate);
|
|
|
|
// Buscar dados de gráficos
|
|
$charts = $this->getCampaignCharts($campaignId, $startDate, $endDate);
|
|
|
|
// Buscar dados de tabelas
|
|
$tables = $this->getCampaignTables($campaignId, $startDate, $endDate);
|
|
|
|
// Buscar domínios disponíveis
|
|
$domains = $this->getAvailableDomains($campaignId);
|
|
|
|
return [
|
|
'slug' => $campaignId,
|
|
'filters' => [
|
|
'domains' => $domains
|
|
],
|
|
'scriptInfo' => [
|
|
'estimatedRevenue' => $stats['total_revenue'] ?? 0,
|
|
'scriptStatusClass' => $this->getStatusClass($stats['status'] ?? 'active'),
|
|
'scriptStatusDisplay' => $this->getStatusDisplay($stats['status'] ?? 'active'),
|
|
'totalViewsAllTime' => $stats['total_views'] ?? 0,
|
|
'firstHit' => $stats['first_hit'] ?? date('Y-m-d'),
|
|
'dealType' => 'CPM',
|
|
'scriptId' => 'script_' . $campaignId
|
|
],
|
|
'kpis' => [
|
|
'impressions' => ['value' => $stats['total_views'] ?? 0],
|
|
'clicks' => ['value' => $stats['total_clicks'] ?? 0],
|
|
'ctr' => ['value' => $stats['avg_ctr'] ?? 0]
|
|
],
|
|
'charts' => $charts,
|
|
'tables' => $tables
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Get campaign formats
|
|
*/
|
|
private function getCampaignFormats(int $campaignId): array
|
|
{
|
|
// Get real campaign formats from database
|
|
$db = DatabaseManager::getInstance();
|
|
$formats = $db->fetchAll("
|
|
SELECT
|
|
id,
|
|
campaign_id,
|
|
name,
|
|
width,
|
|
height,
|
|
is_active
|
|
FROM advertising_formats
|
|
WHERE campaign_id = ? AND status >= 0
|
|
ORDER BY created_at DESC
|
|
", [$campaignId]);
|
|
|
|
if (empty($formats)) {
|
|
return [
|
|
[
|
|
'id' => 0,
|
|
'campaign_id' => $campaignId,
|
|
'name' => 'No formats available',
|
|
'width' => 0,
|
|
'height' => 0,
|
|
'is_active' => 0
|
|
]
|
|
];
|
|
}
|
|
|
|
return $formats;
|
|
}
|
|
|
|
/**
|
|
* Get campaign statistics data
|
|
*/
|
|
private function getCampaignStatsData(int $campaignId, string $startDate, string $endDate): array
|
|
{
|
|
// Get real campaign stats from database
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Get campaign info
|
|
$campaign = $db->fetch("SELECT id, name, status, start_date, end_date, created_at, updated_at FROM advertising_campaigns WHERE id = ?", [$campaignId]);
|
|
|
|
// Get formats count
|
|
$formatsCount = $db->fetch("SELECT COUNT(*) as count FROM advertising_formats WHERE campaign_id = ?", [$campaignId])['count'] ?? 0;
|
|
|
|
// Get creatives count
|
|
$creativesCount = $db->fetch("SELECT COUNT(*) as count FROM advertising_creatives WHERE campaign_id = ?", [$campaignId])['count'] ?? 0;
|
|
|
|
// Get real tracking data from database
|
|
$statsResult = $db->fetch("
|
|
SELECT
|
|
total_impressions as total_views,
|
|
total_clicks,
|
|
0 as total_registers,
|
|
0 as total_revenue,
|
|
CASE
|
|
WHEN total_impressions > 0
|
|
THEN ROUND(total_clicks * 100.0 / total_impressions, 2)
|
|
ELSE 0
|
|
END as avg_ctr,
|
|
0 as avg_cpm,
|
|
0 as avg_epc,
|
|
created_at as first_hit
|
|
FROM advertising_campaigns
|
|
WHERE id = ? AND status >= 0
|
|
", [$campaignId]);
|
|
|
|
return [
|
|
'id' => $campaignId,
|
|
'name' => $campaign['name'] ?? 'Unknown Campaign',
|
|
'status' => $campaign['status'] ?? 'inactive',
|
|
'formats_count' => $formatsCount,
|
|
'creatives_count' => $creativesCount,
|
|
'total_views' => (int)($statsResult['total_views'] ?? 0),
|
|
'total_clicks' => (int)($statsResult['total_clicks'] ?? 0),
|
|
'total_registers' => (int)($statsResult['total_registers'] ?? 0),
|
|
'total_revenue' => (float)($statsResult['total_revenue'] ?? 0),
|
|
'avg_ctr' => (float)($statsResult['avg_ctr'] ?? 0),
|
|
'avg_cpm' => (float)($statsResult['avg_cpm'] ?? 0),
|
|
'avg_epc' => (float)($statsResult['avg_epc'] ?? 0),
|
|
'first_hit' => $statsResult['first_hit'] ? date('Y-m-d', strtotime($statsResult['first_hit'])) : date('Y-m-d')
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Get campaign charts data
|
|
*/
|
|
private function getCampaignCharts(int $campaignId, string $startDate, string $endDate): array
|
|
{
|
|
// Dados de impressions e clicks por dia
|
|
$impressionsClicks = $this->getImpressionsClicksData($campaignId, $startDate, $endDate);
|
|
|
|
// Dados geográficos
|
|
$geos = $this->getGeosData($campaignId, $startDate, $endDate);
|
|
|
|
// Dados de dispositivos
|
|
$devices = $this->getDevicesData($campaignId, $startDate, $endDate);
|
|
|
|
return [
|
|
'impressionsAndClicks' => $impressionsClicks,
|
|
'geos' => $geos,
|
|
'devices' => $devices
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Get impressions and clicks data for charts
|
|
*/
|
|
private function getImpressionsClicksData(int $campaignId, string $startDate, string $endDate): array
|
|
{
|
|
// Get real tracking data from database
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
$dates = [];
|
|
$impressions = [];
|
|
$clicks = [];
|
|
|
|
// Get real data for last 30 days
|
|
$data = $db->fetchAll("
|
|
SELECT
|
|
DATE(created_at) as date,
|
|
SUM(total_impressions) as impressions,
|
|
SUM(total_clicks) as clicks
|
|
FROM advertising_campaigns
|
|
WHERE id = ?
|
|
AND created_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
|
|
GROUP BY DATE(created_at)
|
|
ORDER BY date ASC
|
|
", [$campaignId]);
|
|
|
|
// Create date map
|
|
$dataMap = [];
|
|
foreach ($data as $row) {
|
|
$dataMap[$row['date']] = [
|
|
'impressions' => (int)$row['impressions'],
|
|
'clicks' => (int)$row['clicks']
|
|
];
|
|
}
|
|
|
|
// Generate last 30 days with real data
|
|
for ($i = 29; $i >= 0; $i--) {
|
|
$date = date('Y-m-d', strtotime("-{$i} days"));
|
|
$dates[] = $date;
|
|
$impressions[] = $dataMap[$date]['impressions'] ?? 0;
|
|
$clicks[] = $dataMap[$date]['clicks'] ?? 0;
|
|
}
|
|
|
|
return [
|
|
'categories' => $dates,
|
|
'series' => [
|
|
[
|
|
'name' => 'Impressions',
|
|
'data' => $impressions
|
|
],
|
|
[
|
|
'name' => 'Clicks',
|
|
'data' => $clicks
|
|
]
|
|
]
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Get geographical data for charts
|
|
*/
|
|
private function getGeosData(int $campaignId, string $startDate, string $endDate): array
|
|
{
|
|
// Get real geo data from database
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
$geoData = $db->fetchAll("
|
|
SELECT
|
|
allowed_countries as country,
|
|
SUM(total_impressions) as impressions,
|
|
SUM(total_clicks) as clicks
|
|
FROM advertising_campaigns
|
|
WHERE id = ?
|
|
AND allowed_countries IS NOT NULL
|
|
GROUP BY allowed_countries
|
|
ORDER BY impressions DESC
|
|
LIMIT 10
|
|
", [$campaignId]);
|
|
|
|
$countries = [];
|
|
$impressions = [];
|
|
$clicks = [];
|
|
|
|
foreach ($geoData as $row) {
|
|
$countries[] = $row['country'];
|
|
$impressions[] = (int)$row['impressions'];
|
|
$clicks[] = (int)$row['clicks'];
|
|
}
|
|
|
|
// Fallback if no data
|
|
if (empty($countries)) {
|
|
$countries = ['AA', 'ZA', 'NG', 'CL'];
|
|
$impressions = [0, 0, 0, 0];
|
|
$clicks = [0, 0, 0, 0];
|
|
}
|
|
|
|
return [
|
|
'categories' => $countries,
|
|
'series' => [
|
|
[
|
|
'name' => 'Impressions',
|
|
'data' => $impressions
|
|
],
|
|
[
|
|
'name' => 'Clicks',
|
|
'data' => $clicks
|
|
]
|
|
]
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Get device data for charts
|
|
*/
|
|
private function getDevicesData(int $campaignId, string $startDate, string $endDate): array
|
|
{
|
|
// Get real device data from database
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// For now, use campaign data to estimate device distribution
|
|
$campaign = $db->fetch("
|
|
SELECT
|
|
total_impressions,
|
|
total_clicks,
|
|
disable_mobile,
|
|
disable_desktop
|
|
FROM advertising_campaigns
|
|
WHERE id = ? AND status >= 0
|
|
", [$campaignId]);
|
|
|
|
$totalImpressions = (int)($campaign['total_impressions'] ?? 0);
|
|
$totalClicks = (int)($campaign['total_clicks'] ?? 0);
|
|
|
|
// Estimate device distribution based on campaign settings
|
|
$devices = ['Desktop', 'Mobile', 'Tablet'];
|
|
$impressions = [];
|
|
$clicks = [];
|
|
|
|
if ($campaign['disable_mobile'] ?? false) {
|
|
$impressions = [$totalImpressions * 0.8, 0, $totalImpressions * 0.2];
|
|
$clicks = [$totalClicks * 0.8, 0, $totalClicks * 0.2];
|
|
} elseif ($campaign['disable_desktop'] ?? false) {
|
|
$impressions = [0, $totalImpressions * 0.7, $totalImpressions * 0.3];
|
|
$clicks = [0, $totalClicks * 0.7, $totalClicks * 0.3];
|
|
} else {
|
|
$impressions = [$totalImpressions * 0.4, $totalImpressions * 0.5, $totalImpressions * 0.1];
|
|
$clicks = [$totalClicks * 0.4, $totalClicks * 0.5, $totalClicks * 0.1];
|
|
}
|
|
|
|
return [
|
|
'categories' => $devices,
|
|
'series' => [
|
|
[
|
|
'name' => 'Impressions',
|
|
'data' => array_map('intval', $impressions)
|
|
],
|
|
[
|
|
'name' => 'Clicks',
|
|
'data' => array_map('intval', $clicks)
|
|
]
|
|
]
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Get campaign tables data
|
|
*/
|
|
private function getCampaignTables(int $campaignId, string $startDate, string $endDate): array
|
|
{
|
|
// Get real table data from database
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
$data = $db->fetchAll("
|
|
SELECT
|
|
DATE(created_at) as date,
|
|
total_impressions as impressions,
|
|
total_clicks as clicks,
|
|
CASE
|
|
WHEN total_impressions > 0
|
|
THEN ROUND(total_clicks * 100.0 / total_impressions, 2)
|
|
ELSE 0
|
|
END as ctr,
|
|
0 as revenue
|
|
FROM advertising_campaigns
|
|
WHERE id = ?
|
|
AND created_at >= DATE_SUB(CURDATE(), INTERVAL 10 DAY)
|
|
ORDER BY created_at DESC
|
|
LIMIT 10
|
|
", [$campaignId]);
|
|
|
|
// If no data, create fallback
|
|
if (empty($data)) {
|
|
for ($i = 0; $i < 10; $i++) {
|
|
$date = date('Y-m-d', strtotime("-{$i} days"));
|
|
$data[] = [
|
|
'date' => $date,
|
|
'impressions' => 0,
|
|
'clicks' => 0,
|
|
'ctr' => 0,
|
|
'revenue' => 0
|
|
];
|
|
}
|
|
}
|
|
|
|
return [
|
|
'headers' => ['Date', 'Impressions', 'Clicks', 'CTR', 'Revenue'],
|
|
'data' => array_map(function($row) {
|
|
return [
|
|
$row['date'],
|
|
number_format($row['impressions']),
|
|
number_format($row['clicks']),
|
|
number_format($row['ctr'], 2) . '%',
|
|
'$' . number_format($row['revenue'], 2)
|
|
];
|
|
}, $data)
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Get available domains for filtering
|
|
*/
|
|
private function getAvailableDomains(int $campaignId): array
|
|
{
|
|
// Get real domains from database
|
|
$db = DatabaseManager::getInstance();
|
|
$domains = $db->fetchAll(
|
|
"SELECT DISTINCT domain FROM advertising_site_domains WHERE campaign_id = ?",
|
|
[$campaignId]
|
|
);
|
|
|
|
return array_column($domains, 'domain') ?: ['No domains available'];
|
|
}
|
|
|
|
/**
|
|
* Get status class for UI
|
|
*/
|
|
private function getStatusClass(string $status): string
|
|
{
|
|
return match($status) {
|
|
'active' => 'success',
|
|
'paused' => 'warning',
|
|
'inactive' => 'danger',
|
|
default => 'secondary'
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Get status display text
|
|
*/
|
|
private function getStatusDisplay(string $status): string
|
|
{
|
|
return match($status) {
|
|
'active' => 'Active',
|
|
'paused' => 'Paused',
|
|
'inactive' => 'Inactive',
|
|
default => 'Unknown'
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Gerar script com deteção configurável de marca
|
|
*/
|
|
public function generateScriptWithBrandDetection(): void
|
|
{
|
|
try {
|
|
$this->requireAuth();
|
|
|
|
$campaignId = (int)InputSanitizer::get('campaign_id', 'POST', 0);
|
|
|
|
if (!$campaignId) {
|
|
$this->errorResponse('ID da campanha é obrigatório', 422);
|
|
return;
|
|
}
|
|
|
|
$scriptBuilderService = new ScriptBuilderService();
|
|
$result = $scriptBuilderService->generateScriptWithBrandDetection($campaignId);
|
|
|
|
if ($result['success']) {
|
|
$this->successResponse($result, 'Script gerado com sucesso com deteção configurável de marca');
|
|
} else {
|
|
$this->errorResponse($result['error'] ?? 'Erro ao gerar script', 500);
|
|
}
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_generate_script_with_detection']);
|
|
$this->errorResponse('Erro ao gerar script com deteção', 500);
|
|
}
|
|
}
|
|
}
|