- Fix storage permissions to use 'www' user instead of 'www-data' - Fix UserModel getAllForAdmin query to avoid placeholders in LIMIT/OFFSET - Import missing modules: Advertising, Dashboard, Analytics - Update deploy script to copy files to public directory
791 lines
29 KiB
PHP
791 lines
29 KiB
PHP
<?php
|
|
namespace App\Modules\Dashboard\Controllers;
|
|
|
|
use App\Core\InputSanitizer;
|
|
use App\Core\DatabaseManager;
|
|
use App\Core\ErrorReporter;
|
|
use App\Core\View;
|
|
use App\Core\Auth;
|
|
|
|
class DashboardController
|
|
{
|
|
public static function crmPage(): void
|
|
{
|
|
\App\Core\View::render('@dashboard/crm', [
|
|
'page_title' => 'Dashboard/crm',
|
|
]);
|
|
}
|
|
|
|
public static function dashboardPage(): void
|
|
{
|
|
$userId = $_SESSION['user_id'] ?? 1; // Default to user 1 for now
|
|
$widgetManager = \App\Core\DashboardWidgetManager::getInstance();
|
|
|
|
// Get user's dashboard widgets
|
|
$widgets = $widgetManager->getUserDashboardWidgets($userId);
|
|
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Dashboard',
|
|
'page_name' => 'dashboard-main',
|
|
'page_content' => function() use ($widgets, $widgetManager) {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Dashboard',
|
|
'title' => 'Principal'
|
|
]);
|
|
|
|
// Render modular dashboard with widgets
|
|
View::render('@dashboard/modular', [
|
|
'widgets' => $widgets,
|
|
'widget_manager' => $widgetManager
|
|
]);
|
|
}
|
|
]);
|
|
}
|
|
|
|
public static function dashboardCryptoPage(): void
|
|
{
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Dashboard Crypto',
|
|
'page_name' => 'dashboard-crypto',
|
|
'page_content' => function() {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Dashboard',
|
|
'title' => 'Crypto'
|
|
]);
|
|
View::render('@dashboard/crypto');
|
|
}
|
|
]);
|
|
}
|
|
|
|
public static function dashboardCrmPage(): void
|
|
{
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Dashboard CRM',
|
|
'page_name' => 'dashboard-crm',
|
|
'page_content' => function() {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Dashboard',
|
|
'title' => 'CRM'
|
|
]);
|
|
View::render('@dashboard/crm');
|
|
}
|
|
]);
|
|
}
|
|
|
|
public static function dashboardProjectsPage(): void
|
|
{
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Dashboard Projects',
|
|
'page_name' => 'dashboard-projects',
|
|
'page_content' => function() {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Dashboard',
|
|
'title' => 'Projects'
|
|
]);
|
|
View::render('@dashboard/projects');
|
|
}
|
|
]);
|
|
}
|
|
|
|
public static function dashboardNftPage(): void
|
|
{
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Dashboard NFT',
|
|
'page_name' => 'dashboard-nft',
|
|
'page_content' => function() {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Dashboard',
|
|
'title' => 'NFT'
|
|
]);
|
|
View::render('@dashboard/nft');
|
|
}
|
|
]);
|
|
}
|
|
|
|
public static function dashboardBlogPage(): void
|
|
{
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Dashboard Blog',
|
|
'page_name' => 'dashboard-blog',
|
|
'page_content' => function() {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Dashboard',
|
|
'title' => 'Blog'
|
|
]);
|
|
View::render('@dashboard/blog');
|
|
}
|
|
]);
|
|
}
|
|
|
|
public static function analytics(): void
|
|
{
|
|
Auth::check();
|
|
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Analytics Dashboard',
|
|
'page_name' => 'dashboard-analytics',
|
|
'page_content' => function() {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Dashboards',
|
|
'title' => 'Analytics'
|
|
]);
|
|
View::render('@dashboard/analytics');
|
|
}
|
|
]);
|
|
}
|
|
|
|
public static function dashboardJobPage(): void
|
|
{
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Dashboard Job',
|
|
'page_name' => 'dashboard-job',
|
|
'page_content' => function() {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Dashboard',
|
|
'title' => 'Job'
|
|
]);
|
|
View::render('@dashboard/job');
|
|
}
|
|
]);
|
|
}
|
|
|
|
public static function getDealsApi(): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
// Dados de exemplo baseados no template
|
|
// Get real deals data from database
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
$dealsData = self::getRealDealsData($db);
|
|
|
|
$baseUrl = 'http://localhost:8888'; // [memory:7611689932522187127]
|
|
|
|
$formattedColumns = array_map(function ($column) use ($baseUrl) {
|
|
$column['deals'] = array_map(function ($deal) use ($baseUrl) {
|
|
$deal['owner_img'] = $baseUrl . '/assets/images/users/' . ltrim($deal['owner_img'], '/');
|
|
return $deal;
|
|
}, $column['deals']);
|
|
return $column;
|
|
}, $dealsData);
|
|
|
|
echo json_encode($formattedColumns);
|
|
exit;
|
|
}
|
|
|
|
public function crm(): void
|
|
{
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Dashboard CRM',
|
|
'page_name' => 'dashboard-crm',
|
|
'page_content' => function() {
|
|
View::render('layouts/page-title.php', [
|
|
'pagetitle' => 'Dashboard',
|
|
'title' => 'CRM'
|
|
]);
|
|
View::render('@crm/dashboard');
|
|
}
|
|
]);
|
|
}
|
|
|
|
public function ecommerce(): void
|
|
{
|
|
View::render('@dashboard/ecommerce');
|
|
}
|
|
|
|
// --- WIDGET ENDPOINTS (Missing functionality) ---
|
|
|
|
/**
|
|
* Get specific widget data
|
|
*/
|
|
public static function getWidgetData(string $widget): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
$widgetManager = \App\Core\DashboardWidgetManager::getInstance();
|
|
$userId = $_SESSION['user_id'] ?? 1;
|
|
|
|
// Get widget data based on type
|
|
switch($widget) {
|
|
case 'campaigns':
|
|
$data = self::getCampaignWidgetData();
|
|
break;
|
|
case 'analytics':
|
|
$data = self::getAnalyticsWidgetData();
|
|
break;
|
|
case 'users':
|
|
$data = self::getUsersWidgetData();
|
|
break;
|
|
case 'revenue':
|
|
$data = self::getRevenueWidgetData();
|
|
break;
|
|
default:
|
|
$data = ['error' => 'Widget type not found'];
|
|
}
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'widget' => $widget,
|
|
'data' => $data,
|
|
'timestamp' => date('c')
|
|
]);
|
|
|
|
} catch (\Exception $e) {
|
|
http_response_code(500);
|
|
echo json_encode(['error' => 'Widget data error: ' . $e->getMessage()]);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Export widget data
|
|
*/
|
|
public static function exportWidgetData(string $widget): void
|
|
{
|
|
try {
|
|
$format = $_GET['format'] ?? 'json';
|
|
|
|
// Get widget data
|
|
$data = [];
|
|
switch($widget) {
|
|
case 'campaigns':
|
|
$data = self::getCampaignWidgetData();
|
|
break;
|
|
case 'analytics':
|
|
$data = self::getAnalyticsWidgetData();
|
|
break;
|
|
default:
|
|
$data = ['message' => 'No data available'];
|
|
}
|
|
|
|
// Export based on format
|
|
if ($format === 'csv') {
|
|
header('Content-Type: text/csv');
|
|
header('Content-Disposition: attachment; filename="' . $widget . '_export.csv"');
|
|
echo self::arrayToCsv($data);
|
|
} else {
|
|
header('Content-Type: application/json');
|
|
header('Content-Disposition: attachment; filename="' . $widget . '_export.json"');
|
|
echo json_encode($data, JSON_PRETTY_PRINT);
|
|
}
|
|
|
|
} catch (\Exception $e) {
|
|
http_response_code(500);
|
|
echo json_encode(['error' => 'Export error: ' . $e->getMessage()]);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Render widget HTML
|
|
*/
|
|
public static function renderWidget(string $widget): void
|
|
{
|
|
try {
|
|
$data = [];
|
|
switch($widget) {
|
|
case 'campaigns':
|
|
$data = self::getCampaignWidgetData();
|
|
break;
|
|
case 'analytics':
|
|
$data = self::getAnalyticsWidgetData();
|
|
break;
|
|
default:
|
|
$data = ['message' => 'Widget not found'];
|
|
}
|
|
|
|
View::render('layouts/main.php', [
|
|
'title' => 'Widget: ' . ucfirst($widget),
|
|
'page_name' => 'widget-' . $widget,
|
|
'page_content' => function() use ($widget, $data) {
|
|
View::render('@dashboard/widget.php', [
|
|
'widget_type' => $widget,
|
|
'data' => $data
|
|
]);
|
|
}
|
|
]);
|
|
|
|
} catch (\Exception $e) {
|
|
http_response_code(500);
|
|
echo 'Widget render error: ' . $e->getMessage();
|
|
}
|
|
}
|
|
|
|
// --- WIDGET DATA METHODS ---
|
|
|
|
private static function getCampaignWidgetData(): array
|
|
{
|
|
try {
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Get real campaign data from database
|
|
$totalCampaigns = $db->fetch("SELECT COUNT(*) as count FROM campaigns WHERE status >= 0")['count'] ?? 0;
|
|
$activeCampaigns = $db->fetch("SELECT COUNT(*) as count FROM campaigns WHERE status = 1")['count'] ?? 0;
|
|
$pausedCampaigns = $db->fetch("SELECT COUNT(*) as count FROM campaigns WHERE status = 0")['count'] ?? 0;
|
|
|
|
// Get performance data from stats table
|
|
$performance = [
|
|
'clicks' => 0,
|
|
'impressions' => 0,
|
|
'ctr' => 0
|
|
];
|
|
|
|
try {
|
|
$clicks = $db->fetch("SELECT SUM(count) as total FROM stats WHERE metric = 'clicks'")['total'] ?? 0;
|
|
$impressions = $db->fetch("SELECT SUM(count) as total FROM stats WHERE metric = 'impressions'")['total'] ?? 0;
|
|
|
|
$performance['clicks'] = (int)$clicks;
|
|
$performance['impressions'] = (int)$impressions;
|
|
$performance['ctr'] = $impressions > 0 ? round(($clicks / $impressions) * 100, 2) : 0;
|
|
} catch (\Exception $e) {
|
|
// Table access error, use defaults
|
|
}
|
|
|
|
return [
|
|
'total_campaigns' => (int)$totalCampaigns,
|
|
'active_campaigns' => (int)$activeCampaigns,
|
|
'paused_campaigns' => (int)$pausedCampaigns,
|
|
'performance' => $performance
|
|
];
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e);
|
|
return [
|
|
'total_campaigns' => 0,
|
|
'active_campaigns' => 0,
|
|
'paused_campaigns' => 0,
|
|
'performance' => ['clicks' => 0, 'impressions' => 0, 'ctr' => 0],
|
|
'error' => 'Failed to load campaign data'
|
|
];
|
|
}
|
|
}
|
|
|
|
private static function getAnalyticsWidgetData(): array
|
|
{
|
|
try {
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Get real analytics data from database
|
|
$pageViews = $db->fetch("SELECT SUM(page_views) as total FROM analytics_daily WHERE status >= 0")['total'] ?? 0;
|
|
$uniqueVisitors = $db->fetch("SELECT SUM(unique_visitors) as total FROM analytics_daily WHERE status >= 0")['total'] ?? 0;
|
|
$bounceData = $db->fetch("SELECT AVG(bounce_rate) as avg_bounce FROM analytics_daily WHERE status >= 0");
|
|
$bounceRate = $bounceData ? round((float)$bounceData['avg_bounce'], 1) : 0;
|
|
$sessionData = $db->fetch("SELECT AVG(avg_session_duration) as avg_duration FROM analytics_daily WHERE status >= 0");
|
|
$avgDuration = $sessionData ? round((float)$sessionData['avg_duration']) : 135;
|
|
|
|
return [
|
|
'page_views' => (int)$pageViews,
|
|
'unique_visitors' => (int)$uniqueVisitors,
|
|
'bounce_rate' => $bounceRate,
|
|
'avg_session_duration' => gmdate('i\m s\s', $avgDuration)
|
|
];
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e);
|
|
return [
|
|
'page_views' => 0,
|
|
'unique_visitors' => 0,
|
|
'bounce_rate' => 0,
|
|
'avg_session_duration' => '0m 0s',
|
|
'error' => 'Failed to load analytics data'
|
|
];
|
|
}
|
|
}
|
|
|
|
private static function getUsersWidgetData(): array
|
|
{
|
|
try {
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Get real user data from database
|
|
$totalUsers = $db->fetch("SELECT COUNT(*) as count FROM users WHERE status >= 0")['count'] ?? 0;
|
|
$activeUsers = $db->fetch("SELECT COUNT(*) as count FROM users WHERE status = 1")['count'] ?? 0;
|
|
$newUsersToday = $db->fetch("SELECT COUNT(*) as count FROM users WHERE DATE(created_at) = CURDATE() AND status >= 0")['count'] ?? 0;
|
|
$onlineNow = $db->fetch("SELECT COUNT(*) as count FROM users WHERE last_login > DATE_SUB(NOW(), INTERVAL 15 MINUTE) AND status = 1")['count'] ?? 0;
|
|
|
|
return [
|
|
'total_users' => (int)$totalUsers,
|
|
'active_users' => (int)$activeUsers,
|
|
'new_users_today' => (int)$newUsersToday,
|
|
'online_now' => (int)$onlineNow
|
|
];
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e);
|
|
return [
|
|
'total_users' => 0,
|
|
'active_users' => 0,
|
|
'new_users_today' => 0,
|
|
'online_now' => 0,
|
|
'error' => 'Failed to load users data'
|
|
];
|
|
}
|
|
}
|
|
|
|
private static function getRevenueWidgetData(): array
|
|
{
|
|
try {
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Get real revenue data from database
|
|
$monthlyRevenue = $db->fetch("SELECT SUM(amount) as total FROM revenue WHERE MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) AND status >= 0")['total'] ?? 0;
|
|
$yearlyRevenue = $db->fetch("SELECT SUM(amount) as total FROM revenue WHERE YEAR(created_at) = YEAR(CURDATE()) AND status >= 0")['total'] ?? 0;
|
|
|
|
// Calculate growth rate (current month vs previous month)
|
|
$previousMonthRevenue = $db->fetch("SELECT SUM(amount) as total FROM revenue WHERE MONTH(created_at) = MONTH(CURDATE()) - 1 AND YEAR(created_at) = YEAR(CURDATE()) AND status >= 0")['total'] ?? 1;
|
|
$growthRate = $previousMonthRevenue > 0 ? round((($monthlyRevenue - $previousMonthRevenue) / $previousMonthRevenue) * 100, 1) : 0;
|
|
|
|
// Get top revenue sources
|
|
$topSources = $db->fetchAll("SELECT source, SUM(amount) as total FROM revenue WHERE status >= 0 GROUP BY source ORDER BY total DESC LIMIT 3");
|
|
$sourceNames = array_map(function($source) {
|
|
return $source['source'] ?? 'Unknown';
|
|
}, $topSources);
|
|
|
|
return [
|
|
'monthly_revenue' => (float)$monthlyRevenue,
|
|
'yearly_revenue' => (float)$yearlyRevenue,
|
|
'growth_rate' => $growthRate,
|
|
'top_sources' => !empty($sourceNames) ? $sourceNames : ['No data', 'No data', 'No data']
|
|
];
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e);
|
|
return [
|
|
'monthly_revenue' => 0,
|
|
'yearly_revenue' => 0,
|
|
'growth_rate' => 0,
|
|
'top_sources' => ['No data', 'No data', 'No data'],
|
|
'error' => 'Failed to load revenue data'
|
|
];
|
|
}
|
|
}
|
|
|
|
private static function arrayToCsv(array $data): string
|
|
{
|
|
$output = '';
|
|
if (!empty($data)) {
|
|
$output .= implode(',', array_keys($data)) . "\n";
|
|
$output .= implode(',', array_values($data)) . "\n";
|
|
}
|
|
return $output;
|
|
}
|
|
|
|
/**
|
|
* API endpoint for widget data
|
|
*/
|
|
public static function apiWidgetData(string $widget): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
$data = [];
|
|
switch($widget) {
|
|
case 'campaigns':
|
|
$data = self::getCampaignWidgetData();
|
|
break;
|
|
case 'analytics':
|
|
$data = self::getAnalyticsWidgetData();
|
|
break;
|
|
case 'users':
|
|
$data = self::getUsersWidgetData();
|
|
break;
|
|
case 'revenue':
|
|
$data = self::getRevenueWidgetData();
|
|
break;
|
|
case 'analytics-overview':
|
|
$data = self::getAnalyticsOverviewData();
|
|
break;
|
|
case 'user-activity':
|
|
$data = self::getUserActivityData();
|
|
break;
|
|
case 'advertising-campaigns':
|
|
$data = self::getAdvertisingCampaignsData();
|
|
break;
|
|
default:
|
|
$data = ['error' => 'Widget type not found'];
|
|
}
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'widget' => $widget,
|
|
'data' => $data,
|
|
'timestamp' => date('c')
|
|
]);
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'widget_api', 'widget' => $widget]);
|
|
http_response_code(500);
|
|
echo json_encode([
|
|
'success' => false,
|
|
'error' => 'Widget data error: ' . $e->getMessage(),
|
|
'widget' => $widget
|
|
]);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get analytics overview widget data
|
|
*/
|
|
private static function getAnalyticsOverviewData(): array
|
|
{
|
|
try {
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Get real analytics data from database
|
|
$analyticsResult = $db->fetch("
|
|
SELECT
|
|
COUNT(DISTINCT JSON_EXTRACT(event_data, '$.session_id')) as unique_visitors,
|
|
COUNT(*) as page_views,
|
|
AVG(JSON_EXTRACT(event_data, '$.duration')) as avg_session,
|
|
0 as bounce_rate
|
|
FROM geo_analytics_events
|
|
WHERE event_type = 'page_view'
|
|
AND DATE(created_at) = CURDATE()
|
|
");
|
|
|
|
$stats = [
|
|
'unique_visitors' => (int)($analyticsResult['unique_visitors'] ?? 0),
|
|
'page_views' => (int)($analyticsResult['page_views'] ?? 0),
|
|
'avg_session' => (int)($analyticsResult['avg_session'] ?? 0),
|
|
'bounce_rate' => (int)($analyticsResult['bounce_rate'] ?? 0),
|
|
'top_page' => '/dashboard'
|
|
];
|
|
|
|
return [
|
|
'stats' => $stats,
|
|
'formatted' => [
|
|
'unique_visitors' => number_format($stats['unique_visitors']),
|
|
'page_views' => number_format($stats['page_views']),
|
|
'avg_session' => $stats['avg_session'] . 'm',
|
|
'bounce_rate' => $stats['bounce_rate'] . '%',
|
|
'top_page' => $stats['top_page']
|
|
]
|
|
];
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'analytics_overview_widget']);
|
|
return [
|
|
'stats' => [
|
|
'unique_visitors' => 0,
|
|
'page_views' => 0,
|
|
'avg_session' => 0,
|
|
'bounce_rate' => 0,
|
|
'top_page' => 'N/A'
|
|
],
|
|
'formatted' => [
|
|
'unique_visitors' => '0',
|
|
'page_views' => '0',
|
|
'avg_session' => '0m',
|
|
'bounce_rate' => '0%',
|
|
'top_page' => 'N/A'
|
|
]
|
|
];
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get user activity widget data
|
|
*/
|
|
private static function getUserActivityData(): array
|
|
{
|
|
try {
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Get real user activity data from database
|
|
$userResult = $db->fetch("
|
|
SELECT
|
|
COUNT(DISTINCT user_id) as users_online,
|
|
COUNT(*) as logins_today,
|
|
COUNT(DISTINCT CASE WHEN DATE(created_at) = CURDATE() THEN user_id END) as new_users,
|
|
MAX(created_at) as last_login
|
|
FROM user_sessions
|
|
WHERE DATE(created_at) = CURDATE()
|
|
");
|
|
|
|
$stats = [
|
|
'users_online' => (int)($userResult['users_online'] ?? 0),
|
|
'logins_today' => (int)($userResult['logins_today'] ?? 0),
|
|
'new_users' => (int)($userResult['new_users'] ?? 0),
|
|
'last_login' => $userResult['last_login'] ? date('H:i', strtotime($userResult['last_login'])) : 'N/A'
|
|
];
|
|
|
|
return [
|
|
'stats' => $stats,
|
|
'formatted' => [
|
|
'users_online' => number_format($stats['users_online']) . ' utilizadores',
|
|
'logins_today' => number_format($stats['logins_today']),
|
|
'new_users' => number_format($stats['new_users']) . ' esta semana',
|
|
'last_login' => $stats['last_login']
|
|
]
|
|
];
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'user_activity_widget']);
|
|
return [
|
|
'stats' => [
|
|
'users_online' => 0,
|
|
'logins_today' => 0,
|
|
'new_users' => 0,
|
|
'last_login' => 'N/A'
|
|
],
|
|
'formatted' => [
|
|
'users_online' => '0 utilizadores',
|
|
'logins_today' => '0',
|
|
'new_users' => '0 esta semana',
|
|
'last_login' => 'N/A'
|
|
]
|
|
];
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get advertising campaigns widget data
|
|
*/
|
|
private static function getAdvertisingCampaignsData(): array
|
|
{
|
|
try {
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Get real advertising data from database
|
|
$advertisingResult = $db->fetch("
|
|
SELECT
|
|
COUNT(CASE WHEN status = 'active' THEN 1 END) as active_campaigns,
|
|
SUM(total_impressions) as total_impressions,
|
|
SUM(total_clicks) as total_clicks,
|
|
CASE
|
|
WHEN SUM(total_impressions) > 0
|
|
THEN ROUND(SUM(total_clicks) * 100.0 / SUM(total_impressions), 2)
|
|
ELSE 0
|
|
END as ctr,
|
|
SUM(monthly_spend) as monthly_spend
|
|
FROM advertising_campaigns
|
|
WHERE status >= 0
|
|
");
|
|
|
|
$stats = [
|
|
'active_campaigns' => (int)($advertisingResult['active_campaigns'] ?? 0),
|
|
'total_impressions' => (int)($advertisingResult['total_impressions'] ?? 0),
|
|
'total_clicks' => (int)($advertisingResult['total_clicks'] ?? 0),
|
|
'ctr' => (float)($advertisingResult['ctr'] ?? 0),
|
|
'monthly_spend' => (float)($advertisingResult['monthly_spend'] ?? 0)
|
|
];
|
|
|
|
return [
|
|
'stats' => $stats,
|
|
'formatted' => [
|
|
'active_campaigns' => number_format($stats['active_campaigns']),
|
|
'total_impressions' => number_format($stats['total_impressions']),
|
|
'total_clicks' => number_format($stats['total_clicks']),
|
|
'ctr' => $stats['ctr'] . '%',
|
|
'monthly_spend' => '€' . number_format($stats['monthly_spend'], 2, ',', '.')
|
|
]
|
|
];
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_campaigns_widget']);
|
|
return [
|
|
'stats' => [
|
|
'active_campaigns' => 0,
|
|
'total_impressions' => 0,
|
|
'total_clicks' => 0,
|
|
'ctr' => 0,
|
|
'monthly_spend' => 0
|
|
],
|
|
'formatted' => [
|
|
'active_campaigns' => '0',
|
|
'total_impressions' => '0',
|
|
'total_clicks' => '0',
|
|
'ctr' => '0%',
|
|
'monthly_spend' => '€0,00'
|
|
]
|
|
];
|
|
}
|
|
}
|
|
|
|
private static function getRealDealsData($db): array
|
|
{
|
|
try {
|
|
// Get real deals data from database
|
|
$deals = $db->fetchAll("
|
|
SELECT
|
|
id,
|
|
name as title,
|
|
value,
|
|
stage,
|
|
created_at,
|
|
actual_close_date
|
|
FROM crm_deals
|
|
WHERE status >= 0
|
|
ORDER BY created_at DESC
|
|
LIMIT 20
|
|
");
|
|
|
|
if (empty($deals)) {
|
|
return [
|
|
[
|
|
'id' => 'noDeals',
|
|
'title' => 'No Deals Available',
|
|
'total' => '$0',
|
|
'deal_count' => '0 Deals',
|
|
'color' => 'secondary',
|
|
'deals' => []
|
|
]
|
|
];
|
|
}
|
|
|
|
// Group deals by stage
|
|
$stages = [
|
|
'lead_discovered' => ['title' => 'Lead Discovered', 'color' => 'danger'],
|
|
'contact_initiated' => ['title' => 'Contact Initiated', 'color' => 'success'],
|
|
'needs_identified' => ['title' => 'Needs Identified', 'color' => 'warning'],
|
|
'meeting_arranged' => ['title' => 'Meeting Arranged', 'color' => 'info'],
|
|
'offer_accepted' => ['title' => 'Offer Accepted', 'color' => 'primary']
|
|
];
|
|
|
|
$groupedDeals = [];
|
|
foreach ($stages as $stageKey => $stageInfo) {
|
|
$stageDeals = array_filter($deals, function($deal) use ($stageKey) {
|
|
return $deal['stage'] === $stageKey;
|
|
});
|
|
|
|
if (!empty($stageDeals)) {
|
|
$totalValue = array_sum(array_column($stageDeals, 'value'));
|
|
$groupedDeals[] = [
|
|
'id' => $stageKey,
|
|
'title' => $stageInfo['title'],
|
|
'total' => '$' . number_format($totalValue, 0),
|
|
'deal_count' => count($stageDeals) . ' Deals',
|
|
'color' => $stageInfo['color'],
|
|
'deals' => array_map(function($deal) {
|
|
return [
|
|
'id' => 'deal' . $deal['id'],
|
|
'title' => $deal['title'],
|
|
'value' => '$' . number_format($deal['value'], 0) . 'k',
|
|
'date' => date('d M, Y', strtotime($deal['created_at'])),
|
|
'owner_img' => 'avatar-default.jpg',
|
|
'company' => 'Company',
|
|
'activities' => []
|
|
];
|
|
}, $stageDeals)
|
|
];
|
|
}
|
|
}
|
|
|
|
return $groupedDeals;
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e);
|
|
return [
|
|
[
|
|
'id' => 'error',
|
|
'title' => 'Error Loading Deals',
|
|
'total' => '$0',
|
|
'deal_count' => '0 Deals',
|
|
'color' => 'secondary',
|
|
'deals' => []
|
|
]
|
|
];
|
|
}
|
|
}
|
|
|
|
}
|