461 lines
15 KiB
PHP
461 lines
15 KiB
PHP
<?php
|
|
namespace App\Modules\Controllers;
|
|
|
|
use App\Core\BaseController;
|
|
use App\Core\View;
|
|
use App\Core\DatabaseManager;
|
|
use App\Core\Branding;
|
|
|
|
class PublicCampaignsController extends BaseController
|
|
{
|
|
private DatabaseManager $db;
|
|
|
|
public function __construct()
|
|
{
|
|
parent::__construct();
|
|
$this->db = DatabaseManager::getInstance();
|
|
}
|
|
|
|
/**
|
|
* Renders the public campaign analytics page.
|
|
*/
|
|
public function analytics(string $slug): void
|
|
{
|
|
if (empty($slug)) {
|
|
http_response_code(404);
|
|
echo "Campaign slug is required.";
|
|
return;
|
|
}
|
|
|
|
$branding = Branding::get();
|
|
$page_title = ($branding['company_name'] ?? 'Analytics') . ' - Campaign Dashboard';
|
|
|
|
View::render('layouts/public-blank.php', [
|
|
'title' => $page_title,
|
|
'page_name' => 'public-campaign-analytics',
|
|
'branding' => $branding,
|
|
'slug' => $slug,
|
|
'page_content' => function() use ($branding, $slug) {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Campaign Analytics',
|
|
'title' => 'Campaign Performance'
|
|
]);
|
|
View::render('@modules/public-campaign-analytics', [
|
|
'branding' => $branding,
|
|
'slug' => $slug
|
|
]);
|
|
}
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* API endpoint: Get campaign stats by slug and optional filters.
|
|
*/
|
|
public function getCampaignStats(string $slug): void
|
|
{
|
|
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 = $_GET['startDate'] ?? date('Y-m-d', strtotime('-30 days'));
|
|
$endDate = $_GET['endDate'] ?? date('Y-m-d');
|
|
$domain = $_GET['domain'] ?? '';
|
|
|
|
try {
|
|
// 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) {
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Error fetching campaign data']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get campaign by cuid (slug)
|
|
*/
|
|
private function getCampaignByCuid(string $cuid): ?array
|
|
{
|
|
// First, let's check if the table exists and what campaigns are available
|
|
try {
|
|
$checkTable = $this->db->fetch("SHOW TABLES LIKE 'advertising_campaigns'");
|
|
if (!$checkTable) {
|
|
error_log("Table advertising_campaigns does not exist");
|
|
return null;
|
|
}
|
|
|
|
// Check what campaigns exist
|
|
$allCampaigns = $this->db->fetchAll("SELECT cuid, name FROM advertising_campaigns LIMIT 5");
|
|
error_log("Available campaigns: " . json_encode($allCampaigns));
|
|
|
|
} catch (\Exception $e) {
|
|
error_log("Error checking campaigns: " . $e->getMessage());
|
|
}
|
|
|
|
$sql = "SELECT
|
|
c.id AS campaign_id,
|
|
c.name AS campaign_name,
|
|
c.description AS campaign_description,
|
|
c.cuid AS campaign_cuid,
|
|
c.status AS campaign_status,
|
|
c.budget AS campaign_budget,
|
|
c.start_date AS start_date,
|
|
c.end_date AS end_date,
|
|
c.site_group_id AS site_group_id,
|
|
c.created_at AS created_date,
|
|
c.updated_at AS updated_date
|
|
FROM
|
|
advertising_campaigns c
|
|
WHERE
|
|
c.cuid = :cuid AND c.status >= 0";
|
|
return $this->db->fetch($sql, [':cuid' => $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
|
|
{
|
|
$sql = "SELECT
|
|
f.id AS format_id,
|
|
f.name AS format_name,
|
|
f.type AS format_type,
|
|
f.width AS format_width,
|
|
f.height AS format_height,
|
|
f.weight AS format_weight,
|
|
f.is_active AS is_active,
|
|
f.campaign_id AS campaign_id,
|
|
f.settings AS format_settings,
|
|
f.created_at AS created_date,
|
|
f.updated_at AS updated_date
|
|
FROM
|
|
advertising_formats f
|
|
WHERE
|
|
f.campaign_id = :campaign_id AND f.is_active = 1";
|
|
return $this->db->fetchAll($sql, [':campaign_id' => $campaignId]) ?: [];
|
|
}
|
|
|
|
/**
|
|
* Get campaign statistics data
|
|
*/
|
|
private function getCampaignStatsData(int $campaignId, string $startDate, string $endDate): array
|
|
{
|
|
$sql = "SELECT
|
|
c.id,
|
|
c.name,
|
|
c.status,
|
|
COUNT(DISTINCT f.id) as formats_count,
|
|
COUNT(DISTINCT cr.id) as creatives_count,
|
|
SUM(r.views) as total_views,
|
|
SUM(r.clicks) as total_clicks,
|
|
SUM(r.registers) as total_registers,
|
|
SUM(r.revenue) as total_revenue,
|
|
AVG(r.ctr) as avg_ctr,
|
|
AVG(r.cpm) as avg_cpm,
|
|
AVG(r.epc) as avg_epc,
|
|
MIN(r.date) as first_hit
|
|
FROM advertising_campaigns c
|
|
LEFT JOIN advertising_formats f ON c.id = f.campaign_id
|
|
LEFT JOIN advertising_creatives cr ON f.id = cr.format_id
|
|
LEFT JOIN advertising_reports_daily r ON c.id = r.campaign_id
|
|
WHERE c.id = :campaign_id AND c.status >= 0";
|
|
|
|
$params = [':campaign_id' => $campaignId];
|
|
|
|
if ($startDate) {
|
|
$sql .= " AND r.date >= :start_date";
|
|
$params[':start_date'] = $startDate;
|
|
}
|
|
|
|
if ($endDate) {
|
|
$sql .= " AND r.date <= :end_date";
|
|
$params[':end_date'] = $endDate;
|
|
}
|
|
|
|
$sql .= " GROUP BY c.id";
|
|
|
|
return $this->db->fetch($sql, $params) ?: [];
|
|
}
|
|
|
|
/**
|
|
* 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
|
|
{
|
|
$sql = "SELECT
|
|
DATE(r.date) as date,
|
|
SUM(r.views) as impressions,
|
|
SUM(r.clicks) as clicks
|
|
FROM advertising_reports_daily r
|
|
WHERE r.campaign_id = :campaign_id
|
|
AND r.date BETWEEN :start_date AND :end_date
|
|
GROUP BY DATE(r.date)
|
|
ORDER BY r.date";
|
|
|
|
$result = $this->db->fetchAll($sql, [
|
|
':campaign_id' => $campaignId,
|
|
':start_date' => $startDate,
|
|
':end_date' => $endDate
|
|
]) ?: [];
|
|
|
|
$categories = [];
|
|
$impressionsData = [];
|
|
$clicksData = [];
|
|
|
|
foreach ($result as $row) {
|
|
$categories[] = $row['date'];
|
|
$impressionsData[] = (int)$row['impressions'];
|
|
$clicksData[] = (int)$row['clicks'];
|
|
}
|
|
|
|
return [
|
|
'series' => [
|
|
['name' => 'Impressions', 'data' => $impressionsData],
|
|
['name' => 'Clicks', 'data' => $clicksData]
|
|
],
|
|
'categories' => $categories
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Get geographical data for charts
|
|
*/
|
|
private function getGeosData(int $campaignId, string $startDate, string $endDate): array
|
|
{
|
|
$sql = "SELECT
|
|
r.country_code,
|
|
SUM(r.views) as impressions
|
|
FROM advertising_reports_daily r
|
|
WHERE r.campaign_id = :campaign_id
|
|
AND r.date BETWEEN :start_date AND :end_date
|
|
AND r.country_code IS NOT NULL
|
|
GROUP BY r.country_code
|
|
ORDER BY impressions DESC
|
|
LIMIT 10";
|
|
|
|
$result = $this->db->fetchAll($sql, [
|
|
':campaign_id' => $campaignId,
|
|
':start_date' => $startDate,
|
|
':end_date' => $endDate
|
|
]) ?: [];
|
|
|
|
$series = [];
|
|
$labels = [];
|
|
|
|
foreach ($result as $row) {
|
|
$labels[] = $row['country_code'];
|
|
$series[] = (int)$row['impressions'];
|
|
}
|
|
|
|
return [
|
|
'series' => $series,
|
|
'labels' => $labels
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Get devices data for charts
|
|
*/
|
|
private function getDevicesData(int $campaignId, string $startDate, string $endDate): array
|
|
{
|
|
$sql = "SELECT
|
|
r.device_type,
|
|
SUM(r.views) as impressions
|
|
FROM advertising_reports_daily r
|
|
WHERE r.campaign_id = :campaign_id
|
|
AND r.date BETWEEN :start_date AND :end_date
|
|
AND r.device_type IS NOT NULL
|
|
GROUP BY r.device_type
|
|
ORDER BY impressions DESC";
|
|
|
|
$result = $this->db->fetchAll($sql, [
|
|
':campaign_id' => $campaignId,
|
|
':start_date' => $startDate,
|
|
':end_date' => $endDate
|
|
]) ?: [];
|
|
|
|
$series = [];
|
|
$labels = [];
|
|
|
|
foreach ($result as $row) {
|
|
$labels[] = ucfirst($row['device_type']);
|
|
$series[] = (int)$row['impressions'];
|
|
}
|
|
|
|
return [
|
|
'series' => $series,
|
|
'labels' => $labels
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Get campaign tables data
|
|
*/
|
|
private function getCampaignTables(int $campaignId, string $startDate, string $endDate): array
|
|
{
|
|
$sql = "SELECT
|
|
r.date,
|
|
r.country_code,
|
|
r.views,
|
|
r.clicks,
|
|
r.ctr
|
|
FROM advertising_reports_daily r
|
|
WHERE r.campaign_id = :campaign_id
|
|
AND r.date BETWEEN :start_date AND :end_date
|
|
ORDER BY r.date DESC, r.views DESC
|
|
LIMIT 20";
|
|
|
|
$result = $this->db->fetchAll($sql, [
|
|
':campaign_id' => $campaignId,
|
|
':start_date' => $startDate,
|
|
':end_date' => $endDate
|
|
]) ?: [];
|
|
|
|
$dailyStats = [];
|
|
foreach ($result as $row) {
|
|
$dailyStats[] = [
|
|
$row['date'],
|
|
$row['country_code'] ?? 'Unknown',
|
|
number_format($row['views']),
|
|
number_format($row['clicks']),
|
|
number_format($row['ctr'], 2) . '%'
|
|
];
|
|
}
|
|
|
|
return [
|
|
'dailyStats' => $dailyStats
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Get available domains for the campaign
|
|
*/
|
|
private function getAvailableDomains(int $campaignId): array
|
|
{
|
|
try {
|
|
// Buscar domínios reais das campanhas
|
|
$domains = $this->db->fetchAll("SELECT DISTINCT
|
|
domain
|
|
FROM advertising_campaigns
|
|
WHERE domain IS NOT NULL AND domain != '' AND deleted_at IS NULL
|
|
ORDER BY domain");
|
|
|
|
if (empty($domains)) {
|
|
return ['performix.pt', 'bitreport.pt', 'crm.local'];
|
|
}
|
|
|
|
return array_column($domains, 'domain');
|
|
|
|
} catch (\Exception $e) {
|
|
return ['performix.pt', 'bitreport.pt', 'crm.local'];
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get status class for display
|
|
*/
|
|
private function getStatusClass(string $status): string
|
|
{
|
|
return match($status) {
|
|
'active' => 'badge bg-success-subtle text-success',
|
|
'paused' => 'badge bg-warning-subtle text-warning',
|
|
'completed' => 'badge bg-info-subtle text-info',
|
|
'archived' => 'badge bg-secondary-subtle text-secondary',
|
|
default => 'badge bg-secondary-subtle text-secondary'
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Get status display text
|
|
*/
|
|
private function getStatusDisplay(string $status): string
|
|
{
|
|
return match($status) {
|
|
'active' => 'Ativo',
|
|
'paused' => 'Pausado',
|
|
'completed' => 'Concluído',
|
|
'archived' => 'Arquivado',
|
|
default => 'Desconhecido'
|
|
};
|
|
}
|
|
}
|