- Add source maps and license files for compiled assets - Add debug and test files for development - Complete Git repository with all necessary files for MoneyFlix project
2671 lines
103 KiB
PHP
2671 lines
103 KiB
PHP
<?php
|
|
namespace App\Modules\Advertising\Controllers;
|
|
|
|
use App\Core\BaseController;
|
|
use App\Core\ErrorReporter;
|
|
use App\Core\Sanitize;
|
|
use App\Core\InputSanitizer;
|
|
use App\Core\DatabaseManager;
|
|
use App\Core\Auth;
|
|
use App\Modules\Advertising\Models\CampaignModel;
|
|
use App\Modules\Advertising\Models\TrackingModel;
|
|
use App\Modules\Advertising\Services\AdvertisingActivityLogger;
|
|
use App\Modules\Advertising\Services\MultiBookService;
|
|
use Visus\Cuid2\Cuid2;
|
|
|
|
class AdvertisingApiController extends BaseController
|
|
{
|
|
public function __construct()
|
|
{
|
|
parent::__construct('Advertising');
|
|
}
|
|
|
|
/**
|
|
* Get authenticated user ID with validation
|
|
*/
|
|
private function getAuthenticatedUserId(): int
|
|
{
|
|
$userId = \App\Core\Auth::id();
|
|
if (!$userId) {
|
|
throw new \Exception('Utilizador não autenticado');
|
|
}
|
|
return $userId;
|
|
}
|
|
|
|
public function getCampaigns(): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
$filters = [
|
|
'status' => InputSanitizer::get('status', 'GET', ''),
|
|
'type' => InputSanitizer::get('type', 'GET', ''),
|
|
'search' => InputSanitizer::get('search', 'GET', '')
|
|
];
|
|
|
|
$campaignModel = new \App\Modules\Advertising\Models\CampaignModel();
|
|
$campaigns = $campaignModel->getAll($filters);
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $campaigns
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_api_get_campaigns']);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
|
|
}
|
|
}
|
|
|
|
public function createCampaign(): void
|
|
{
|
|
try {
|
|
$this->requireAuth();
|
|
|
|
// ✅ NOVO: Validação automática usando ValidatorFactory
|
|
$validation = $this->validatePostAutoOrFail('campaign.create');
|
|
|
|
// Se chegou aqui, a validação passou - dados já sanitizados
|
|
$input = $validation['data'];
|
|
|
|
$campaignModel = new \App\Modules\Advertising\Models\CampaignModel();
|
|
$success = $campaignModel->create($input);
|
|
|
|
if ($success) {
|
|
// Log de atividade
|
|
$userId = $this->getAuthenticatedUserId();
|
|
$activityLogger = $this->resolveModuleService('service.AdvertisingActivityLogger');
|
|
$activityLogger::log('create', 'campaign', (int)$campaignModel->getDb()->lastInsertId(), $userId, 'Campanha criada via API', [
|
|
'name' => $input['name'] ?? 'N/A'
|
|
]);
|
|
|
|
$this->successResponse(['id' => $campaignModel->getDb()->lastInsertId()], 'Campanha criada com sucesso');
|
|
} else {
|
|
$this->errorResponse('Erro ao criar campanha');
|
|
}
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_api_create_campaign']);
|
|
$this->errorResponse('Internal server error', 500);
|
|
}
|
|
}
|
|
|
|
public function getCampaign(int $id): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
if ($id <= 0) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'ID inválido']);
|
|
return;
|
|
}
|
|
|
|
$campaignModel = new \App\Modules\Advertising\Models\CampaignModel();
|
|
$campaign = $campaignModel->getById($id);
|
|
|
|
if (!$campaign) {
|
|
http_response_code(404);
|
|
echo json_encode(['success' => false, 'message' => 'Campanha não encontrada']);
|
|
return;
|
|
}
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $campaign
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_api_get_campaign', 'id' => $id]);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
|
|
}
|
|
}
|
|
|
|
public function updateCampaign(int $id): void
|
|
{
|
|
try {
|
|
$this->requireAuth();
|
|
|
|
// ✅ NOVO: Validação automática usando ValidatorFactory
|
|
$validation = $this->validatePostAutoOrFail('campaign.update');
|
|
|
|
// Se chegou aqui, a validação passou - dados já sanitizados
|
|
$input = $validation['data'];
|
|
|
|
// Construir query dinamicamente baseado nos campos fornecidos
|
|
$fields = [];
|
|
$params = [];
|
|
|
|
$allowedFields = [
|
|
'name', 'alias', 'seller_id', 'category', 'observations',
|
|
'description', 'status', 'budget', 'budget_type',
|
|
'start_date', 'end_date', 'has_end_date', 'expire_hours', 'expire_mobile_hours',
|
|
'wait_seconds', 'trigger_timer_seconds', 'iframe_url', 'timezone',
|
|
'targeting_rules', 'disabled_countries', 'allowed_countries', 'allowed_formats',
|
|
'allow_subdomains', 'hide_referer', 'disable_mobile', 'disable_desktop',
|
|
'theme', 'pricing_info', 'garbage_tracker_url', 'frequency_cap', 'frequency_period', 'region'
|
|
];
|
|
|
|
foreach ($allowedFields as $field) {
|
|
if (array_key_exists($field, $input)) {
|
|
$fields[] = "$field = ?";
|
|
$params[] = $input[$field];
|
|
}
|
|
}
|
|
|
|
if (empty($fields)) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'Nenhum campo para atualizar']);
|
|
return;
|
|
}
|
|
|
|
// Adicionar updated_at
|
|
$fields[] = "updated_at = CURRENT_TIMESTAMP";
|
|
|
|
// Adicionar ID no final dos parâmetros
|
|
$params[] = $id;
|
|
|
|
$sql = "UPDATE advertising_campaigns SET " . implode(', ', $fields) . " WHERE id = ? AND deleted_at IS NULL";
|
|
|
|
if (DatabaseManager::getInstance()->query($sql, $params)) {
|
|
$this->successResponse([], 'Campanha atualizada com sucesso');
|
|
} else {
|
|
$this->errorResponse('Erro ao atualizar campanha');
|
|
}
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_api_update_campaign', 'id' => $id]);
|
|
$this->errorResponse('Internal server error', 500);
|
|
}
|
|
}
|
|
|
|
public function deleteCampaign(int $id): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
$campaignModel = new \App\Modules\Advertising\Models\CampaignModel();
|
|
$success = $campaignModel->delete($id);
|
|
|
|
if ($success) {
|
|
echo json_encode(['success' => true, 'message' => 'Campanha eliminada com sucesso']);
|
|
} else {
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao eliminar campanha']);
|
|
}
|
|
}
|
|
|
|
public function trackView(): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
|
|
if (!$input || !isset($input['tracker_id']) || !isset($input['creative_id'])) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
|
|
return;
|
|
}
|
|
|
|
$ipAddress = $_SERVER['REMOTE_ADDR'] ?? '';
|
|
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
|
|
$referer = $_SERVER['HTTP_REFERER'] ?? '';
|
|
|
|
// Verificar se IP está bloqueado
|
|
if (new \App\Modules\Advertising\Models\TrackingModel()->isIpBlocked($ipAddress)) {
|
|
http_response_code(403);
|
|
echo json_encode(['success' => false, 'message' => 'IP blocked']);
|
|
return;
|
|
}
|
|
|
|
// Analisar fonte de tráfego
|
|
$trafficAnalysis = new \App\Modules\Advertising\Models\TrackingModel()->analyzeTrafficSource($userAgent, $referer);
|
|
$sessionId = session_id() ?: (string) new \Visus\Cuid2\Cuid2();
|
|
|
|
// Verificar se é app bloqueada (Facebook, Instagram, etc.)
|
|
if (new \App\Modules\Advertising\Models\TrackingModel()->isAppBlocked($userAgent, $referer)) {
|
|
new \App\Modules\Advertising\Models\TrackingModel()->recordTrafficAnalysis($trafficAnalysis, $sessionId, $ipAddress, $userAgent, $referer, 'App blocked');
|
|
http_response_code(403);
|
|
echo json_encode(['success' => false, 'message' => 'App blocked']);
|
|
return;
|
|
}
|
|
|
|
// Verificar se é bot traffic
|
|
if (new \App\Modules\Advertising\Models\TrackingModel()->isBotTraffic($userAgent)) {
|
|
new \App\Modules\Advertising\Models\TrackingModel()->recordTrafficAnalysis($trafficAnalysis, $sessionId, $ipAddress, $userAgent, $referer, 'Bot traffic');
|
|
http_response_code(403);
|
|
echo json_encode(['success' => false, 'message' => 'Bot traffic detected']);
|
|
return;
|
|
}
|
|
|
|
// Registar análise de tráfego válido
|
|
new \App\Modules\Advertising\Models\TrackingModel()->recordTrafficAnalysis($trafficAnalysis, $sessionId, $ipAddress, $userAgent, $referer);
|
|
|
|
$trackingData = array_merge($input, [
|
|
'ip_address' => $ipAddress,
|
|
'ip_long' => ip2long($ipAddress) ?: 0,
|
|
'user_agent' => $userAgent,
|
|
'referer' => $referer,
|
|
'session_id' => session_id() ?: (string) new \Visus\Cuid2\Cuid2(),
|
|
'device_type' => $trafficAnalysis['is_mobile'] ? 'mobile' : 'desktop',
|
|
'browser' => $trafficAnalysis['browser'],
|
|
'platform' => $trafficAnalysis['platform']
|
|
]);
|
|
|
|
$success = new \App\Modules\Advertising\Models\TrackingModel()->recordView(
|
|
(int) $input['tracker_id'],
|
|
(int) $input['creative_id'],
|
|
$trackingData
|
|
);
|
|
|
|
if ($success) {
|
|
echo json_encode(['success' => true]);
|
|
} else {
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Error recording view']);
|
|
}
|
|
}
|
|
|
|
public function trackClick(): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
|
|
if (!$input || !isset($input['tracker_id']) || !isset($input['creative_id'])) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
|
|
return;
|
|
}
|
|
|
|
$ipAddress = $_SERVER['REMOTE_ADDR'] ?? '';
|
|
|
|
// Verificar fraude
|
|
if (new \App\Modules\Advertising\Models\TrackingModel()->detectFraud($ipAddress)) {
|
|
new \App\Modules\Advertising\Models\TrackingModel()->recordFraudDetection($ipAddress, 'click_spam', 'Too many clicks in short time');
|
|
http_response_code(403);
|
|
echo json_encode(['success' => false, 'message' => 'Fraud detected']);
|
|
return;
|
|
}
|
|
|
|
$trackingData = array_merge($input, [
|
|
'ip_address' => $ipAddress,
|
|
'ip_long' => ip2long($ipAddress) ?: 0,
|
|
'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? null,
|
|
'referer' => $_SERVER['HTTP_REFERER'] ?? null,
|
|
'session_id' => session_id() ?: (string) new \Visus\Cuid2\Cuid2()
|
|
]);
|
|
|
|
$success = new \App\Modules\Advertising\Models\TrackingModel()->recordClick(
|
|
(int) $input['tracker_id'],
|
|
(int) $input['creative_id'],
|
|
$trackingData
|
|
);
|
|
|
|
if ($success) {
|
|
echo json_encode(['success' => true]);
|
|
} else {
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Error recording click']);
|
|
}
|
|
}
|
|
|
|
public function trackRegister(): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
|
|
if (!$input || !isset($input['tracker_id']) || !isset($input['creative_id'])) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
|
|
return;
|
|
}
|
|
|
|
$ipAddress = $_SERVER['REMOTE_ADDR'] ?? '';
|
|
|
|
$trackingData = array_merge($input, [
|
|
'ip_address' => $ipAddress,
|
|
'ip_long' => ip2long($ipAddress) ?: 0,
|
|
'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? null,
|
|
'referer' => $_SERVER['HTTP_REFERER'] ?? null,
|
|
'session_id' => session_id() ?: (string) new \Visus\Cuid2\Cuid2()
|
|
]);
|
|
|
|
$success = new \App\Modules\Advertising\Models\TrackingModel()->recordRegister(
|
|
(int) $input['tracker_id'],
|
|
(int) $input['creative_id'],
|
|
$trackingData
|
|
);
|
|
|
|
if ($success) {
|
|
echo json_encode(['success' => true]);
|
|
} else {
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Error recording register']);
|
|
}
|
|
}
|
|
|
|
public function getCampaignStats(int $campaignId): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
$startDate = InputSanitizer::get('start_date', 'GET', '');
|
|
$endDate = InputSanitizer::get('end_date', 'GET', '');
|
|
|
|
$stats = (new \App\Modules\Advertising\Models\CampaignModel())->getCampaignStats($campaignId, $startDate, $endDate);
|
|
$eventStats = new \App\Modules\Advertising\Models\TrackingModel()->getEventStats($campaignId, $startDate, $endDate);
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => [
|
|
'campaign_stats' => $stats,
|
|
'event_stats' => $eventStats
|
|
]
|
|
]);
|
|
}
|
|
|
|
public function getGeoStats(int $campaignId): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
$startDate = InputSanitizer::get('start_date', 'GET', '');
|
|
$endDate = InputSanitizer::get('end_date', 'GET', '');
|
|
|
|
$geoStats = new \App\Modules\Advertising\Models\TrackingModel()->getGeoStats($campaignId, $startDate, $endDate);
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $geoStats
|
|
]);
|
|
}
|
|
|
|
public function getDeviceStats(int $campaignId): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
$startDate = InputSanitizer::get('start_date', 'GET', '');
|
|
$endDate = InputSanitizer::get('end_date', 'GET', '');
|
|
|
|
$deviceStats = new \App\Modules\Advertising\Models\TrackingModel()->getDeviceStats($campaignId, $startDate, $endDate);
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $deviceStats
|
|
]);
|
|
}
|
|
|
|
public function getTrafficStats(): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
$startDate = InputSanitizer::get('start_date', 'GET', '');
|
|
$endDate = InputSanitizer::get('end_date', 'GET', '');
|
|
|
|
$stats = new \App\Modules\Advertising\Models\TrackingModel()->getTrafficStats($startDate, $endDate);
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $stats
|
|
]);
|
|
}
|
|
|
|
public function getBlockedAppsStats(): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
$stats = new \App\Modules\Advertising\Models\TrackingModel()->getBlockedAppsStats();
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $stats
|
|
]);
|
|
}
|
|
|
|
public function getDashboardStats(): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
try {
|
|
// ✅ PERFORMANCE: Use MySQL COUNT() instead of PHP processing
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Single efficient query to get all campaign stats
|
|
$statsQuery = "SELECT
|
|
COUNT(*) as total_campaigns,
|
|
SUM(IF(status = 'active', 1, 0)) as active_campaigns,
|
|
SUM(IF(status = 'paused', 1, 0)) as paused_campaigns,
|
|
SUM(IF(end_date IS NULL OR end_date = '', 1, 0)) as no_end_date
|
|
FROM advertising_campaigns
|
|
WHERE status >= 0";
|
|
|
|
$stats = $db->fetch($statsQuery);
|
|
|
|
$totalCampaigns = (int)($stats['total_campaigns'] ?? 0);
|
|
$activeCampaigns = (int)($stats['active_campaigns'] ?? 0);
|
|
$pausedCampaigns = (int)($stats['paused_campaigns'] ?? 0);
|
|
$noEndDateCampaigns = (int)($stats['no_end_date'] ?? 0);
|
|
|
|
// Estatísticas de eventos de hoje
|
|
$trackingModel = new \App\Modules\Advertising\Models\TrackingModel();
|
|
$impressionsToday = $trackingModel->getTodayViewsCount();
|
|
$clicksToday = $trackingModel->getTodayClicksCount();
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => [
|
|
'total_campaigns' => $totalCampaigns,
|
|
'active_campaigns' => $activeCampaigns,
|
|
'paused_campaigns' => $pausedCampaigns,
|
|
'no_end_date_campaigns' => $noEndDateCampaigns,
|
|
'impressions_today' => $impressionsToday,
|
|
'clicks_today' => $clicksToday
|
|
]
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_api_get_dashboard_stats']);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao obter estatísticas do painel']);
|
|
}
|
|
}
|
|
|
|
public function getDailyPerformance(): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
try {
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Get views from advertising_events where event_type = 'view'
|
|
$sql = "SELECT DATE(timestamp) as date, COUNT(*) as views
|
|
FROM advertising_events
|
|
WHERE event_type = 'view'
|
|
GROUP BY DATE(timestamp)
|
|
ORDER BY date DESC
|
|
LIMIT 14";
|
|
$views = $db->fetchAll($sql);
|
|
|
|
// Get clicks from advertising_events where event_type = 'click'
|
|
$sql = "SELECT DATE(timestamp) as date, COUNT(*) as clicks
|
|
FROM advertising_events
|
|
WHERE event_type = 'click'
|
|
GROUP BY DATE(timestamp)
|
|
ORDER BY date DESC
|
|
LIMIT 14";
|
|
$clicks = $db->fetchAll($sql);
|
|
|
|
// Merge views and clicks by date
|
|
$data = [];
|
|
foreach ($views as $v) {
|
|
$data[$v['date']] = [
|
|
'date' => $v['date'],
|
|
'views' => (int)$v['views'],
|
|
'clicks' => 0
|
|
];
|
|
}
|
|
foreach ($clicks as $c) {
|
|
if (!isset($data[$c['date']])) {
|
|
$data[$c['date']] = [
|
|
'date' => $c['date'],
|
|
'views' => 0,
|
|
'clicks' => (int)$c['clicks']
|
|
];
|
|
} else {
|
|
$data[$c['date']]['clicks'] = (int)$c['clicks'];
|
|
}
|
|
}
|
|
// Ordenar por data ascendente
|
|
ksort($data);
|
|
echo json_encode(['success' => true, 'data' => array_values($data)]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_api_get_daily_performance']);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao obter desempenho diário']);
|
|
}
|
|
}
|
|
|
|
public function generateScript(int $campaignId): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
$db = DatabaseManager::getInstance();
|
|
$campaign = $db->fetch(
|
|
"SELECT\n id, cuid, name, alias, status, type, budget, start_date, end_date, created_by, created_at, updated_at\n FROM\n advertising_campaigns\n WHERE\n id = ? AND deleted_at IS NULL",
|
|
[$campaignId]
|
|
);
|
|
|
|
if (!$campaign) {
|
|
http_response_code(404);
|
|
echo json_encode(['success' => false, 'message' => 'Campanha não encontrada']);
|
|
return;
|
|
}
|
|
|
|
// Generate real script for campaign using ScriptBuilderService
|
|
try {
|
|
$scriptBuilder = new \App\Modules\Advertising\Services\ScriptBuilderService();
|
|
$result = $scriptBuilder->generateScript($campaignId);
|
|
|
|
if ($result['success']) {
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => [
|
|
'script_id' => $result['script_id'],
|
|
'script_hash' => $result['script_hash'],
|
|
'file_name' => $result['file_name'],
|
|
'script_preview' => $result['script_preview'],
|
|
'campaign' => $campaign
|
|
]
|
|
]);
|
|
} else {
|
|
echo json_encode([
|
|
'success' => false,
|
|
'message' => 'Erro ao gerar script: ' . $result['error']
|
|
]);
|
|
}
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_api_generate_script']);
|
|
echo json_encode([
|
|
'success' => false,
|
|
'message' => 'Erro ao gerar script: ' . $e->getMessage()
|
|
]);
|
|
}
|
|
}
|
|
|
|
public function deployScript(): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
|
|
if (!$input || !isset($input['campaign_id'])) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'Missing campaign_id']);
|
|
return;
|
|
}
|
|
|
|
// Deploy script to CDN/Server
|
|
$campaignId = (int)$input['campaign_id'];
|
|
|
|
try {
|
|
// Buscar o script mais recente da campanha
|
|
$db = DatabaseManager::getInstance();
|
|
$script = $db->fetch("
|
|
SELECT * FROM advertising_scripts
|
|
WHERE campaign_id = ?
|
|
ORDER BY created_at DESC
|
|
LIMIT 1
|
|
", [$campaignId]);
|
|
|
|
if (!$script) {
|
|
echo json_encode([
|
|
'success' => false,
|
|
'message' => 'Nenhum script encontrado para esta campanha'
|
|
]);
|
|
return;
|
|
}
|
|
|
|
// Usar ScriptBuilderService para deployment
|
|
$scriptBuilder = new \App\Modules\Advertising\Services\ScriptBuilderService();
|
|
$result = $scriptBuilder->deployScript($script['id']);
|
|
|
|
if ($result['success']) {
|
|
echo json_encode([
|
|
'success' => true,
|
|
'message' => 'Script deployed successfully',
|
|
'data' => [
|
|
'campaign_id' => $campaignId,
|
|
'script_id' => $script['id'],
|
|
'deployment_url' => $result['deployment_url'] ?? null,
|
|
'status' => 'deployed'
|
|
]
|
|
]);
|
|
} else {
|
|
echo json_encode([
|
|
'success' => false,
|
|
'message' => 'Erro no deployment: ' . $result['error']
|
|
]);
|
|
}
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_api_deploy_script']);
|
|
echo json_encode([
|
|
'success' => false,
|
|
'message' => 'Erro no deployment: ' . $e->getMessage()
|
|
]);
|
|
}
|
|
}
|
|
|
|
public function getTopCampaigns(): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
try {
|
|
$db = DatabaseManager::getInstance();
|
|
$sql = "SELECT c.id, c.name, c.status,
|
|
0 as views, 0 as clicks, 0.00 as ctr
|
|
FROM advertising_campaigns c
|
|
WHERE c.deleted_at IS NULL AND c.status = 1
|
|
ORDER BY c.created_at DESC
|
|
LIMIT 10";
|
|
|
|
$campaigns = $db->fetchAll($sql);
|
|
echo json_encode(['success' => true, 'data' => $campaigns]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_api_get_top_campaigns']);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro: ' . $e->getMessage()]);
|
|
}
|
|
}
|
|
|
|
public function getCreatives(): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Parâmetros de paginação
|
|
$page = InputSanitizer::has('page', 'GET') ? InputSanitizer::integer('page', 'GET') : 1;
|
|
$limit = InputSanitizer::has('limit', 'GET') ? InputSanitizer::integer('limit', 'GET') : 20;
|
|
$offset = ($page - 1) * $limit;
|
|
|
|
// Filtros
|
|
$search = InputSanitizer::get('search', 'GET', '');
|
|
$format = InputSanitizer::get('format', 'GET', '');
|
|
$campaignId = InputSanitizer::integer('campaign', 'GET', 0);
|
|
|
|
// Construir query base
|
|
$sql = "
|
|
SELECT
|
|
c.id,
|
|
c.cuid,
|
|
c.name,
|
|
c.description,
|
|
c.width,
|
|
c.height,
|
|
c.is_active,
|
|
c.created_at,
|
|
c.updated_at,
|
|
c.creative_type as ad_type,
|
|
c.target_country,
|
|
c.view_url,
|
|
c.rotator_hash,
|
|
c.last_sync_at,
|
|
af.name as format_name,
|
|
camp.name as campaign_name
|
|
FROM advertising_creatives c
|
|
LEFT JOIN advertising_formats af ON c.format_id = af.id
|
|
LEFT JOIN advertising_trackers t ON c.id = t.creative_id
|
|
LEFT JOIN advertising_campaign_trackers ct ON t.id = ct.tracker_id
|
|
LEFT JOIN advertising_campaigns camp ON ct.campaign_id = camp.id
|
|
WHERE c.deleted_at IS NULL
|
|
";
|
|
|
|
$params = [];
|
|
|
|
// Aplicar filtros
|
|
if ($search) {
|
|
$sql .= " AND (c.name LIKE ? OR c.description LIKE ?)";
|
|
$searchTerm = '%' . $search . '%';
|
|
$params[] = $searchTerm;
|
|
$params[] = $searchTerm;
|
|
}
|
|
|
|
if ($format) {
|
|
$sql .= " AND c.format_id = ?";
|
|
$params[] = $format;
|
|
}
|
|
|
|
if ($campaignId > 0) {
|
|
$sql .= " AND ct.campaign_id = ?";
|
|
$params[] = $campaignId;
|
|
}
|
|
|
|
// Contar total de registos
|
|
$countSql = "SELECT COUNT(*) as total FROM (" . $sql . ") as subquery";
|
|
$totalResult = $db->fetch($countSql, $params);
|
|
$total = $totalResult['total'] ?? 0;
|
|
|
|
// Adicionar ordenação e paginação
|
|
$sql .= " ORDER BY c.created_at DESC LIMIT " . (int)$limit . " OFFSET " . (int)$offset;
|
|
|
|
// Executar query principal
|
|
$creatives = $db->fetchAll($sql, $params);
|
|
|
|
// Calcular metadados de paginação
|
|
$totalPages = ceil($total / $limit);
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $creatives ?: [],
|
|
'pagination' => [
|
|
'current_page' => $page,
|
|
'per_page' => $limit,
|
|
'total' => $total,
|
|
'total_pages' => $totalPages,
|
|
'has_next_page' => $page < $totalPages,
|
|
'has_prev_page' => $page > 1
|
|
]
|
|
]);
|
|
}
|
|
|
|
public function createCreative(): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
|
|
if (!$input || !isset($input['name']) || !isset($input['format_id'])) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'Dados inválidos']);
|
|
return;
|
|
}
|
|
|
|
$db = DatabaseManager::getInstance();
|
|
$cuid = (string) new Cuid2();
|
|
|
|
$success = $db->query("INSERT INTO advertising_creatives (cuid, format_id, name, file_name, file_path, file_size, mime_type, width, height, alt_text, is_active, script_id, creative_slug) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", [
|
|
$cuid,
|
|
$input['format_id'],
|
|
$input['name'],
|
|
$input['file_name'] ?? $input['name'] . '.html',
|
|
$input['file_path'] ?? '/creatives/' . $input['name'] . '.html',
|
|
$input['file_size'] ?? 1024,
|
|
$input['mime_type'] ?? 'text/html',
|
|
$input['width'] ?? 300,
|
|
$input['height'] ?? 250,
|
|
$input['alt_text'] ?? $input['name'],
|
|
$input['is_active'] ?? 1,
|
|
$input['script_id'] ?? null,
|
|
$input['creative_slug'] ?? $cuid
|
|
]);
|
|
|
|
if ($success) {
|
|
echo json_encode(['success' => true, 'message' => 'Criativo criado com sucesso']);
|
|
} else {
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao criar criativo']);
|
|
}
|
|
}
|
|
|
|
public function getCreative(int $id): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
$db = DatabaseManager::getInstance();
|
|
$creative = $db->fetch(
|
|
"SELECT
|
|
id, cuid, name, description, width, height, is_active, created_at, updated_at
|
|
FROM
|
|
advertising_creatives
|
|
WHERE
|
|
id = ?",
|
|
[$id]
|
|
);
|
|
|
|
if (!$creative) {
|
|
http_response_code(404);
|
|
echo json_encode(['success' => false, 'message' => 'Criativo não encontrado']);
|
|
return;
|
|
}
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $creative
|
|
]);
|
|
}
|
|
|
|
public function updateCreative(int $id): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
|
|
if (!$input) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'Dados inválidos']);
|
|
return;
|
|
}
|
|
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Buscar dados existentes
|
|
$existing = $db->fetch(
|
|
"SELECT
|
|
id, name, file_name, file_path, file_size, mime_type, width, height, alt_text, click_url, is_active, cdn_url
|
|
FROM
|
|
advertising_creatives
|
|
WHERE
|
|
id = ?",
|
|
[$id]
|
|
);
|
|
if (!$existing) {
|
|
http_response_code(404);
|
|
echo json_encode(['success' => false, 'message' => 'Criativo não encontrado']);
|
|
return;
|
|
}
|
|
|
|
$success = $db->query("UPDATE advertising_creatives SET name = ?, file_name = ?, file_path = ?, file_size = ?, mime_type = ?, width = ?, height = ?, alt_text = ?, click_url = ?, is_active = ?, cdn_url = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?", [
|
|
$input['name'] ?? $existing['name'],
|
|
$input['file_name'] ?? $existing['file_name'],
|
|
$input['file_path'] ?? $existing['file_path'],
|
|
$input['file_size'] ?? $existing['file_size'],
|
|
$input['mime_type'] ?? $existing['mime_type'],
|
|
$input['width'] ?? $existing['width'],
|
|
$input['height'] ?? $existing['height'],
|
|
$input['alt_text'] ?? $existing['alt_text'],
|
|
$input['click_url'] ?? $existing['click_url'],
|
|
$input['is_active'] ?? $existing['is_active'],
|
|
$input['cdn_url'] ?? $existing['cdn_url'],
|
|
$id
|
|
]);
|
|
|
|
if ($success) {
|
|
echo json_encode(['success' => true, 'message' => 'Criativo atualizado com sucesso']);
|
|
} else {
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao atualizar criativo']);
|
|
}
|
|
}
|
|
|
|
public function deleteCreative(int $id): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
$db = DatabaseManager::getInstance();
|
|
$success = $db->query("UPDATE advertising_creatives SET is_active = 0 WHERE id = ?", [$id]);
|
|
|
|
if ($success) {
|
|
echo json_encode(['success' => true, 'message' => 'Criativo eliminado com sucesso']);
|
|
} else {
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao eliminar criativo']);
|
|
}
|
|
}
|
|
|
|
public function getTrackers(): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
try {
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// ✅ CORRETO: Obter filtros e paginação
|
|
$filters = [
|
|
'search' => InputSanitizer::get('search', 'GET', ''),
|
|
'type' => InputSanitizer::get('type', 'GET', ''),
|
|
'status' => InputSanitizer::get('status', 'GET', ''),
|
|
'campaign' => InputSanitizer::integer('campaign', 'GET', 0)
|
|
];
|
|
|
|
$page = InputSanitizer::integer('page', 'GET', 1);
|
|
$limit = InputSanitizer::integer('limit', 'GET', 50); // Limite padrão de 50
|
|
$offset = ($page - 1) * $limit;
|
|
|
|
// ✅ CORRETO: Construir query com filtros e paginação
|
|
$whereConditions = ['t.is_active >= 0'];
|
|
$params = [];
|
|
|
|
if (!empty($filters['search'])) {
|
|
$whereConditions[] = '(t.name LIKE ? OR t.cuid LIKE ?)';
|
|
$searchTerm = '%' . $filters['search'] . '%';
|
|
$params[] = $searchTerm;
|
|
$params[] = $searchTerm;
|
|
}
|
|
|
|
if (!empty($filters['type'])) {
|
|
$whereConditions[] = 't.tracking_type = ?';
|
|
$params[] = $filters['type'];
|
|
}
|
|
|
|
if (!empty($filters['status'])) {
|
|
$whereConditions[] = 't.is_active = ?';
|
|
$params[] = $filters['status'] === 'active' ? 1 : 0;
|
|
}
|
|
|
|
if ($filters['campaign'] > 0) {
|
|
$whereConditions[] = 'ct.campaign_id = ?';
|
|
$params[] = $filters['campaign'];
|
|
}
|
|
|
|
$whereClause = implode(' AND ', $whereConditions);
|
|
|
|
// ✅ CORRETO: Query otimizada com JOIN apenas se necessário
|
|
if ($filters['campaign'] > 0) {
|
|
$sql = "
|
|
SELECT
|
|
t.id,
|
|
t.name,
|
|
t.cuid,
|
|
t.tracking_type as type,
|
|
t.is_active as status,
|
|
t.created_at,
|
|
t.updated_at,
|
|
c.name as campaign_name,
|
|
c.id as campaign_id
|
|
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 $whereClause
|
|
ORDER BY t.created_at DESC
|
|
LIMIT $limit OFFSET $offset
|
|
";
|
|
} else {
|
|
$sql = "
|
|
SELECT
|
|
t.id,
|
|
t.name,
|
|
t.cuid,
|
|
t.tracking_type as type,
|
|
t.is_active as status,
|
|
t.created_at,
|
|
t.updated_at,
|
|
c.name as campaign_name,
|
|
c.id as campaign_id
|
|
FROM advertising_trackers t
|
|
LEFT JOIN advertising_campaign_trackers ct ON t.id = ct.tracker_id
|
|
LEFT JOIN advertising_campaigns c ON ct.campaign_id = c.id
|
|
WHERE $whereClause
|
|
ORDER BY t.created_at DESC
|
|
LIMIT $limit OFFSET $offset
|
|
";
|
|
}
|
|
|
|
$trackers = $db->fetchAll($sql, $params);
|
|
|
|
// ✅ CORRETO: Contar total para paginação
|
|
$countSql = "
|
|
SELECT COUNT(*) as total
|
|
FROM advertising_trackers t
|
|
";
|
|
|
|
if ($filters['campaign'] > 0) {
|
|
$countSql .= "
|
|
JOIN advertising_campaign_trackers ct ON t.id = ct.tracker_id
|
|
JOIN advertising_campaigns c ON ct.campaign_id = c.id
|
|
";
|
|
} else {
|
|
$countSql .= "
|
|
LEFT JOIN advertising_campaign_trackers ct ON t.id = ct.tracker_id
|
|
LEFT JOIN advertising_campaigns c ON ct.campaign_id = c.id
|
|
";
|
|
}
|
|
|
|
$countSql .= " WHERE " . $whereClause;
|
|
|
|
// Remover limit e offset dos parâmetros para o count
|
|
array_pop($params); // Remove offset
|
|
array_pop($params); // Remove limit
|
|
|
|
$totalResult = $db->fetch($countSql, $params);
|
|
$total = $totalResult['total'] ?? 0;
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $trackers ?: [],
|
|
'pagination' => [
|
|
'page' => $page,
|
|
'limit' => $limit,
|
|
'total' => $total,
|
|
'pages' => ceil($total / $limit),
|
|
'has_more' => ($page * $limit) < $total
|
|
],
|
|
'filters' => $filters
|
|
]);
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, [
|
|
'context' => 'advertising_api_get_trackers',
|
|
'filters' => $filters ?? [],
|
|
'page' => $page ?? 1,
|
|
'limit' => $limit ?? 50
|
|
]);
|
|
http_response_code(500);
|
|
echo json_encode([
|
|
'success' => false,
|
|
'message' => 'Erro ao carregar trackers'
|
|
]);
|
|
}
|
|
}
|
|
|
|
public function getCountries(): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
try {
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Get most used countries from campaigns
|
|
$mostUsedCountries = $db->fetchAll("
|
|
SELECT allowed_countries as code, COUNT(*) as usage_count
|
|
FROM advertising_campaigns
|
|
WHERE allowed_countries IS NOT NULL
|
|
AND allowed_countries != ''
|
|
AND allowed_countries != 'AA'
|
|
GROUP BY allowed_countries
|
|
ORDER BY usage_count DESC
|
|
LIMIT 10
|
|
");
|
|
|
|
// Get country details for most used countries
|
|
$mostUsedCodes = array_column($mostUsedCountries, 'code');
|
|
$mostUsedCountriesDetails = [];
|
|
|
|
if (!empty($mostUsedCodes)) {
|
|
$placeholders = str_repeat('?,', count($mostUsedCodes) - 1) . '?';
|
|
$mostUsedCountriesDetails = $db->fetchAll("
|
|
SELECT code, name, full_name, continent_code
|
|
FROM countries
|
|
WHERE code IN ($placeholders)
|
|
ORDER BY FIELD(code, $placeholders)
|
|
", array_merge($mostUsedCodes, $mostUsedCodes));
|
|
}
|
|
|
|
// Get AA (All Countries) always first
|
|
$aaCountry = $db->fetch("
|
|
SELECT code, name, full_name, continent_code
|
|
FROM countries
|
|
WHERE code = 'AA'
|
|
");
|
|
|
|
// Combine AA + most used countries
|
|
$countries = [];
|
|
if ($aaCountry) {
|
|
$countries[] = $aaCountry;
|
|
}
|
|
$countries = array_merge($countries, $mostUsedCountriesDetails);
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $countries ?: [],
|
|
'most_used' => $mostUsedCountries
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_api_get_countries']);
|
|
http_response_code(500);
|
|
echo json_encode([
|
|
'success' => false,
|
|
'message' => 'Erro ao carregar países'
|
|
]);
|
|
}
|
|
}
|
|
|
|
public function createTracker(): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
|
|
if (!$input || !isset($input['name']) || !isset($input['format_id'])) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'Dados inválidos']);
|
|
return;
|
|
}
|
|
|
|
$db = DatabaseManager::getInstance();
|
|
$cuid = (string) new Cuid2();
|
|
|
|
$success = $db->query("INSERT INTO advertising_trackers (cuid, format_id, name, tracking_url, tracking_params, is_active) VALUES (?, ?, ?, ?, ?, ?)", [
|
|
$cuid,
|
|
$input['format_id'],
|
|
$input['name'],
|
|
$input['tracking_url'] ?? null,
|
|
$input['tracking_params'] ?? null,
|
|
$input['is_active'] ?? 1
|
|
]);
|
|
|
|
if ($success) {
|
|
// Log de atividade
|
|
$userId = $this->getAuthenticatedUserId();
|
|
$activityLogger = $this->resolveModuleService('service.AdvertisingActivityLogger');
|
|
$activityLogger::log('create', 'tracker', (int)$db->lastInsertId(), $userId, 'Tracker criado via API', [
|
|
'name' => $input['name'],
|
|
'format_id' => $input['format_id']
|
|
]);
|
|
|
|
echo json_encode(['success' => true, 'message' => 'Tracker criado com sucesso']);
|
|
} else {
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao criar tracker']);
|
|
}
|
|
}
|
|
|
|
public function getTracker(int $id): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
if ($id <= 0) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'ID inválido']);
|
|
return;
|
|
}
|
|
|
|
$db = DatabaseManager::getInstance();
|
|
$tracker = $db->fetch("
|
|
SELECT
|
|
t.id AS tracker_id,
|
|
t.name AS tracker_name,
|
|
t.cuid AS tracker_cuid,
|
|
t.brand_id AS brand_id,
|
|
t.landing_type_id AS landing_type_id,
|
|
t.creative_id AS creative_id,
|
|
t.tracking_url AS tracking_url,
|
|
t.final_tracking_url AS final_tracking_url,
|
|
t.tracking_params AS tracking_params,
|
|
t.tracking_type AS tracking_type,
|
|
t.is_active AS is_active,
|
|
t.created_at AS created_date,
|
|
t.updated_at AS updated_date,
|
|
b.name AS brand_name,
|
|
lt.name AS landing_type_name
|
|
FROM
|
|
advertising_trackers t
|
|
LEFT JOIN
|
|
advertising_brands b ON t.brand_id = b.id
|
|
LEFT JOIN
|
|
advertising_brand_landing_types lt ON t.landing_type_id = lt.id
|
|
WHERE
|
|
t.id = ?
|
|
", [$id]);
|
|
|
|
if (!$tracker) {
|
|
http_response_code(404);
|
|
echo json_encode(['success' => false, 'message' => 'Tracker não encontrado']);
|
|
return;
|
|
}
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $tracker
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_api_get_tracker', 'tracker_id' => $id]);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
|
|
}
|
|
}
|
|
|
|
public function updateTracker(int $id): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
|
|
if (!$input) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'Dados inválidos']);
|
|
return;
|
|
}
|
|
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Buscar dados existentes
|
|
$existing = $db->fetch(
|
|
"SELECT
|
|
id, name, cuid, tracking_url, final_tracking_url, tracking_params, tracking_type, is_active
|
|
FROM
|
|
advertising_trackers
|
|
WHERE
|
|
id = ?",
|
|
[$id]
|
|
);
|
|
if (!$existing) {
|
|
http_response_code(404);
|
|
echo json_encode(['success' => false, 'message' => 'Tracker não encontrado']);
|
|
return;
|
|
}
|
|
|
|
// Preparar campos para atualização
|
|
$fields = [];
|
|
$params = [];
|
|
|
|
// Campos que podem ser atualizados
|
|
$allowedFields = [
|
|
'name', 'brand_id', 'landing_type_id', 'final_tracking_url',
|
|
'creative_id', 'creative_override', 'tracking_url', 'tracking_params',
|
|
'is_active'
|
|
];
|
|
|
|
foreach ($allowedFields as $field) {
|
|
if (array_key_exists($field, $input)) {
|
|
$fields[] = "$field = ?";
|
|
$params[] = $input[$field];
|
|
}
|
|
}
|
|
|
|
// Se não há campos para atualizar
|
|
if (empty($fields)) {
|
|
echo json_encode(['success' => true, 'message' => 'Nenhuma alteração necessária']);
|
|
return;
|
|
}
|
|
|
|
// Adicionar updated_at
|
|
$fields[] = "updated_at = CURRENT_TIMESTAMP";
|
|
|
|
// Adicionar ID no final
|
|
$params[] = $id;
|
|
|
|
$sql = "UPDATE advertising_trackers SET " . implode(', ', $fields) . " WHERE id = ?";
|
|
$success = $db->query($sql, $params);
|
|
|
|
if ($success) {
|
|
// Log de atividade
|
|
$userId = $this->getAuthenticatedUserId();
|
|
$activityLogger = $this->resolveModuleService('service.AdvertisingActivityLogger');
|
|
$activityLogger::log('update', 'tracker', (int)$id, $userId, 'Tracker atualizado via API', [
|
|
'fields' => array_keys($input)
|
|
]);
|
|
|
|
echo json_encode(['success' => true, 'message' => 'Tracker atualizado com sucesso']);
|
|
} else {
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao atualizar tracker']);
|
|
}
|
|
}
|
|
|
|
public function deleteTracker(int $id): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Buscar dados do tracker antes de eliminar
|
|
$tracker = $db->fetch(
|
|
"SELECT
|
|
id, name, cuid, brand_id, landing_type_id, creative_id, tracking_url, final_tracking_url, tracking_params, tracking_type, is_active, created_at, updated_at
|
|
FROM
|
|
advertising_trackers
|
|
WHERE
|
|
id = ?",
|
|
[$id]
|
|
);
|
|
|
|
$success = $db->query("UPDATE advertising_trackers SET is_active = 0 WHERE id = ?", [$id]);
|
|
|
|
if ($success) {
|
|
// Log de atividade
|
|
$userId = $this->getAuthenticatedUserId();
|
|
$activityLogger = $this->resolveModuleService('service.AdvertisingActivityLogger');
|
|
$activityLogger::log('delete', 'tracker', (int)$id, $userId, 'Tracker eliminado via API', [
|
|
'name' => $tracker['name'] ?? 'N/A'
|
|
]);
|
|
|
|
echo json_encode(['success' => true, 'message' => 'Tracker eliminado com sucesso']);
|
|
} else {
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao eliminar tracker']);
|
|
}
|
|
}
|
|
|
|
public function getCampaignTrackers(int $id): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Buscar trackers associados à campanha via tabela de relacionamento
|
|
$sql = "SELECT t.*
|
|
FROM advertising_trackers t
|
|
INNER JOIN advertising_campaign_trackers ct ON t.id = ct.tracker_id
|
|
WHERE ct.campaign_id = ? AND t.is_active = 1
|
|
ORDER BY ct.order ASC";
|
|
|
|
$trackers = $db->fetchAll($sql, [$id]);
|
|
|
|
// Se não houver trackers na tabela de relacionamento, buscar todos os trackers ativos
|
|
if (empty($trackers)) {
|
|
$trackers = $db->fetchAll(
|
|
"SELECT id, name, cuid, tracking_type, is_active, created_at\n+ FROM advertising_trackers\n+ WHERE is_active = 1\n+ ORDER BY id ASC\n+ LIMIT 10"
|
|
);
|
|
}
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $trackers ?: []
|
|
]);
|
|
}
|
|
|
|
public function updateCampaignTrackers(int $id): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
|
|
if (!isset($input['trackers']) || !is_array($input['trackers'])) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'Dados inválidos']);
|
|
return;
|
|
}
|
|
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
try {
|
|
// Iniciar transação
|
|
$db->query("START TRANSACTION");
|
|
|
|
// Soft delete associações existentes (update status to -1)
|
|
$db->query("UPDATE advertising_campaign_trackers SET status = '-1', updated_at = CURRENT_TIMESTAMP WHERE campaign_id = ?", [$id]);
|
|
|
|
// Adicionar novas associações
|
|
foreach ($input['trackers'] as $index => $tracker) {
|
|
if (isset($tracker['id']) && !str_starts_with($tracker['id'], 'new_')) {
|
|
// Tracker existente - apenas criar associação
|
|
$db->query("INSERT INTO advertising_campaign_trackers (campaign_id, tracker_id, `order`) VALUES (?, ?, ?)",
|
|
[$id, $tracker['id'], $index]);
|
|
|
|
// Atualizar dados do tracker se necessário
|
|
$db->query("UPDATE advertising_trackers SET
|
|
name = ?, format_id = ?,
|
|
tracking_url = ?, is_active = ?, updated_at = CURRENT_TIMESTAMP
|
|
WHERE id = ?", [
|
|
$tracker['name'],
|
|
$tracker['format_id'],
|
|
$tracker['tracking_url'] ?? null,
|
|
$tracker['is_active'],
|
|
$tracker['id']
|
|
]);
|
|
} else {
|
|
// Novo tracker - criar primeiro
|
|
$cuid = (string) new Cuid2();
|
|
|
|
$db->query("INSERT INTO advertising_trackers
|
|
(cuid, format_id, name, tracking_url, is_active)
|
|
VALUES (?, ?, ?, ?, ?)", [
|
|
$cuid,
|
|
$tracker['format_id'],
|
|
$tracker['name'],
|
|
$tracker['tracking_url'] ?? null,
|
|
$tracker['is_active']
|
|
]);
|
|
|
|
$newTrackerId = $db->lastInsertId();
|
|
|
|
// Criar associação
|
|
$db->query("INSERT INTO advertising_campaign_trackers (campaign_id, tracker_id, `order`) VALUES (?, ?, ?)",
|
|
[$id, $newTrackerId, $index]);
|
|
}
|
|
}
|
|
|
|
// Confirmar transação
|
|
$db->query("COMMIT");
|
|
|
|
echo json_encode(['success' => true, 'message' => 'Trackers atualizados com sucesso']);
|
|
|
|
} catch (\Exception $e) {
|
|
$db->query("ROLLBACK");
|
|
ErrorReporter::report($e, ['context' => 'advertising_api_update_campaign_trackers', 'campaign_id' => $id]);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao atualizar trackers: ' . $e->getMessage()]);
|
|
}
|
|
}
|
|
|
|
public function serveAd(): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
$campaignId = Sanitize::string($_GET['campaign'] ?? null);
|
|
$format = Sanitize::string($_GET['format'] ?? '300x250');
|
|
|
|
if (!$campaignId) {
|
|
echo json_encode(['success' => false, 'message' => 'Campaign ID required']);
|
|
return;
|
|
}
|
|
|
|
// Obter dimensões reais a partir da BD
|
|
$dimensions = $this->getFormatDimensions($format);
|
|
if (!$dimensions) {
|
|
http_response_code(404);
|
|
echo json_encode(['success' => false, 'message' => 'Formato não encontrado']);
|
|
return;
|
|
}
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'campaign_id' => $campaignId,
|
|
'format' => $format,
|
|
'dimensions' => $dimensions
|
|
]);
|
|
}
|
|
|
|
private function getFormatDimensions(string $format): ?array
|
|
{
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Se vier no formato 300x250, procurar por width/height
|
|
if (preg_match('/^(\d+)x(\d+)$/', $format, $m)) {
|
|
$w = (int) $m[1];
|
|
$h = (int) $m[2];
|
|
$row = $db->fetch(
|
|
"SELECT width, height FROM advertising_formats WHERE is_active = 1 AND width = ? AND height = ? ORDER BY sort_order ASC, id ASC LIMIT 1",
|
|
[$w, $h]
|
|
);
|
|
if ($row) {
|
|
return [
|
|
'width' => ($row['width'] ?? 0) > 0 ? ($row['width'] . 'px') : '100%',
|
|
'height' => ($row['height'] ?? 0) > 0 ? ($row['height'] . 'px') : 'auto'
|
|
];
|
|
}
|
|
}
|
|
|
|
// Por nome
|
|
$row = $db->fetch(
|
|
"SELECT width, height FROM advertising_formats WHERE is_active = 1 AND (name = ? OR LOWER(name) = LOWER(?)) ORDER BY sort_order ASC, id ASC LIMIT 1",
|
|
[$format, $format]
|
|
);
|
|
if ($row) {
|
|
return [
|
|
'width' => ($row['width'] ?? 0) > 0 ? ($row['width'] . 'px') : '100%',
|
|
'height' => ($row['height'] ?? 0) > 0 ? ($row['height'] . 'px') : 'auto'
|
|
];
|
|
}
|
|
|
|
// Fallback: responsivo na BD (width=0 ou height=0)
|
|
$row = $db->fetch(
|
|
"SELECT width, height FROM advertising_formats WHERE is_active = 1 AND (width = 0 OR height = 0) ORDER BY sort_order ASC, id ASC LIMIT 1"
|
|
);
|
|
if ($row) {
|
|
return [
|
|
'width' => ($row['width'] ?? 0) > 0 ? ($row['width'] . 'px') : '100%',
|
|
'height' => ($row['height'] ?? 0) > 0 ? ($row['height'] . 'px') : 'auto'
|
|
];
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* Obter formatos de anúncio disponíveis
|
|
*/
|
|
public function getAdFormats(): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
// Buscar formatos da base de dados (baseados na folha Config)
|
|
$db = DatabaseManager::getInstance();
|
|
$formats = $db->fetchAll(
|
|
"SELECT id, cuid, name, width, height, format_type, pub_type, pub_method,
|
|
html_template, is_active, sort_order
|
|
FROM advertising_formats
|
|
WHERE is_active = 1
|
|
ORDER BY sort_order ASC, name ASC"
|
|
);
|
|
|
|
// Sem fallback inventado: se não houver formatos, devolver erro explícito
|
|
if (empty($formats)) {
|
|
http_response_code(404);
|
|
echo json_encode([
|
|
'success' => false,
|
|
'message' => 'No ad formats found in database'
|
|
]);
|
|
return;
|
|
}
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $formats,
|
|
'total' => count($formats)
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_api_get_ad_formats']);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Obter formatos de criativos para formulários
|
|
*/
|
|
public function getCreativeFormats(): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
// Buscar formatos da base de dados (baseados na folha Config)
|
|
$db = DatabaseManager::getInstance();
|
|
$formats = $db->fetchAll(
|
|
"SELECT id, cuid, name, width, height, format_type, pub_type
|
|
FROM advertising_formats
|
|
WHERE is_active = 1
|
|
ORDER BY sort_order ASC, name ASC"
|
|
);
|
|
|
|
// Se não houver formatos na BD, retornar erro
|
|
if (empty($formats)) {
|
|
http_response_code(404);
|
|
echo json_encode([
|
|
'success' => false,
|
|
'message' => 'Nenhum formato encontrado na base de dados'
|
|
]);
|
|
return;
|
|
}
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $formats,
|
|
'total' => count($formats)
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_api_get_creative_formats']);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Obter formatos de campanha para formulários
|
|
*/
|
|
public function getCampaignFormats(): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
// Buscar formatos da base de dados
|
|
$db = DatabaseManager::getInstance();
|
|
$formats = $db->fetchAll(
|
|
"SELECT id, cuid, name, width, height, format_type, pub_type, pub_method
|
|
FROM advertising_formats
|
|
WHERE is_active = 1
|
|
ORDER BY sort_order ASC, name ASC"
|
|
);
|
|
|
|
// Se não houver formatos na BD, retornar erro
|
|
if (empty($formats)) {
|
|
http_response_code(404);
|
|
echo json_encode([
|
|
'success' => false,
|
|
'message' => 'Nenhum formato encontrado na base de dados'
|
|
]);
|
|
return;
|
|
}
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $formats,
|
|
'total' => count($formats)
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_api_get_campaign_formats']);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Obter tipos MIME para criativos
|
|
*/
|
|
public function getMimeTypes(): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
$mimeTypes = [
|
|
['value' => 'image/jpeg', 'label' => 'JPEG'],
|
|
['value' => 'image/png', 'label' => 'PNG'],
|
|
['value' => 'image/gif', 'label' => 'GIF'],
|
|
['value' => 'image/webp', 'label' => 'WebP'],
|
|
['value' => 'image/svg+xml', 'label' => 'SVG']
|
|
];
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $mimeTypes
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_api_get_mime_types']);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Obter statuses para site groups
|
|
*/
|
|
public function getSiteGroupStatuses(): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
$statuses = [
|
|
['value' => 'active', 'label' => 'Ativo'],
|
|
['value' => 'inactive', 'label' => 'Inativo'],
|
|
['value' => 'pending', 'label' => 'Pendente']
|
|
];
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $statuses
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_api_get_site_group_statuses']);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Obter opções de tema
|
|
*/
|
|
public function getThemeOptions(): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
$themes = [
|
|
['value' => 'default', 'label' => 'Default'],
|
|
['value' => 'dark', 'label' => 'Dark'],
|
|
['value' => 'light', 'label' => 'Light'],
|
|
['value' => 'custom', 'label' => 'Custom']
|
|
];
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $themes
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_api_get_theme_options']);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Obter lista de países para formulários
|
|
*/
|
|
public function getCountriesList(): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Verificar se existe tabela countries
|
|
$tableExists = $db->fetch("SHOW TABLES LIKE 'countries'");
|
|
|
|
if ($tableExists) {
|
|
// Buscar países da base de dados
|
|
$countries = $db->fetchAll("
|
|
SELECT code, name, full_name, continent_code
|
|
FROM countries
|
|
WHERE code != 'AA'
|
|
ORDER BY name ASC
|
|
");
|
|
|
|
// Adicionar "Todos os países" no início
|
|
array_unshift($countries, [
|
|
'code' => 'AA',
|
|
'name' => 'Todos os países',
|
|
'full_name' => 'All Countries',
|
|
'continent_code' => 'ALL'
|
|
]);
|
|
} else {
|
|
// Se não existir tabela countries, retornar erro
|
|
http_response_code(404);
|
|
echo json_encode([
|
|
'success' => false,
|
|
'message' => 'Tabela de países não encontrada na base de dados'
|
|
]);
|
|
return;
|
|
}
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $countries,
|
|
'total' => count($countries)
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_api_get_countries_list']);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
|
|
}
|
|
}
|
|
|
|
// --- SITE GROUPS (MULTISITES) API METHODS ---
|
|
|
|
/**
|
|
* Listar site groups
|
|
*/
|
|
public function getSiteGroups(): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
// Sanitizar e validar inputs
|
|
$page = max(1, Sanitize::integer(InputSanitizer::get('page', 'GET') ?? 1));
|
|
$limit = max(1, min(100, Sanitize::integer(InputSanitizer::get('limit', 'GET') ?? 10)));
|
|
$search = Sanitize::string(InputSanitizer::get('search', 'GET') ?? '');
|
|
$offset = ($page - 1) * $limit;
|
|
|
|
$whereClause = "WHERE sg.deleted_at IS NULL";
|
|
$params = [];
|
|
|
|
// Ordenação (whitelist)
|
|
$sortBy = Sanitize::string(InputSanitizer::get('sort_by', 'GET') ?? 'alias');
|
|
$sortDir = strtolower(Sanitize::string(InputSanitizer::get('sort_dir', 'GET') ?? 'asc')) === 'desc' ? 'DESC' : 'ASC';
|
|
$allowedSort = [
|
|
'alias' => 'sg.alias',
|
|
'name' => 'sg.name',
|
|
'status' => 'sg.status',
|
|
'created_at' => 'sg.created_at',
|
|
'domains_count' => 'domains_count',
|
|
'campaigns_count' => 'campaigns_count'
|
|
];
|
|
$orderBy = $allowedSort[$sortBy] ?? 'sg.alias';
|
|
|
|
if (!empty($search)) {
|
|
$whereClause .= " AND (sg.name LIKE ? OR sg.description LIKE ?)";
|
|
$searchTerm = "%{$search}%";
|
|
$params = [$searchTerm, $searchTerm];
|
|
}
|
|
|
|
// Query principal
|
|
$query = "
|
|
SELECT
|
|
sg.id AS id,
|
|
sg.cuid AS cuid,
|
|
sg.name AS name,
|
|
sg.alias AS alias,
|
|
sg.description AS description,
|
|
sg.status AS status,
|
|
sg.settings AS settings,
|
|
sg.created_at AS created_at,
|
|
sg.updated_at AS updated_at,
|
|
COUNT(DISTINCT sd.id) AS domains_count,
|
|
COUNT(DISTINCT c.id) AS campaigns_count
|
|
FROM advertising_site_groups sg
|
|
LEFT JOIN advertising_site_domains sd ON sg.id = sd.site_group_id AND sd.deleted_at IS NULL
|
|
LEFT JOIN advertising_campaigns c ON sg.id = c.site_group_id AND c.deleted_at IS NULL
|
|
{$whereClause}
|
|
GROUP BY sg.id
|
|
ORDER BY {$orderBy} {$sortDir}
|
|
LIMIT {$limit} OFFSET {$offset}
|
|
";
|
|
|
|
$siteGroups = DatabaseManager::getInstance()->fetchAll($query, $params);
|
|
|
|
// Query de contagem
|
|
$countQuery = "
|
|
SELECT COUNT(DISTINCT sg.id) as total
|
|
FROM advertising_site_groups sg
|
|
{$whereClause}
|
|
";
|
|
|
|
$totalResult = DatabaseManager::getInstance()->fetch($countQuery, $params);
|
|
$total = (int)($totalResult['total'] ?? 0);
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $siteGroups,
|
|
'pagination' => [
|
|
'page' => $page,
|
|
'limit' => $limit,
|
|
'total' => $total,
|
|
'pages' => ceil($total / $limit),
|
|
'hasNext' => $page < ceil($total / $limit),
|
|
'hasPrev' => $page > 1,
|
|
'start' => $offset + 1,
|
|
'end' => min($offset + $limit, $total),
|
|
'showing' => count($siteGroups)
|
|
],
|
|
'sorting' => [
|
|
'sort_by' => $sortBy,
|
|
'sort_dir' => strtolower($sortDir)
|
|
]
|
|
]);
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_get_site_groups']);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
|
|
}
|
|
}
|
|
|
|
// --- SITE DOMAINS (API) ---
|
|
|
|
/**
|
|
* Listar domínios de um site group
|
|
*/
|
|
public function getSiteDomains(int $id): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
$db = DatabaseManager::getInstance();
|
|
$domains = $db->fetchAll(
|
|
"SELECT
|
|
d.id AS id,
|
|
d.cuid AS cuid,
|
|
d.domain AS domain,
|
|
d.subdomain AS subdomain,
|
|
d.is_primary AS is_primary,
|
|
d.status AS status,
|
|
d.created_at AS created_at,
|
|
d.updated_at AS updated_at
|
|
FROM advertising_site_domains d
|
|
WHERE d.site_group_id = ? AND d.deleted_at IS NULL
|
|
ORDER BY d.is_primary DESC, d.domain ASC",
|
|
[$id]
|
|
);
|
|
echo json_encode(['success' => true, 'data' => $domains ?: []]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_get_site_domains', 'site_group_id' => $id]);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao carregar domínios']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Adicionar domínio a um site group
|
|
*/
|
|
public function addSiteDomain(int $id): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
|
$domain = Sanitize::string($input['domain'] ?? '');
|
|
$subdomain = Sanitize::string($input['subdomain'] ?? '');
|
|
$isPrimary = !empty($input['is_primary']) ? 1 : 0;
|
|
|
|
if ($domain === '') {
|
|
http_response_code(422);
|
|
echo json_encode(['success' => false, 'message' => 'Domínio é obrigatório']);
|
|
return;
|
|
}
|
|
|
|
$db = DatabaseManager::getInstance();
|
|
$success = $db->query(
|
|
"INSERT INTO advertising_site_domains (
|
|
cuid, site_group_id, domain, subdomain, is_primary, status, created_by
|
|
) VALUES (?, ?, ?, ?, ?, ?, ?)",
|
|
[
|
|
(string) new Cuid2(),
|
|
$id,
|
|
$domain,
|
|
$subdomain,
|
|
$isPrimary,
|
|
1,
|
|
$this->getAuthenticatedUserId()
|
|
]
|
|
);
|
|
|
|
if ($success) {
|
|
echo json_encode(['success' => true]);
|
|
} else {
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao adicionar domínio']);
|
|
}
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_add_site_domain', 'site_group_id' => $id]);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Atualizar domínio de um site group
|
|
*/
|
|
public function updateSiteDomain(int $id, int $domain_id): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
|
|
|
$fields = [];
|
|
$params = [];
|
|
|
|
$allowed = ['domain', 'subdomain', 'is_primary', 'status'];
|
|
foreach ($allowed as $key) {
|
|
if (array_key_exists($key, $input)) {
|
|
$fields[] = "$key = ?";
|
|
$params[] = $key === 'is_primary' ? ((int) !!$input[$key]) : Sanitize::string($input[$key]);
|
|
}
|
|
}
|
|
|
|
if (empty($fields)) {
|
|
echo json_encode(['success' => true, 'message' => 'Sem alterações']);
|
|
return;
|
|
}
|
|
|
|
$fields[] = 'updated_at = CURRENT_TIMESTAMP';
|
|
$params[] = $domain_id;
|
|
$params[] = $id;
|
|
|
|
$sql = "UPDATE advertising_site_domains SET " . implode(', ', $fields) . " WHERE id = ? AND site_group_id = ? AND deleted_at IS NULL";
|
|
$ok = DatabaseManager::getInstance()->query($sql, $params);
|
|
echo json_encode(['success' => (bool)$ok]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_update_site_domain', 'site_group_id' => $id, 'domain_id' => $domain_id]);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao atualizar domínio']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Remover (soft delete) domínio de um site group
|
|
*/
|
|
public function deleteSiteDomain(int $id, int $domain_id): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
$ok = DatabaseManager::getInstance()->query(
|
|
"UPDATE advertising_site_domains SET deleted_at = CURRENT_TIMESTAMP WHERE id = ? AND site_group_id = ?",
|
|
[$domain_id, $id]
|
|
);
|
|
echo json_encode(['success' => (bool)$ok]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_delete_site_domain', 'site_group_id' => $id, 'domain_id' => $domain_id]);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao eliminar domínio']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Criar site group
|
|
*/
|
|
public function createSiteGroup(): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
|
|
if (!$input) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'Dados inválidos']);
|
|
return;
|
|
}
|
|
|
|
// Validar campos obrigatórios
|
|
if (empty($input['name'])) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'Nome é obrigatório']);
|
|
return;
|
|
}
|
|
|
|
if (empty($input['domains']) || !is_array($input['domains'])) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'Pelo menos um domínio é obrigatório']);
|
|
return;
|
|
}
|
|
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Generate alias if not provided (lógica da "matrícula")
|
|
$alias = null;
|
|
if (!empty($input['alias'])) {
|
|
// Validate provided alias
|
|
$aliasService = new \App\Modules\Advertising\Services\SiteGroupAliasService();
|
|
if (!$aliasService->isValidAlias($input['alias'])) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'Formato de alias inválido. Use o formato TT-PA-XXX (ex: BR-01-001)']);
|
|
return;
|
|
}
|
|
if (!$aliasService->isAliasUnique($input['alias'])) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'Alias já existe']);
|
|
return;
|
|
}
|
|
$alias = $input['alias'];
|
|
} else {
|
|
// Auto-generate alias using "matrícula" logic
|
|
$aliasService = new \App\Modules\Advertising\Services\SiteGroupAliasService();
|
|
$createdBy = Auth::id() ?? 1;
|
|
$alias = $aliasService->generateUniqueAlias($createdBy);
|
|
}
|
|
|
|
// Criar site group
|
|
$cuid = (string) new Cuid2();
|
|
|
|
$result = $db->query(
|
|
"INSERT INTO advertising_site_groups (cuid, name, alias, description, status, settings, created_by) VALUES (?, ?, ?, ?, ?, ?, ?)",
|
|
[
|
|
$cuid,
|
|
Sanitize::string($input['name']),
|
|
$alias,
|
|
Sanitize::string($input['description'] ?? ''),
|
|
Sanitize::string($input['status'] ?? 'active'),
|
|
json_encode($input['settings'] ?? []),
|
|
Auth::id() ?? 1 // Use authenticated user or fallback to 1
|
|
]
|
|
);
|
|
|
|
$siteGroupId = $db->lastInsertId();
|
|
|
|
if (!$siteGroupId) {
|
|
throw new \Exception('Failed to get last insert ID');
|
|
}
|
|
|
|
// Criar domínios
|
|
foreach ($input['domains'] as $domainData) {
|
|
if (empty($domainData['domain'])) continue;
|
|
|
|
$db->query(
|
|
"INSERT INTO advertising_site_domains (cuid, site_group_id, domain, subdomain, is_primary, status, created_by) VALUES (?, ?, ?, ?, ?, ?, ?)",
|
|
[
|
|
(string) new Cuid2(),
|
|
$siteGroupId,
|
|
Sanitize::string($domainData['domain']),
|
|
Sanitize::string($domainData['subdomain'] ?? ''),
|
|
$domainData['is_primary'] ? 1 : 0,
|
|
1, // 1=active (tinyint)
|
|
$this->getAuthenticatedUserId()
|
|
]
|
|
);
|
|
}
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'message' => 'Site group criado com sucesso',
|
|
'data' => ['id' => $siteGroupId]
|
|
]);
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_create_site_group']);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao criar site group: ' . $e->getMessage()]);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Obter site group específico
|
|
*/
|
|
public function getSiteGroup(int $id): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
$siteGroup = $db->fetch(
|
|
"SELECT
|
|
id, cuid, name, alias, description, status, settings, created_at, updated_at
|
|
FROM
|
|
advertising_site_groups
|
|
WHERE
|
|
id = ? AND deleted_at IS NULL",
|
|
[$id]
|
|
);
|
|
|
|
if (!$siteGroup) {
|
|
http_response_code(404);
|
|
echo json_encode(['success' => false, 'message' => 'Site group não encontrado']);
|
|
return;
|
|
}
|
|
|
|
// Buscar domínios
|
|
$domains = $db->fetchAll(
|
|
"SELECT
|
|
id, cuid, domain, subdomain, is_primary, status, created_at, updated_at
|
|
FROM
|
|
advertising_site_domains
|
|
WHERE
|
|
site_group_id = ? AND deleted_at IS NULL
|
|
ORDER BY
|
|
is_primary DESC, domain",
|
|
[$id]
|
|
);
|
|
|
|
// Buscar campanhas associadas
|
|
$campaigns = $db->fetchAll(
|
|
"SELECT
|
|
c.id,
|
|
c.name,
|
|
c.status,
|
|
c.start_date,
|
|
c.end_date,
|
|
c.budget,
|
|
c.budget_type,
|
|
c.created_at
|
|
FROM advertising_campaigns c
|
|
WHERE c.site_group_id = ? AND c.deleted_at IS NULL
|
|
ORDER BY c.created_at DESC",
|
|
[$id]
|
|
);
|
|
|
|
// Buscar trackers associados através das campanhas
|
|
$trackers = $db->fetchAll(
|
|
"SELECT DISTINCT
|
|
t.id,
|
|
t.name,
|
|
t.tracking_type,
|
|
t.is_active,
|
|
t.final_tracking_url,
|
|
t.created_at
|
|
FROM advertising_trackers t
|
|
INNER JOIN advertising_campaign_trackers ct ON t.id = ct.tracker_id
|
|
INNER JOIN advertising_campaigns c ON ct.campaign_id = c.id
|
|
WHERE c.site_group_id = ? AND c.deleted_at IS NULL
|
|
ORDER BY t.created_at DESC",
|
|
[$id]
|
|
);
|
|
|
|
// Calcular estatísticas
|
|
$stats = [
|
|
'total_campaigns' => count($campaigns),
|
|
'active_campaigns' => count(array_filter($campaigns, fn($c) => $c['status'] == 1)),
|
|
'total_trackers' => count($trackers),
|
|
'active_trackers' => count(array_filter($trackers, fn($t) => $t['is_active'] == 1)),
|
|
'total_domains' => count($domains)
|
|
];
|
|
|
|
$siteGroup['domains'] = $domains;
|
|
$siteGroup['campaigns'] = $campaigns;
|
|
$siteGroup['trackers'] = $trackers;
|
|
$siteGroup['stats'] = $stats;
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $siteGroup
|
|
]);
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_get_site_group', 'id' => $id]);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Atualizar site group
|
|
*/
|
|
public function updateSiteGroup(int $id): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
// Try to get input from JSON first, then from POST data
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
|
|
if (!$input) {
|
|
// Fallback to POST data for form submissions
|
|
$input = $_POST;
|
|
}
|
|
|
|
if (!$input) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'Dados inválidos']);
|
|
return;
|
|
}
|
|
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Verificar se existe
|
|
$existing = $db->fetch("SELECT id FROM advertising_site_groups WHERE id = ? AND deleted_at IS NULL", [$id]);
|
|
if (!$existing) {
|
|
http_response_code(404);
|
|
echo json_encode(['success' => false, 'message' => 'Site group não encontrado']);
|
|
return;
|
|
}
|
|
|
|
// Validate alias if provided
|
|
$alias = null;
|
|
if (!empty($input['alias'])) {
|
|
$aliasService = new \App\Modules\Advertising\Services\SiteGroupAliasService();
|
|
if (!$aliasService->isValidAlias($input['alias'])) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'Formato de alias inválido. Use o formato TT-PA-XXX (ex: BR-01-001)']);
|
|
return;
|
|
}
|
|
if (!$aliasService->isAliasUnique($input['alias'], $id)) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'Alias já existe']);
|
|
return;
|
|
}
|
|
$alias = $input['alias'];
|
|
}
|
|
|
|
// Usar método transaction() do DatabaseManager
|
|
$result = $db->transaction(function() use ($db, $input, $id, $alias) {
|
|
// Atualizar site group
|
|
if ($alias !== null) {
|
|
$db->query(
|
|
"UPDATE advertising_site_groups SET name = ?, alias = ?, description = ?, status = ?, settings = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
|
|
[
|
|
Sanitize::string($input['name']),
|
|
$alias,
|
|
Sanitize::string($input['description'] ?? ''),
|
|
Sanitize::string($input['status'] ?? 'active'),
|
|
json_encode($input['settings'] ?? []),
|
|
$id
|
|
]
|
|
);
|
|
} else {
|
|
$db->query(
|
|
"UPDATE advertising_site_groups SET name = ?, description = ?, status = ?, settings = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
|
|
[
|
|
Sanitize::string($input['name']),
|
|
Sanitize::string($input['description'] ?? ''),
|
|
Sanitize::string($input['status'] ?? 'active'),
|
|
json_encode($input['settings'] ?? []),
|
|
$id
|
|
]
|
|
);
|
|
}
|
|
|
|
// Atualizar domínios se fornecidos
|
|
if (isset($input['domains']) && is_array($input['domains'])) {
|
|
// Soft delete domínios existentes (update status to -1)
|
|
$db->query("UPDATE advertising_site_domains SET status = '-1', updated_at = CURRENT_TIMESTAMP WHERE site_group_id = ?", [$id]);
|
|
|
|
// Adicionar novos domínios
|
|
foreach ($input['domains'] as $domainData) {
|
|
if (empty($domainData['domain'])) continue;
|
|
|
|
$db->query(
|
|
"INSERT INTO advertising_site_domains (cuid, site_group_id, domain, subdomain, is_primary, status, created_by) VALUES (?, ?, ?, ?, ?, ?, ?)",
|
|
[
|
|
(string) new Cuid2(),
|
|
$id,
|
|
Sanitize::string($domainData['domain']),
|
|
Sanitize::string($domainData['subdomain'] ?? ''),
|
|
$domainData['is_primary'] ? 1 : 0,
|
|
1, // 1=active (tinyint)
|
|
$this->getAuthenticatedUserId()
|
|
]
|
|
);
|
|
}
|
|
}
|
|
|
|
return true;
|
|
});
|
|
|
|
if ($result) {
|
|
echo json_encode([
|
|
'success' => true,
|
|
'message' => 'Site group atualizado com sucesso'
|
|
]);
|
|
} else {
|
|
throw new \Exception('Erro na transação');
|
|
}
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_update_site_group', 'id' => $id]);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao atualizar site group: ' . $e->getMessage()]);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Eliminar site group
|
|
*/
|
|
public function deleteSiteGroup(int $id): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Verificar se existe
|
|
$existing = $db->fetch("SELECT id FROM advertising_site_groups WHERE id = ? AND deleted_at IS NULL", [$id]);
|
|
if (!$existing) {
|
|
http_response_code(404);
|
|
echo json_encode(['success' => false, 'message' => 'Site group não encontrado']);
|
|
return;
|
|
}
|
|
|
|
// Soft delete
|
|
$db->query("UPDATE advertising_site_groups SET deleted_at = CURRENT_TIMESTAMP WHERE id = ?", [$id]);
|
|
$db->query("UPDATE advertising_site_domains SET deleted_at = CURRENT_TIMESTAMP WHERE site_group_id = ?", [$id]);
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'message' => 'Site group eliminado com sucesso'
|
|
]);
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_delete_site_group', 'id' => $id]);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao eliminar site group']);
|
|
}
|
|
}
|
|
|
|
public function getGeneralStats(): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
try {
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Obter período dos parâmetros
|
|
$period = $_GET['period'] ?? 'last7days';
|
|
$type = $_GET['type'] ?? '';
|
|
|
|
// Calcular datas baseado no período
|
|
$startDate = date('Y-m-d');
|
|
$endDate = date('Y-m-d');
|
|
|
|
switch ($period) {
|
|
case 'today':
|
|
$startDate = date('Y-m-d');
|
|
$endDate = date('Y-m-d');
|
|
break;
|
|
case 'yesterday':
|
|
$startDate = date('Y-m-d', strtotime('-1 day'));
|
|
$endDate = date('Y-m-d', strtotime('-1 day'));
|
|
break;
|
|
case 'last7days':
|
|
$startDate = date('Y-m-d', strtotime('-7 days'));
|
|
$endDate = date('Y-m-d');
|
|
break;
|
|
case 'last30days':
|
|
$startDate = date('Y-m-d', strtotime('-30 days'));
|
|
$endDate = date('Y-m-d');
|
|
break;
|
|
case 'thisMonth':
|
|
$startDate = date('Y-m-01');
|
|
$endDate = date('Y-m-t');
|
|
break;
|
|
case 'lastMonth':
|
|
$startDate = date('Y-m-01', strtotime('-1 month'));
|
|
$endDate = date('Y-m-t', strtotime('-1 month'));
|
|
break;
|
|
case 'custom':
|
|
$startDate = $_GET['start_date'] ?? date('Y-m-d');
|
|
$endDate = $_GET['end_date'] ?? date('Y-m-d');
|
|
break;
|
|
}
|
|
|
|
// Construir filtros
|
|
$whereConditions = ["DATE(timestamp) BETWEEN ? AND ?"];
|
|
$params = [$startDate, $endDate];
|
|
|
|
if ($type) {
|
|
$whereConditions[] = "campaign_type = ?";
|
|
$params[] = $type;
|
|
}
|
|
|
|
$whereClause = implode(' AND ', $whereConditions);
|
|
|
|
// Estatísticas gerais usando uma única tabela de eventos
|
|
$totalImpressions = $db->fetch("
|
|
SELECT COUNT(*) as count FROM advertising_events
|
|
WHERE $whereClause AND event_type = 'view'
|
|
", $params)['count'] ?? 0;
|
|
|
|
$totalClicks = $db->fetch("
|
|
SELECT COUNT(*) as count FROM advertising_events
|
|
WHERE $whereClause AND event_type = 'click'
|
|
", $params)['count'] ?? 0;
|
|
|
|
$totalConversions = $db->fetch("
|
|
SELECT COUNT(*) as count FROM advertising_events
|
|
WHERE $whereClause AND event_type = 'conversion'
|
|
", $params)['count'] ?? 0;
|
|
|
|
$averageCtr = $totalImpressions > 0 ? ($totalClicks / $totalImpressions) * 100 : 0;
|
|
|
|
// Dados de performance ao longo do tempo
|
|
$performanceData = $db->fetchAll("
|
|
SELECT DATE(timestamp) as date, COUNT(*) as impressions
|
|
FROM advertising_events
|
|
WHERE $whereClause AND event_type = 'view'
|
|
GROUP BY DATE(timestamp)
|
|
ORDER BY date
|
|
", $params);
|
|
|
|
$clicksData = $db->fetchAll("
|
|
SELECT DATE(timestamp) as date, COUNT(*) as clicks
|
|
FROM advertising_events
|
|
WHERE $whereClause AND event_type = 'click'
|
|
GROUP BY DATE(timestamp)
|
|
ORDER BY date
|
|
", $params);
|
|
|
|
// Mesclar dados de impressões e cliques
|
|
$performanceChart = [];
|
|
foreach ($performanceData as $row) {
|
|
$performanceChart[$row['date']] = [
|
|
'date' => $row['date'],
|
|
'impressions' => (int)$row['impressions'],
|
|
'clicks' => 0
|
|
];
|
|
}
|
|
|
|
foreach ($clicksData as $row) {
|
|
if (!isset($performanceChart[$row['date']])) {
|
|
$performanceChart[$row['date']] = [
|
|
'date' => $row['date'],
|
|
'impressions' => 0,
|
|
'clicks' => (int)$row['clicks']
|
|
];
|
|
} else {
|
|
$performanceChart[$row['date']]['clicks'] = (int)$row['clicks'];
|
|
}
|
|
}
|
|
|
|
// Ordenar por data
|
|
ksort($performanceChart);
|
|
|
|
// Distribuição por tipo de campanha
|
|
$typeDistribution = $db->fetchAll("
|
|
SELECT campaign_type as name, COUNT(*) as value
|
|
FROM advertising_events
|
|
WHERE $whereClause AND event_type = 'view'
|
|
GROUP BY campaign_type
|
|
ORDER BY value DESC
|
|
", $params);
|
|
|
|
// Obter parâmetros de paginação
|
|
$page = (int)($_GET['page'] ?? 1);
|
|
$limit = (int)($_GET['limit'] ?? 10);
|
|
$offset = ($page - 1) * $limit;
|
|
|
|
// Contar total de campanhas para paginação
|
|
$totalCampaignsQuery = "
|
|
SELECT COUNT(DISTINCT c.id) as total
|
|
FROM advertising_campaigns c
|
|
LEFT JOIN advertising_events e ON c.id = e.campaign_id AND DATE(e.timestamp) BETWEEN ? AND ?
|
|
" . ($type ? "WHERE c.type = ?" : "");
|
|
|
|
$totalCampaigns = $db->fetch($totalCampaignsQuery, array_merge($params, $type ? [$type] : []))['total'] ?? 0;
|
|
|
|
// Detalhes das campanhas com paginação
|
|
$sql = "
|
|
SELECT
|
|
c.name,
|
|
c.type as campaign_type,
|
|
COUNT(DISTINCT CASE WHEN e.event_type = 'view' THEN e.id END) as impressions,
|
|
COUNT(DISTINCT CASE WHEN e.event_type = 'click' THEN e.id END) as clicks,
|
|
COUNT(DISTINCT CASE WHEN e.event_type = 'conversion' THEN e.id END) as conversions,
|
|
CASE
|
|
WHEN COUNT(DISTINCT CASE WHEN e.event_type = 'view' THEN e.id END) > 0
|
|
THEN (COUNT(DISTINCT CASE WHEN e.event_type = 'click' THEN e.id END) / COUNT(DISTINCT CASE WHEN e.event_type = 'view' THEN e.id END)) * 100
|
|
ELSE 0
|
|
END as ctr,
|
|
CASE
|
|
WHEN COUNT(DISTINCT CASE WHEN e.event_type = 'click' THEN e.id END) > 0
|
|
THEN (COUNT(DISTINCT CASE WHEN e.event_type = 'conversion' THEN e.id END) / COUNT(DISTINCT CASE WHEN e.event_type = 'click' THEN e.id END)) * 100
|
|
ELSE 0
|
|
END as conversion_rate,
|
|
COALESCE(c.budget, 0) as cost,
|
|
CASE
|
|
WHEN COALESCE(c.budget, 0) > 0
|
|
THEN ((COUNT(DISTINCT CASE WHEN e.event_type = 'conversion' THEN e.id END) * 10) / COALESCE(c.budget, 1)) * 100
|
|
ELSE 0
|
|
END as roi
|
|
FROM advertising_campaigns c
|
|
LEFT JOIN advertising_events e ON c.id = e.campaign_id AND DATE(e.timestamp) BETWEEN ? AND ?
|
|
" . ($type ? "WHERE c.type = ?" : "") . "
|
|
GROUP BY c.id, c.name, c.type, c.budget
|
|
ORDER BY impressions DESC
|
|
LIMIT " . (int)$limit . " OFFSET " . (int)$offset;
|
|
|
|
$campaignDetails = $db->fetchAll($sql, array_merge($params, $type ? [$type] : []));
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => [
|
|
'totalImpressions' => $totalImpressions,
|
|
'totalClicks' => $totalClicks,
|
|
'totalConversions' => $totalConversions,
|
|
'averageCtr' => $averageCtr,
|
|
'performanceData' => [
|
|
'dates' => array_keys($performanceChart),
|
|
'impressions' => array_column($performanceChart, 'impressions'),
|
|
'clicks' => array_column($performanceChart, 'clicks')
|
|
],
|
|
'typeDistribution' => $typeDistribution,
|
|
'campaignDetails' => $campaignDetails,
|
|
'pagination' => [
|
|
'current_page' => $page,
|
|
'per_page' => $limit,
|
|
'total' => $totalCampaigns,
|
|
'total_pages' => ceil($totalCampaigns / $limit),
|
|
'has_next_page' => $page < ceil($totalCampaigns / $limit),
|
|
'has_prev_page' => $page > 1
|
|
]
|
|
]
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_api_get_general_stats']);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao obter estatísticas gerais: ' . $e->getMessage()]);
|
|
}
|
|
}
|
|
|
|
// =============================================================================
|
|
// MULTISITE ENDPOINTS (Legacy - use Site Groups instead)
|
|
// =============================================================================
|
|
|
|
/**
|
|
* Adicionar Multisite para uma marca (Legacy - use Site Groups instead)
|
|
*/
|
|
public function addMultiBook(): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
|
|
if (!$input || !isset($input['brand_name'])) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'brand_name é obrigatório']);
|
|
return;
|
|
}
|
|
|
|
$brandName = Sanitize::string($input['brand_name']);
|
|
$country = Sanitize::string($input['country'] ?? 'ZA');
|
|
|
|
$multiBookService = new MultiBookService();
|
|
$result = $multiBookService->addMultiBookForBrand($brandName, $country);
|
|
|
|
echo json_encode($result);
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_api_add_multisite']);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Verificar se pode criar MB para marca em país
|
|
*/
|
|
public function checkMultiBookAvailability(): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
$brandName = Sanitize::string($_GET['brand_name'] ?? '');
|
|
$country = Sanitize::string($_GET['country'] ?? 'ZA');
|
|
|
|
if (empty($brandName)) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'brand_name é obrigatório']);
|
|
return;
|
|
}
|
|
|
|
$multiBookService = new MultiBookService();
|
|
$result = $multiBookService->canCreateMultiBook($brandName, $country);
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $result
|
|
]);
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_api_check_multisite_availability']);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Obter MBs de uma marca
|
|
*/
|
|
public function getMultiBooksByBrand(): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
$brandName = Sanitize::string($_GET['brand_name'] ?? '');
|
|
$limit = max(1, min(100, Sanitize::integer($_GET['limit'] ?? 50)));
|
|
|
|
if (empty($brandName)) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'brand_name é obrigatório']);
|
|
return;
|
|
}
|
|
|
|
$multiBookService = new MultiBookService();
|
|
$results = $multiBookService->getMultiBooksByBrand($brandName, $limit);
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $results
|
|
]);
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_api_get_multisites_by_brand']);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Obter MBs por país
|
|
*/
|
|
public function getMultiBooksByCountry(): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
$country = Sanitize::string($_GET['country'] ?? 'ZA');
|
|
$limit = max(1, min(100, Sanitize::integer($_GET['limit'] ?? 50)));
|
|
|
|
$multiBookService = new MultiBookService();
|
|
$results = $multiBookService->getMultiBooksByCountry($country, $limit);
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $results
|
|
]);
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_api_get_multisites_by_country']);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Obter estatísticas de MBs
|
|
*/
|
|
public function getMultiBookStatistics(): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
$brandName = Sanitize::string($_GET['brand_name'] ?? '');
|
|
$country = Sanitize::string($_GET['country'] ?? '');
|
|
|
|
$multiBookService = new MultiBookService();
|
|
$stats = $multiBookService->getMultiBookStatistics($brandName ?: null, $country ?: null);
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $stats
|
|
]);
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_api_get_multisite_statistics']);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
|
|
}
|
|
}
|
|
}
|