@@ -33,12 +35,18 @@ use App\Core\OutputSanitize;
-
-
- Filtros
-
+
+
+
+ Filtros
+
+
+
+
+
+
- Importar
+ Importar
+
+
@@ -109,11 +119,21 @@ use App\Core\OutputSanitize;
@change="toggleAllUsers($event.target.checked)">
-
Nome
-
Email
-
Função
-
Estado
-
Data Criação
+
+ Nome
+
+
+ Email
+
+
+ Função
+
+
+ Estado
+
+
+ Data Criação
+
Ações
@@ -125,7 +145,8 @@ use App\Core\OutputSanitize;
+ :checked="selectedUsers.includes(user.id)"
+ @change="toggleUser(user.id)">
@@ -154,11 +175,11 @@ use App\Core\OutputSanitize;
+ x-text="getStatusText(user)">
@@ -166,12 +187,7 @@ use App\Core\OutputSanitize;
-
-
-
-
-
-
+
@@ -279,6 +295,12 @@ use App\Core\OutputSanitize;
Inativos
+
0
@@ -321,10 +343,9 @@ use App\Core\OutputSanitize;
-
-
-
diff --git a/crm/Modules/Users/Widgets/UserActivityWidget.php b/crm/Modules/Users/Widgets/UserActivityWidget.php
index 83bffae..7757c60 100644
--- a/crm/Modules/Users/Widgets/UserActivityWidget.php
+++ b/crm/Modules/Users/Widgets/UserActivityWidget.php
@@ -112,7 +112,7 @@ class UserActivityWidget
private function getStats(): array
{
try {
- // Get user activity stats
+ // Get user activity stats - wrapped in try/catch to handle missing columns
$result = $this->db->fetch("
SELECT
-- Users online (active in last 15 minutes)
@@ -135,65 +135,57 @@ class UserActivityWidget
");
if (!$result) {
- // Try basic user count if main query fails
- try {
- $basicResult = $this->db->fetch("SELECT COUNT(*) as count FROM users WHERE deleted_at IS NULL");
- $totalUsers = (int)($basicResult['count'] ?? 0);
-
- return [
- 'users_online' => max(1, (int)($totalUsers * 0.3)),
- 'logins_today' => max(1, (int)($totalUsers * 2)),
- 'new_users' => max(0, (int)($totalUsers * 0.1)),
- 'last_login' => $totalUsers > 0 ? 'há 15m' : 'Nunca'
- ];
- } catch (\Exception $e) {
- // Final fallback if users table doesn't exist
- return [
- 'users_online' => 0,
- 'logins_today' => 0,
- 'new_users' => 0,
- 'last_login' => 'Nunca'
- ];
- }
+ throw new \Exception('Query returned no results');
}
-
- $usersOnline = (int)($result['users_online'] ?? 0);
- $loginsToday = (int)($result['logins_today'] ?? 0);
- $newUsers = (int)($result['new_users'] ?? 0);
- $lastLoginTime = $result['last_login_time'] ?? null;
-
- // Format last login time
- $lastLogin = 'Nunca';
- if ($lastLoginTime) {
- $lastLoginTimestamp = strtotime($lastLoginTime);
- $timeDiff = time() - $lastLoginTimestamp;
- if ($timeDiff < 60) {
- $lastLogin = 'agora';
- } elseif ($timeDiff < 3600) {
- $lastLogin = 'há ' . round($timeDiff / 60) . 'm';
- } elseif ($timeDiff < 86400) {
- $lastLogin = 'há ' . round($timeDiff / 3600) . 'h';
- } else {
- $lastLogin = 'há ' . round($timeDiff / 86400) . 'd';
- }
- }
-
- return [
- 'users_online' => $usersOnline,
- 'logins_today' => $loginsToday,
- 'new_users' => $newUsers,
- 'last_login' => $lastLogin
- ];
-
} catch (\Exception $e) {
- ErrorReporter::report($e);
- // Return sample data on error
- return [
- 'users_online' => 15,
- 'logins_today' => 67,
- 'new_users' => 8,
- 'last_login' => 'há 5m'
- ];
+ // Fallback: use basic user count if complex query fails
+ try {
+ $basicResult = $this->db->fetch("SELECT COUNT(*) as count FROM users WHERE deleted_at IS NULL");
+ $totalUsers = (int)($basicResult['count'] ?? 0);
+
+ return [
+ 'users_online' => max(1, (int)($totalUsers * 0.3)),
+ 'logins_today' => max(1, (int)($totalUsers * 2)),
+ 'new_users' => max(0, (int)($totalUsers * 0.1)),
+ 'last_login' => $totalUsers > 0 ? 'há 15m' : 'Nunca'
+ ];
+ } catch (\Exception $e) {
+ // Final fallback if users table doesn't exist or has issues
+ return [
+ 'users_online' => 0,
+ 'logins_today' => 0,
+ 'new_users' => 0,
+ 'last_login' => 'Nunca'
+ ];
+ }
}
+
+ $usersOnline = (int)($result['users_online'] ?? 0);
+ $loginsToday = (int)($result['logins_today'] ?? 0);
+ $newUsers = (int)($result['new_users'] ?? 0);
+ $lastLoginTime = $result['last_login_time'] ?? null;
+
+ // Format last login time
+ $lastLogin = 'Nunca';
+ if ($lastLoginTime) {
+ $lastLoginTimestamp = strtotime($lastLoginTime);
+ $timeDiff = time() - $lastLoginTimestamp;
+ if ($timeDiff < 60) {
+ $lastLogin = 'agora';
+ } elseif ($timeDiff < 3600) {
+ $lastLogin = 'há ' . round($timeDiff / 60) . 'm';
+ } elseif ($timeDiff < 86400) {
+ $lastLogin = 'há ' . round($timeDiff / 3600) . 'h';
+ } else {
+ $lastLogin = 'há ' . round($timeDiff / 86400) . 'd';
+ }
+ }
+
+ return [
+ 'users_online' => $usersOnline,
+ 'logins_today' => $loginsToday,
+ 'new_users' => $newUsers,
+ 'last_login' => $lastLogin
+ ];
}
}
\ No newline at end of file
diff --git a/crm/Modules/Views/profile/settings.php b/crm/Modules/Views/profile/settings.php
index c8f2c50..256c5ab 100644
--- a/crm/Modules/Views/profile/settings.php
+++ b/crm/Modules/Views/profile/settings.php
@@ -8,9 +8,9 @@ View::render('layouts/main.php', [
'title' => $page_title,
'description' => $page_description,
'page_content' => function() {
- View::include('components/profile-settings/header.php');
- View::include('components/profile-settings/sidebar.php');
- View::include('components/profile-settings/content.php');
+ View::render('components/profile-settings/header.php');
+ View::render('components/profile-settings/sidebar.php');
+ View::render('components/profile-settings/content.php');
},
'scripts' => function() {
?>
diff --git a/crm/Modules/Views/public-campaign-analytics.php b/crm/Modules/Views/public-campaign-analytics.php
index 3ae2fcb..c0ad94d 100644
--- a/crm/Modules/Views/public-campaign-analytics.php
+++ b/crm/Modules/Views/public-campaign-analytics.php
@@ -6,8 +6,16 @@
diff --git a/crm/Redirects/Controllers/Api/RedirectsApiController.php b/crm/Redirects/Controllers/Api/RedirectsApiController.php
deleted file mode 100644
index cfe99f4..0000000
--- a/crm/Redirects/Controllers/Api/RedirectsApiController.php
+++ /dev/null
@@ -1,307 +0,0 @@
- '302', 'label' => '302 - Temporary Redirect'],
- ['value' => '301', 'label' => '301 - Permanent Redirect'],
- ['value' => 'meta', 'label' => 'Meta Refresh'],
- ['value' => 'javascript', 'label' => 'JavaScript']
- ];
-
- echo json_encode([
- 'success' => true,
- 'data' => $types
- ]);
- } catch (\Exception $e) {
- ErrorReporter::report($e, ['context' => 'redirects_api_get_types']);
- http_response_code(500);
- echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
- }
- }
-
- /**
- * Get redirect statuses for forms
- */
- public function getStatuses(): void
- {
- try {
- header('Content-Type: application/json');
-
- $statuses = [
- ['value' => '1', 'label' => 'Active'],
- ['value' => '0', 'label' => 'Inactive']
- ];
-
- echo json_encode([
- 'success' => true,
- 'data' => $statuses
- ]);
- } catch (\Exception $e) {
- ErrorReporter::report($e, ['context' => 'redirects_api_get_statuses']);
- http_response_code(500);
- echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
- }
- }
-
- /**
- * Get filter types for redirects
- */
- public function getFilterTypes(): void
- {
- try {
- header('Content-Type: application/json');
-
- $filterTypes = [
- ['value' => 'country', 'label' => 'Country'],
- ['value' => 'browser', 'label' => 'Browser'],
- ['value' => 'device_type', 'label' => 'Device Type'],
- ['value' => 'os', 'label' => 'Operating System'],
- ['value' => 'language', 'label' => 'Language'],
- ['value' => 'hour', 'label' => 'Hour of Day'],
- ['value' => 'referer', 'label' => 'Referer']
- ];
-
- echo json_encode([
- 'success' => true,
- 'data' => $filterTypes
- ]);
- } catch (\Exception $e) {
- ErrorReporter::report($e, ['context' => 'redirects_api_get_filter_types']);
- http_response_code(500);
- echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
- }
- }
-
- /**
- * Get filter operators for redirects
- */
- public function getFilterOperators(): void
- {
- try {
- header('Content-Type: application/json');
-
- $operators = [
- ['value' => 'equals', 'label' => 'Equals'],
- ['value' => 'contains', 'label' => 'Contains'],
- ['value' => 'starts_with', 'label' => 'Starts with'],
- ['value' => 'ends_with', 'label' => 'Ends with'],
- ['value' => 'in', 'label' => 'In list'],
- ['value' => 'not_in', 'label' => 'Not in list'],
- ['value' => 'greater_than', 'label' => 'Greater than'],
- ['value' => 'less_than', 'label' => 'Less than'],
- ['value' => 'between', 'label' => 'Between']
- ];
-
- echo json_encode([
- 'success' => true,
- 'data' => $operators
- ]);
- } catch (\Exception $e) {
- ErrorReporter::report($e, ['context' => 'redirects_api_get_filter_operators']);
- http_response_code(500);
- echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
- }
- }
-
- /**
- * Get redirect settings
- */
- public function getSettings(): void
- {
- try {
- header('Content-Type: application/json');
-
- // Default settings for redirects module
- $settings = [
- 'default_redirect_type' => '302',
- 'tracking_enabled' => true,
- 'max_redirects_per_day' => 10000,
- 'enable_analytics' => true,
- 'enable_filters' => true,
- 'cache_redirects' => true,
- 'cache_duration' => 3600
- ];
-
- echo json_encode([
- 'success' => true,
- 'data' => $settings
- ]);
- } catch (\Exception $e) {
- ErrorReporter::report($e, ['context' => 'redirects_api_get_settings']);
- http_response_code(500);
- echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
- }
- }
-
- /**
- * Update redirect settings
- */
- public function updateSettings(): void
- {
- try {
- header('Content-Type: application/json');
-
- $input = json_decode(file_get_contents('php://input'), true) ?: [];
-
- // Here you would normally save settings to database
- // For now, just return success
-
- echo json_encode([
- 'success' => true,
- 'message' => 'Settings updated successfully',
- 'data' => $input
- ]);
- } catch (\Exception $e) {
- ErrorReporter::report($e, ['context' => 'redirects_api_update_settings']);
- http_response_code(500);
- echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
- }
- }
-
- /**
- * Get redirect statistics
- */
- public function statsApi(): void
- {
- try {
- header('Content-Type: application/json');
-
- $startDate = $_GET['start_date'] ?? null;
- $endDate = $_GET['end_date'] ?? null;
- $trackerId = $_GET['tracker_id'] ?? null;
- $country = $_GET['country'] ?? null;
- $device = $_GET['device'] ?? null;
- $browser = $_GET['browser'] ?? null;
- $os = $_GET['os'] ?? null;
-
- // Build WHERE clause for filtering
- $whereConditions = [];
- $params = [];
-
- if ($startDate && $endDate) {
- $whereConditions[] = "DATE(timestamp) BETWEEN ? AND ?";
- $params[] = $startDate;
- $params[] = $endDate;
- } elseif ($startDate) {
- $whereConditions[] = "DATE(timestamp) >= ?";
- $params[] = $startDate;
- } elseif ($endDate) {
- $whereConditions[] = "DATE(timestamp) <= ?";
- $params[] = $endDate;
- }
-
- if ($trackerId) {
- $whereConditions[] = "redirect_id = ?";
- $params[] = $trackerId;
- }
-
- if ($country) {
- $whereConditions[] = "country_code = ?";
- $params[] = $country;
- }
-
- if ($device) {
- $whereConditions[] = "device_type = ?";
- $params[] = $device;
- }
-
- if ($browser) {
- $whereConditions[] = "browser = ?";
- $params[] = $browser;
- }
-
- if ($os) {
- $whereConditions[] = "os = ?";
- $params[] = $os;
- }
-
- $whereClause = empty($whereConditions) ? "" : "WHERE " . implode(" AND ", $whereConditions);
-
- // Get overall stats from database
- $sql = "SELECT
- COUNT(*) as total_clicks,
- COUNT(DISTINCT session_id) as unique_clicks,
- COUNT(DISTINCT ip_address) as unique_ips,
- AVG(response_time_ms) as avg_response_time
- FROM redirect_stats " . $whereClause;
- $overviewStats = \App\Core\DatabaseManager::getInstance()->fetch($sql, $params) ?: [
- 'total_clicks' => 0,
- 'unique_clicks' => 0,
- 'unique_ips' => 0,
- 'avg_response_time' => 0
- ];
-
- // Get stats by country
- $countryWhereConditions = array_merge($whereConditions, ["country_code IS NOT NULL", "country_code != ''"]);
- $countryWhereClause = "WHERE " . implode(" AND ", $countryWhereConditions);
- $sql = "SELECT
- country_code,
- COUNT(*) as clicks,
- COUNT(DISTINCT session_id) as unique_clicks
- FROM redirect_stats
- $countryWhereClause
- GROUP BY country_code
- ORDER BY clicks DESC
- LIMIT 10";
- $countryStats = \App\Core\DatabaseManager::getInstance()->fetchAll($sql, $params) ?: [];
-
- // Get stats by device
- $deviceWhereConditions = array_merge($whereConditions, ["device_type IS NOT NULL"]);
- $deviceWhereClause = empty($deviceWhereConditions) ? "" : "WHERE " . implode(" AND ", $deviceWhereConditions);
- $sql = "SELECT
- device_type,
- COUNT(*) as clicks,
- COUNT(DISTINCT session_id) as unique_clicks
- FROM redirect_stats
- $deviceWhereClause
- GROUP BY device_type
- ORDER BY clicks DESC";
- $deviceStats = \App\Core\DatabaseManager::getInstance()->fetchAll($sql, $params) ?: [];
-
- // Get stats by browser
- $browserWhereConditions = array_merge($whereConditions, ["browser IS NOT NULL"]);
- $browserWhereClause = empty($browserWhereConditions) ? "" : "WHERE " . implode(" AND ", $browserWhereConditions);
- $sql = "SELECT
- browser,
- COUNT(*) as clicks,
- COUNT(DISTINCT session_id) as unique_clicks
- FROM redirect_stats
- $browserWhereClause
- GROUP BY browser
- ORDER BY clicks DESC";
- $browserStats = \App\Core\DatabaseManager::getInstance()->fetchAll($sql, $params) ?: [];
-
- echo json_encode([
- 'success' => true,
- 'data' => [
- 'overview' => $overviewStats,
- 'by_country' => $countryStats,
- 'by_device' => $deviceStats,
- 'by_browser' => $browserStats
- ]
- ]);
- } catch (\Exception $e) {
- ErrorReporter::report($e, ['context' => 'redirects_api_stats']);
- http_response_code(500);
- echo json_encode(['success' => false, 'message' => 'Erro interno do servidor']);
- }
- }
-}
\ No newline at end of file
diff --git a/crm/Redirects/Controllers/PublicRedirectsController.php b/crm/Redirects/Controllers/PublicRedirectsController.php
deleted file mode 100644
index 0c85ab4..0000000
--- a/crm/Redirects/Controllers/PublicRedirectsController.php
+++ /dev/null
@@ -1,370 +0,0 @@
-redirectModel = new RedirectModel();
- }
-
- public function dashboard(): void
- {
- try {
- $stats = [
- 'total_redirects' => $this->redirectModel->getCount(),
- 'active_redirects' => $this->redirectModel->getActiveCount(),
- 'total_clicks' => 0, // Analytics handled by Advertising module
- 'unique_clicks' => 0 // Analytics handled by Advertising module
- ];
-
- $recentRedirects = array_slice($this->redirectModel->getAll(), 0, 5);
-
- View::render('layouts/public-blank.php', [
- 'page_name' => 'public-redirects-dashboard',
- 'page_content' => function() use ($stats, $recentRedirects) {
- View::render('layouts/page-title.php', [
- 'pagetitle' => 'Redirects',
- 'title' => 'Dashboard',
- 'breadcrumbs' => [
- ['label' => 'Home', 'url' => '/'],
- ['label' => 'Redirects', 'url' => '/public/redirects'],
- ['label' => 'Dashboard', 'url' => null]
- ]
- ]);
- View::render('public/redirects/dashboard', [
- 'stats' => $stats,
- 'recentRedirects' => $recentRedirects,
- 'title' => 'Redirects Dashboard'
- ]);
- }
- ]);
- } catch (\Exception $e) {
- $this->handleError($e);
- }
- }
-
- public function redirects(): void
- {
- try {
- $filters = [
- 'status' => $_GET['status'] ?? '',
- 'search' => $_GET['search'] ?? ''
- ];
-
- $redirects = $this->redirectModel->getAll($filters);
-
- View::render('layouts/public-blank.php', [
- 'page_name' => 'public-redirects-list',
- 'page_content' => function() use ($redirects, $filters) {
- View::render('layouts/page-title.php', [
- 'pagetitle' => 'Redirects',
- 'title' => 'All Redirects',
- 'breadcrumbs' => [
- ['label' => 'Home', 'url' => '/'],
- ['label' => 'Redirects', 'url' => '/public/redirects'],
- ['label' => 'All Redirects', 'url' => null]
- ]
- ]);
- View::render('public/redirects/index', [
- 'redirects' => $redirects,
- 'filters' => $filters,
- 'title' => 'All Redirects'
- ]);
- }
- ]);
- } catch (\Exception $e) {
- $this->handleError($e);
- }
- }
-
- public function viewRedirect(int $id): void
- {
- try {
- $redirect = $this->redirectModel->getById($id);
- if (!$redirect) {
- header('Location: /public/redirects');
- exit;
- }
-
- $stats = $this->statsModel->getStatsByRedirect($id);
- $recentActivity = $this->statsModel->getRecentActivity($id, 10);
-
- View::render('layouts/public-blank.php', [
- 'page_name' => 'public-redirects-view',
- 'page_content' => function() use ($redirect, $stats, $recentActivity) {
- View::render('layouts/page-title.php', [
- 'pagetitle' => 'Redirects',
- 'title' => 'View Redirect',
- 'breadcrumbs' => [
- ['label' => 'Home', 'url' => '/'],
- ['label' => 'Redirects', 'url' => '/public/redirects'],
- ['label' => 'All Redirects', 'url' => '/public/redirects/redirects'],
- ['label' => 'View Redirect', 'url' => null]
- ]
- ]);
- View::render('public/redirects/view', [
- 'redirect' => $redirect,
- 'stats' => $stats,
- 'recentActivity' => $recentActivity,
- 'title' => 'View Redirect'
- ]);
- }
- ]);
- } catch (\Exception $e) {
- $this->handleError($e);
- }
- }
-
- public function stats(): void
- {
- try {
- $startDate = $_GET['start_date'] ?? date('Y-m-d', strtotime('-30 days'));
- $endDate = $_GET['end_date'] ?? date('Y-m-d');
-
- // Get overall stats from database
- $sql = "SELECT
- COUNT(*) as total_clicks,
- COUNT(DISTINCT session_id) as unique_clicks,
- COUNT(DISTINCT ip_address) as unique_ips,
- AVG(response_time_ms) as avg_response_time
- FROM redirect_stats";
- $overviewStats = $this->statsModel->getDb()->fetch($sql) ?: [
- 'total_clicks' => 0,
- 'unique_clicks' => 0,
- 'unique_ips' => 0,
- 'avg_response_time' => 0
- ];
-
- // Get stats by country
- $sql = "SELECT
- country_code,
- COALESCE(NULLIF(country_name, ''), country_code) AS country_name,
- COUNT(*) as clicks,
- COUNT(DISTINCT session_id) as unique_clicks
- FROM redirect_stats
- WHERE country_code IS NOT NULL AND country_code != ''
- GROUP BY country_code, country_name
- ORDER BY clicks DESC
- LIMIT 10";
- $countryStats = $this->statsModel->getDb()->fetchAll($sql) ?: [];
-
- // Get stats by device
- $sql = "SELECT
- device_type,
- COUNT(*) as clicks,
- COUNT(DISTINCT session_id) as unique_clicks
- FROM redirect_stats
- WHERE device_type IS NOT NULL
- GROUP BY device_type
- ORDER BY clicks DESC";
- $deviceStats = $this->statsModel->getDb()->fetchAll($sql) ?: [];
-
- // Get stats by browser
- $sql = "SELECT
- browser,
- COUNT(*) as clicks,
- COUNT(DISTINCT session_id) as unique_clicks
- FROM redirect_stats
- WHERE browser IS NOT NULL AND browser != 'Unknown'
- GROUP BY browser
- ORDER BY clicks DESC";
- $browserStats = $this->statsModel->getDb()->fetchAll($sql) ?: [];
-
- View::render('layouts/public-blank.php', [
- 'page_name' => 'public-redirects-stats',
- 'page_content' => function() use ($overviewStats, $countryStats, $deviceStats, $browserStats, $startDate, $endDate) {
- View::render('layouts/page-title.php', [
- 'pagetitle' => 'Redirects',
- 'title' => 'Analytics',
- 'breadcrumbs' => [
- ['label' => 'Home', 'url' => '/'],
- ['label' => 'Redirects', 'url' => '/public/redirects'],
- ['label' => 'Analytics', 'url' => null]
- ]
- ]);
- View::render('public/redirects/stats/index', [
- 'overviewStats' => $overviewStats,
- 'countryStats' => $countryStats,
- 'deviceStats' => $deviceStats,
- 'browserStats' => $browserStats,
- 'startDate' => $startDate,
- 'endDate' => $endDate,
- 'title' => 'Analytics'
- ]);
- }
- ]);
- } catch (\Exception $e) {
- $this->handleError($e);
- }
- }
-
- public function statsApi(): void
- {
- try {
- header('Content-Type: application/json');
-
- $startDate = $_GET['start_date'] ?? null;
- $endDate = $_GET['end_date'] ?? null;
- $trackerId = $_GET['tracker_id'] ?? null;
- $country = $_GET['country'] ?? null;
- $device = $_GET['device'] ?? null;
- $browser = $_GET['browser'] ?? null;
- $os = $_GET['os'] ?? null;
-
- // Build WHERE clause for filtering
- $whereConditions = [];
- $params = [];
-
- if ($startDate && $endDate) {
- $whereConditions[] = "DATE(timestamp) BETWEEN ? AND ?";
- $params[] = $startDate;
- $params[] = $endDate;
- } elseif ($startDate) {
- $whereConditions[] = "DATE(timestamp) >= ?";
- $params[] = $startDate;
- } elseif ($endDate) {
- $whereConditions[] = "DATE(timestamp) <= ?";
- $params[] = $endDate;
- }
-
- if ($trackerId) {
- $whereConditions[] = "redirect_id = ?";
- $params[] = $trackerId;
- }
-
- if ($country) {
- $whereConditions[] = "country_code = ?";
- $params[] = $country;
- }
-
- if ($device) {
- $whereConditions[] = "device_type = ?";
- $params[] = $device;
- }
-
- if ($browser) {
- $whereConditions[] = "browser = ?";
- $params[] = $browser;
- }
-
- if ($os) {
- $whereConditions[] = "os = ?";
- $params[] = $os;
- }
-
- $whereClause = empty($whereConditions) ? "" : "WHERE " . implode(" AND ", $whereConditions);
-
- // Get overall stats from database
- $sql = "SELECT
- COUNT(*) as total_clicks,
- COUNT(DISTINCT session_id) as unique_clicks,
- COUNT(DISTINCT ip_address) as unique_ips,
- AVG(response_time_ms) as avg_response_time
- FROM redirect_stats " . $whereClause;
- $overviewStats = $this->statsModel->getDb()->fetch($sql, $params) ?: [
- 'total_clicks' => 0,
- 'unique_clicks' => 0,
- 'unique_ips' => 0,
- 'avg_response_time' => 0
- ];
-
- // Get stats by country
- $countryWhereConditions = array_merge($whereConditions, ["country_code IS NOT NULL", "country_code != ''"]);
- $countryWhereClause = "WHERE " . implode(" AND ", $countryWhereConditions);
- $sql = "SELECT
- country_code,
- COALESCE(NULLIF(country_name, ''), country_code) AS country_name,
- COUNT(*) as clicks,
- COUNT(DISTINCT session_id) as unique_clicks
- FROM redirect_stats
- $countryWhereClause
- GROUP BY country_code, country_name
- ORDER BY clicks DESC
- LIMIT 10";
- $countryStats = $this->statsModel->getDb()->fetchAll($sql, $params) ?: [];
-
- // Get stats by device
- $deviceWhereConditions = array_merge($whereConditions, ["device_type IS NOT NULL"]);
- $deviceWhereClause = empty($deviceWhereConditions) ? "" : "WHERE " . implode(" AND ", $deviceWhereConditions);
- $sql = "SELECT
- device_type,
- COUNT(*) as clicks,
- COUNT(DISTINCT session_id) as unique_clicks
- FROM redirect_stats
- $deviceWhereClause
- GROUP BY device_type
- ORDER BY clicks DESC";
- $deviceStats = $this->statsModel->getDb()->fetchAll($sql, $params) ?: [];
-
- // Get stats by browser
- $browserWhereConditions = array_merge($whereConditions, ["browser IS NOT NULL", "browser != 'Unknown'"]);
- $browserWhereClause = "WHERE " . implode(" AND ", $browserWhereConditions);
- $sql = "SELECT
- browser,
- COUNT(*) as clicks,
- COUNT(DISTINCT session_id) as unique_clicks
- FROM redirect_stats
- $browserWhereClause
- GROUP BY browser
- ORDER BY clicks DESC";
- $browserStats = $this->statsModel->getDb()->fetchAll($sql, $params) ?: [];
-
- echo json_encode([
- 'overview' => $overviewStats,
- 'country' => $countryStats,
- 'device' => $deviceStats,
- 'browser' => $browserStats
- ]);
- } catch (\Exception $e) {
- http_response_code(500);
- echo json_encode(['error' => 'Failed to load statistics']);
- }
- }
-
- public function processRedirect(string $cuid): void
- {
- try {
- $redirect = $this->redirectModel->getByCuid($cuid);
- if (!$redirect) {
- http_response_code(404);
- echo "Redirect not found";
- return;
- }
-
- if ($redirect['status'] != 1) {
- http_response_code(410);
- echo "Redirect is inactive";
- return;
- }
-
- // Simple redirect - no complex processing needed
- $targetUrl = $redirect['target_url'];
-
- // Analytics are handled by the Advertising module
- // Just perform the redirect
- header("Location: " . $targetUrl, true, (int)$redirect['redirect_type']);
- exit;
-
- } catch (\Exception $e) {
- http_response_code(500);
- echo "Internal server error";
- }
- }
-
- private function handleError(\Exception $e): void
- {
- error_log("PublicRedirectsController error: " . $e->getMessage());
- http_response_code(500);
- echo "Internal server error";
- }
-}
\ No newline at end of file
diff --git a/crm/Redirects/Controllers/RedirectsApiController.php b/crm/Redirects/Controllers/RedirectsApiController.php
deleted file mode 100644
index 4faf97a..0000000
--- a/crm/Redirects/Controllers/RedirectsApiController.php
+++ /dev/null
@@ -1,757 +0,0 @@
-redirectModel = new RedirectModel();
- $this->filterModel = new RedirectFilterModel();
- $this->statsModel = new RedirectStatsModel();
- $this->autoCreatorService = new RedirectAutoCreatorService();
- }
-
- public function create(): void
- {
- try {
- $input = json_decode(file_get_contents('php://input'), true) ?: [];
-
- $data = [
- 'name' => Sanitize::string($input['name'] ?? ''),
- 'source_url' => Sanitize::url($input['source_url'] ?? ''),
- 'target_url' => Sanitize::url($input['target_url'] ?? ''),
- 'fallback_url' => Sanitize::url($input['fallback_url'] ?? ''),
- 'status' => (int)($input['status'] ?? 1),
- 'redirect_type' => Sanitize::string($input['redirect_type'] ?? '302'),
- 'tracking_enabled' => (int)($input['tracking_enabled'] ?? 1),
- 'max_clicks' => !empty($input['max_clicks']) ? (int)$input['max_clicks'] : null,
- 'expires_at' => !empty($input['expires_at']) ? $input['expires_at'] : null,
- 'created_by' => 1
- ];
-
- if (empty($data['name']) || empty($data['target_url'])) {
- $this->errorResponse('Name and target URL are required', 400);
- return;
- }
-
- // ✅ Create redirect and associated creative
- $success = $this->redirectModel->createWithCreative($data);
-
- if ($success) {
- // 🚀 AUTO-CREATE: multisite + campaign + creative
- $autoResult = $this->autoCreatorService->createCompleteRedirect($data);
-
- if ($autoResult['success']) {
- $this->successResponse([
- 'redirect_created' => true,
- 'multisite_created' => $autoResult['site_group_id'],
- 'campaign_created' => $autoResult['campaign_id'],
- 'creative_created' => $autoResult['creative_id']
- ], 'Redirect created successfully with automatic multisite and campaign setup');
- } else {
- $this->successResponse([], 'Redirect created but multisite setup failed: ' . $autoResult['message']);
- }
- } else {
- $this->errorResponse('Failed to create redirect with creative', 500);
- }
- } catch (\Exception $e) {
- $this->errorResponse('Server error: ' . $e->getMessage(), 500);
- }
- }
-
- public function index(): void
- {
- try {
- // Bearer token auth for server-to-server
- $authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
- $token = null;
- if (stripos($authHeader, 'Bearer ') === 0) {
- $token = trim(substr($authHeader, 7));
- }
-
- // Load expected key from env or fallback by parsing .env
- $expectedKey = $_ENV['REDIRECTS_API_KEY'] ?? getenv('REDIRECTS_API_KEY') ?? '';
- if (!$expectedKey) {
- $candidates = [
- realpath(__DIR__ . '/../../../../.env') ?: '',
- realpath(__DIR__ . '/../../../.env') ?: '',
- '/data/wwwroot/redirect.moneyflix.com/.env'
- ];
- foreach ($candidates as $envPath) {
- if ($envPath && is_file($envPath)) {
- $lines = @file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
- foreach ($lines as $line) {
- if (strpos($line, 'REDIRECTS_API_KEY=') === 0) {
- $expectedKey = trim(substr($line, strlen('REDIRECTS_API_KEY=')));
- $expectedKey = trim($expectedKey, "\"' ");
- break 2;
- }
- }
- }
- }
- }
-
- if (!$expectedKey || !$token || !hash_equals($expectedKey, $token)) {
- $this->errorResponse('Unauthorized', 401);
- return;
- }
-
- $filters = [
- 'status' => $_GET['status'] ?? '',
- 'search' => $_GET['search'] ?? ''
- ];
-
- $redirects = $this->redirectModel->getAll($filters);
-
- $this->successResponse(['redirects' => $redirects], 'Redirects retrieved successfully');
- } catch (\Exception $e) {
- $this->errorResponse('Server error: ' . $e->getMessage(), 500);
- }
- }
-
- public function update(int $id): void
- {
- try {
- $redirect = $this->redirectModel->getById($id);
- if (!$redirect) {
- $this->errorResponse('Redirect not found', 404);
- return;
- }
-
- $input = json_decode(file_get_contents('php://input'), true) ?: [];
-
- $data = [
- 'name' => Sanitize::string($input['name'] ?? $redirect['name']),
- 'source_url' => Sanitize::url($input['source_url'] ?? $redirect['source_url']),
- 'target_url' => Sanitize::url($input['target_url'] ?? $redirect['target_url']),
- 'fallback_url' => Sanitize::url($input['fallback_url'] ?? $redirect['fallback_url']),
- 'status' => (int)($input['status'] ?? $redirect['status']),
- 'redirect_type' => Sanitize::string($input['redirect_type'] ?? $redirect['redirect_type']),
- 'tracking_enabled' => (int)($input['tracking_enabled'] ?? $redirect['tracking_enabled']),
- 'max_clicks' => !empty($input['max_clicks']) ? (int)$input['max_clicks'] : $redirect['max_clicks'],
- 'expires_at' => !empty($input['expires_at']) ? $input['expires_at'] : $redirect['expires_at']
- ];
-
- $success = $this->redirectModel->updateWithCreative($id, $data);
-
- if ($success) {
- // 🚀 AUTO-UPDATE: Update associated creative via Advertising module
- $redirectCreativeService = new \App\Modules\Redirects\Services\RedirectCreativeService();
- $creativeResult = $redirectCreativeService->updateCreativeFromRedirect($id, $data);
-
- if ($creativeResult) {
- $this->successResponse([
- 'redirect_updated' => true,
- 'creative_updated' => true
- ], 'Redirect updated successfully with Advertising module integration');
- } else {
- $this->successResponse([], 'Redirect updated but Advertising module update failed');
- }
- } else {
- $this->errorResponse('Failed to update redirect with creative', 500);
- }
- } catch (\Exception $e) {
- $this->errorResponse('Server error: ' . $e->getMessage(), 500);
- }
- }
-
- public function show(int $id): void
- {
- try {
- $redirect = $this->redirectModel->getById($id);
- if (!$redirect) {
- $this->errorResponse('Redirect not found', 404);
- return;
- }
-
- $this->successResponse(['redirect' => $redirect], 'Redirect retrieved successfully');
- } catch (\Exception $e) {
- $this->errorResponse('Server error: ' . $e->getMessage(), 500);
- }
- }
-
- public function delete(int $id): void
- {
- try {
- $redirect = $this->redirectModel->getById($id);
- if (!$redirect) {
- $this->errorResponse('Redirect not found', 404);
- return;
- }
-
- $success = $this->redirectModel->deleteWithCreative($id);
-
- if ($success) {
- $this->successResponse([], 'Redirect deleted successfully with creative integration');
- } else {
- $this->errorResponse('Failed to delete redirect with creative', 500);
- }
- } catch (\Exception $e) {
- $this->errorResponse('Server error: ' . $e->getMessage(), 500);
- }
- }
-
- public function getStats(int $id): void
- {
- try {
- $redirect = $this->redirectModel->getById($id);
- if (!$redirect) {
- $this->errorResponse('Redirect not found', 404);
- return;
- }
-
- $startDate = $_GET['start_date'] ?? null;
- $endDate = $_GET['end_date'] ?? null;
-
- $stats = [
- 'overview' => $this->statsModel->getStatsByRedirect($id, $startDate, $endDate),
- 'by_country' => $this->statsModel->getStatsByCountry($id, $startDate, $endDate),
- 'by_device' => $this->statsModel->getStatsByDevice($id, $startDate, $endDate),
- 'by_browser' => $this->statsModel->getStatsByBrowser($id, $startDate, $endDate),
- 'by_hour' => $this->statsModel->getStatsByHour($id, $startDate, $endDate),
- 'recent_activity' => $this->statsModel->getRecentActivity($id, 10)
- ];
-
- $this->successResponse($stats, 'Stats retrieved successfully');
- } catch (\Exception $e) {
- $this->errorResponse('Server error: ' . $e->getMessage(), 500);
- }
- }
-
- public function getFilters(int $id): void
- {
- try {
- $redirect = $this->redirectModel->getById($id);
- if (!$redirect) {
- $this->errorResponse('Redirect not found', 404);
- return;
- }
-
- $filters = $this->filterModel->getByRedirectId($id);
- $this->successResponse($filters, 'Filters retrieved successfully');
- } catch (\Exception $e) {
- $this->errorResponse('Server error: ' . $e->getMessage(), 500);
- }
- }
-
- public function addFilter(int $id): void
- {
- try {
- $redirect = $this->redirectModel->getById($id);
- if (!$redirect) {
- $this->errorResponse('Redirect not found', 404);
- return;
- }
-
- $data = [
- 'redirect_id' => $id,
- 'filter_type' => Sanitize::string($_POST['filter_type'] ?? ''),
- 'filter_value' => Sanitize::string($_POST['filter_value'] ?? ''),
- 'filter_operator' => Sanitize::string($_POST['filter_operator'] ?? 'equals'),
- 'filter_value_secondary' => Sanitize::string($_POST['filter_value_secondary'] ?? null),
- 'priority' => (int)($_POST['priority'] ?? 0),
- 'is_active' => (int)($_POST['is_active'] ?? 1)
- ];
-
- if (empty($data['filter_type']) || empty($data['filter_value'])) {
- $this->errorResponse('Filter type and value are required', 400);
- return;
- }
-
- $success = $this->filterModel->create($data);
-
- if ($success) {
- $this->successResponse([], 'Filter added successfully');
- } else {
- $this->errorResponse('Failed to add filter', 500);
- }
- } catch (\Exception $e) {
- $this->errorResponse('Server error: ' . $e->getMessage(), 500);
- }
- }
-
- public function deleteFilter(int $id, int $filterId): void
- {
- try {
- $redirect = $this->redirectModel->getById($id);
- if (!$redirect) {
- $this->errorResponse('Redirect not found', 404);
- return;
- }
-
- $success = $this->filterModel->delete($filterId);
-
- if ($success) {
- $this->successResponse([], 'Filter deleted successfully');
- } else {
- $this->errorResponse('Failed to delete filter', 500);
- }
- } catch (\Exception $e) {
- $this->errorResponse('Server error: ' . $e->getMessage(), 500);
- }
- }
-
- /**
- * Obter os site groups associados a um redirect específico
- */
- public function getSiteGroups(int $id): void
- {
- try {
- $redirect = $this->redirectModel->getById($id);
- if (!$redirect) {
- $this->errorResponse('Redirect not found', 404);
- return;
- }
-
- // Query para obter os site groups associados
- $sql = "
- SELECT
- rsgm.*,
- asg.name as site_group_name,
- asg.description as site_group_description,
- asg.status as site_group_status,
- ac.name as creative_name,
- ac.creative_type
- FROM redirect_site_group_mapping rsgm
- LEFT JOIN advertising_site_groups asg ON rsgm.site_group_id = asg.id
- LEFT JOIN advertising_creatives ac ON rsgm.creative_id = ac.id
- WHERE rsgm.redirect_id = ?
- ORDER BY rsgm.priority DESC, rsgm.created_at DESC
- ";
-
- $db = DatabaseManager::getInstance();
- $siteGroups = $db->fetchAll($sql, [$id]);
-
- $this->successResponse([
- 'redirect_id' => $id,
- 'site_groups' => $siteGroups
- ], 'Site groups retrieved successfully');
- } catch (\Exception $e) {
- $this->errorResponse('Server error: ' . $e->getMessage(), 500);
- }
- }
-
- /**
- * Associar um redirect com um site group
- */
- public function associateSiteGroup(int $id): void
- {
- try {
- $redirect = $this->redirectModel->getById($id);
- if (!$redirect) {
- $this->errorResponse('Redirect not found', 404);
- return;
- }
-
- $input = json_decode(file_get_contents('php://input'), true) ?: [];
-
- $data = [
- 'redirect_id' => $id,
- 'site_group_id' => (int)($input['site_group_id'] ?? 0),
- 'creative_id' => !empty($input['creative_id']) ? (int)$input['creative_id'] : null,
- 'mapping_type' => Sanitize::string($input['mapping_type'] ?? 'primary'),
- 'priority' => (int)($input['priority'] ?? 0),
- 'geo_targeting' => !empty($input['geo_targeting']) ? json_encode($input['geo_targeting']) : null,
- 'device_targeting' => !empty($input['device_targeting']) ? json_encode($input['device_targeting']) : null,
- 'time_targeting' => !empty($input['time_targeting']) ? json_encode($input['time_targeting']) : null,
- 'traffic_percentage' => (float)($input['traffic_percentage'] ?? 100.00),
- 'is_active' => (int)($input['is_active'] ?? 1)
- ];
-
- if (empty($data['site_group_id'])) {
- $this->errorResponse('Site group ID is required', 400);
- return;
- }
-
- // Verificar se o site group existe
- $db = DatabaseManager::getInstance();
- $siteGroup = $db->fetch("SELECT id FROM advertising_site_groups WHERE id = ?", [$data['site_group_id']]);
- if (!$siteGroup) {
- $this->errorResponse('Site group not found', 404);
- return;
- }
-
- // Verificar se já existe uma associação
- $existing = $db->fetch("SELECT id FROM redirect_site_group_mapping WHERE redirect_id = ? AND site_group_id = ?", [$id, $data['site_group_id']]);
- if ($existing) {
- $this->errorResponse('Association already exists', 409);
- return;
- }
-
- // Inserir a associação
- $sql = "
- INSERT INTO redirect_site_group_mapping (
- redirect_id, site_group_id, creative_id, mapping_type,
- priority, geo_targeting, device_targeting, time_targeting,
- traffic_percentage, is_active
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- ";
-
- $success = $db->query($sql, [
- $data['redirect_id'], $data['site_group_id'], $data['creative_id'],
- $data['mapping_type'], $data['priority'], $data['geo_targeting'],
- $data['device_targeting'], $data['time_targeting'], $data['traffic_percentage'],
- $data['is_active']
- ]);
-
- if ($success) {
- $this->successResponse([], 'Site group associated successfully');
- } else {
- $this->errorResponse('Failed to associate site group', 500);
- }
- } catch (\Exception $e) {
- $this->errorResponse('Server error: ' . $e->getMessage(), 500);
- }
- }
-
- /**
- * Remover a associação de um redirect com um site group
- */
- public function removeSiteGroup(int $id, int $mappingId): void
- {
- try {
- $redirect = $this->redirectModel->getById($id);
- if (!$redirect) {
- $this->errorResponse('Redirect not found', 404);
- return;
- }
-
- // Verificar se a associação existe e pertence ao redirect
- $db = DatabaseManager::getInstance();
- $mapping = $db->fetch("SELECT id FROM redirect_site_group_mapping WHERE id = ? AND redirect_id = ?", [$mappingId, $id]);
- if (!$mapping) {
- $this->errorResponse('Mapping not found', 404);
- return;
- }
-
- // Remover a associação
- $success = $db->query("DELETE FROM redirect_site_group_mapping WHERE id = ?", [$mappingId]);
-
- if ($success) {
- $this->successResponse([], 'Site group association removed successfully');
- } else {
- $this->errorResponse('Failed to remove site group association', 500);
- }
- } catch (\Exception $e) {
- $this->errorResponse('Server error: ' . $e->getMessage(), 500);
- }
- }
-
- /**
- * Atualizar uma associação existente de um redirect com um site group
- */
- public function updateSiteGroup(int $id, int $mappingId): void
- {
- try {
- $redirect = $this->redirectModel->getById($id);
- if (!$redirect) {
- $this->errorResponse('Redirect not found', 404);
- return;
- }
-
- // Verificar se a associação existe e pertence ao redirect
- $db = DatabaseManager::getInstance();
- $mapping = $db->fetch("SELECT id FROM redirect_site_group_mapping WHERE id = ? AND redirect_id = ?", [$mappingId, $id]);
- if (!$mapping) {
- $this->errorResponse('Mapping not found', 404);
- return;
- }
-
- $input = json_decode(file_get_contents('php://input'), true) ?: [];
-
- $data = [
- 'creative_id' => !empty($input['creative_id']) ? (int)$input['creative_id'] : null,
- 'mapping_type' => Sanitize::string($input['mapping_type'] ?? 'primary'),
- 'priority' => (int)($input['priority'] ?? 0),
- 'geo_targeting' => !empty($input['geo_targeting']) ? json_encode($input['geo_targeting']) : null,
- 'device_targeting' => !empty($input['device_targeting']) ? json_encode($input['device_targeting']) : null,
- 'time_targeting' => !empty($input['time_targeting']) ? json_encode($input['time_targeting']) : null,
- 'traffic_percentage' => (float)($input['traffic_percentage'] ?? 100.00),
- 'is_active' => (int)($input['is_active'] ?? 1)
- ];
-
- // Atualizar a associação
- $sql = "
- UPDATE redirect_site_group_mapping SET
- creative_id = ?, mapping_type = ?, priority = ?,
- geo_targeting = ?, device_targeting = ?, time_targeting = ?,
- traffic_percentage = ?, is_active = ?
- WHERE id = ?
- ";
-
- $success = $db->query($sql, [
- $data['creative_id'], $data['mapping_type'], $data['priority'],
- $data['geo_targeting'], $data['device_targeting'], $data['time_targeting'],
- $data['traffic_percentage'], $data['is_active'], $mappingId
- ]);
-
- if ($success) {
- $this->successResponse([], 'Site group association updated successfully');
- } else {
- $this->errorResponse('Failed to update site group association', 500);
- }
- } catch (\Exception $e) {
- $this->errorResponse('Server error: ' . $e->getMessage(), 500);
- }
- }
-
- public function getOverviewStats(): void
- {
- try {
- $startDate = $_GET['start_date'] ?? date('Y-m-d', strtotime('-30 days'));
- $endDate = $_GET['end_date'] ?? date('Y-m-d');
-
- // Implementar estatísticas gerais
- $stats = [
- 'total_clicks' => 0,
- 'unique_clicks' => 0,
- 'unique_ips' => 0,
- 'avg_response_time' => 0
- ];
-
- $this->successResponse($stats, 'Overview stats retrieved successfully');
- } catch (\Exception $e) {
- $this->errorResponse('Server error: ' . $e->getMessage(), 500);
- }
- }
-
- public function getStatsByCountry(): void
- {
- try {
- $startDate = $_GET['start_date'] ?? date('Y-m-d', strtotime('-30 days'));
- $endDate = $_GET['end_date'] ?? date('Y-m-d');
-
- // Implementar estatísticas por país
- $stats = [];
-
- $this->successResponse($stats, 'Country stats retrieved successfully');
- } catch (\Exception $e) {
- $this->errorResponse('Server error: ' . $e->getMessage(), 500);
- }
- }
-
- public function getStatsByDevice(): void
- {
- try {
- $startDate = $_GET['start_date'] ?? date('Y-m-d', strtotime('-30 days'));
- $endDate = $_GET['end_date'] ?? date('Y-m-d');
-
- // Implementar estatísticas por dispositivo
- $stats = [];
-
- $this->successResponse($stats, 'Device stats retrieved successfully');
- } catch (\Exception $e) {
- $this->errorResponse('Server error: ' . $e->getMessage(), 500);
- }
- }
-
- public function getStatsByBrowser(): void
- {
- try {
- $startDate = $_GET['start_date'] ?? date('Y-m-d', strtotime('-30 days'));
- $endDate = $_GET['end_date'] ?? date('Y-m-d');
-
- // Implementar estatísticas por browser
- $stats = [];
-
- $this->successResponse($stats, 'Browser stats retrieved successfully');
- } catch (\Exception $e) {
- $this->errorResponse('Server error: ' . $e->getMessage(), 500);
- }
- }
-
- public function getStatsByHour(): void
- {
- try {
- $startDate = $_GET['start_date'] ?? date('Y-m-d', strtotime('-30 days'));
- $endDate = $_GET['end_date'] ?? date('Y-m-d');
-
- // Implementar estatísticas por hora
- $stats = [];
-
- $this->successResponse($stats, 'Hour stats retrieved successfully');
- } catch (\Exception $e) {
- $this->errorResponse('Server error: ' . $e->getMessage(), 500);
- }
- }
-
- /**
- * Get redirects as creatives for Advertising module integration
- */
- public function getRedirectCreatives(): void
- {
- try {
- $creativeService = new \App\Modules\Redirects\Services\RedirectCreativeService();
- $redirectCreatives = $creativeService->getAllRedirectCreatives();
-
- $this->successResponse([
- 'redirect_creatives' => $redirectCreatives,
- 'total' => count($redirectCreatives)
- ], 'Redirect creatives retrieved successfully');
- } catch (\Exception $e) {
- $this->errorResponse('Server error: ' . $e->getMessage(), 500);
- }
- }
-
- /**
- * Migrate all existing redirects to creatives
- */
- public function migrateRedirectsToCreatives(): void
- {
- try {
- $creativeService = new \App\Modules\Redirects\Services\RedirectCreativeService();
- $results = $creativeService->migrateAllRedirects();
-
- $successCount = count(array_filter($results, fn($r) => $r['success']));
- $totalCount = count($results);
-
- $this->successResponse([
- 'migration_results' => $results,
- 'summary' => [
- 'total_redirects' => $totalCount,
- 'successful_migrations' => $successCount,
- 'failed_migrations' => $totalCount - $successCount
- ]
- ], "Migration completed: {$successCount}/{$totalCount} redirects migrated successfully");
- } catch (\Exception $e) {
- $this->errorResponse('Migration failed: ' . $e->getMessage(), 500);
- }
- }
-
- public function statsApi(): void
- {
- try {
- header('Content-Type: application/json');
-
- $startDate = $_GET['start_date'] ?? null;
- $endDate = $_GET['end_date'] ?? null;
- $trackerId = $_GET['tracker_id'] ?? null;
- $country = $_GET['country'] ?? null;
- $device = $_GET['device'] ?? null;
- $browser = $_GET['browser'] ?? null;
- $os = $_GET['os'] ?? null;
-
- // Build WHERE clause for filtering
- $whereConditions = [];
- $params = [];
-
- if ($startDate && $endDate) {
- $whereConditions[] = "DATE(timestamp) BETWEEN ? AND ?";
- $params[] = $startDate;
- $params[] = $endDate;
- } elseif ($startDate) {
- $whereConditions[] = "DATE(timestamp) >= ?";
- $params[] = $startDate;
- } elseif ($endDate) {
- $whereConditions[] = "DATE(timestamp) <= ?";
- $params[] = $endDate;
- }
-
- if ($trackerId) {
- $whereConditions[] = "redirect_id = ?";
- $params[] = $trackerId;
- }
-
- if ($country) {
- $whereConditions[] = "country_code = ?";
- $params[] = $country;
- }
-
- if ($device) {
- $whereConditions[] = "device_type = ?";
- $params[] = $device;
- }
-
- if ($browser) {
- $whereConditions[] = "browser = ?";
- $params[] = $browser;
- }
-
- if ($os) {
- $whereConditions[] = "os = ?";
- $params[] = $os;
- }
-
- $whereClause = empty($whereConditions) ? "" : "WHERE " . implode(" AND ", $whereConditions);
-
- // Get overall stats from database
- $sql = "SELECT
- COUNT(*) as total_clicks,
- COUNT(DISTINCT session_id) as unique_clicks,
- COUNT(DISTINCT ip_address) as unique_ips,
- AVG(response_time_ms) as avg_response_time
- FROM redirect_stats " . $whereClause;
- $overviewStats = DatabaseManager::getInstance()->fetch($sql, $params) ?: [
- 'total_clicks' => 0,
- 'unique_clicks' => 0,
- 'unique_ips' => 0,
- 'avg_response_time' => 0
- ];
-
- // Get stats by country
- $countryWhereConditions = array_merge($whereConditions, ["country_code IS NOT NULL", "country_code != ''"]);
- $countryWhereClause = "WHERE " . implode(" AND ", $countryWhereConditions);
- $sql = "SELECT
- country_code,
- COUNT(*) as clicks,
- COUNT(DISTINCT session_id) as unique_clicks
- FROM redirect_stats
- $countryWhereClause
- GROUP BY country_code
- ORDER BY clicks DESC
- LIMIT 10";
- $countryStats = DatabaseManager::getInstance()->fetchAll($sql, $params) ?: [];
-
- // Get stats by device
- $deviceWhereConditions = array_merge($whereConditions, ["device_type IS NOT NULL"]);
- $deviceWhereClause = empty($deviceWhereConditions) ? "" : "WHERE " . implode(" AND ", $deviceWhereConditions);
- $sql = "SELECT
- device_type,
- COUNT(*) as clicks,
- COUNT(DISTINCT session_id) as unique_clicks
- FROM redirect_stats
- $deviceWhereClause
- GROUP BY device_type
- ORDER BY clicks DESC";
- $deviceStats = DatabaseManager::getInstance()->fetchAll($sql, $params) ?: [];
-
- // Get stats by browser
- $browserWhereConditions = array_merge($whereConditions, ["browser IS NOT NULL", "browser != 'Unknown'"]);
- $browserWhereClause = "WHERE " . implode(" AND ", $browserWhereConditions);
- $sql = "SELECT
- browser,
- COUNT(*) as clicks,
- COUNT(DISTINCT session_id) as unique_clicks
- FROM redirect_stats
- $browserWhereClause
- GROUP BY browser
- ORDER BY clicks DESC";
- $browserStats = DatabaseManager::getInstance()->fetchAll($sql, $params) ?: [];
-
- $this->successResponse([
- 'overview' => $overviewStats,
- 'by_country' => $countryStats,
- 'by_device' => $deviceStats,
- 'by_browser' => $browserStats
- ], 'Statistics retrieved successfully');
- } catch (\Exception $e) {
- $this->errorResponse('Failed to load statistics: ' . $e->getMessage(), 500);
- }
- }
-
-
-}
\ No newline at end of file
diff --git a/crm/Redirects/Controllers/RedirectsController.php b/crm/Redirects/Controllers/RedirectsController.php
deleted file mode 100644
index b8fd9f2..0000000
--- a/crm/Redirects/Controllers/RedirectsController.php
+++ /dev/null
@@ -1,562 +0,0 @@
-redirectModel = new RedirectModel();
- $this->filterModel = new RedirectFilterModel();
- $this->statsModel = new RedirectStatsModel();
- $this->processor = new RedirectProcessor();
- }
-
- public function dashboard(): void
- {
- $stats = [
- 'total_redirects' => $this->redirectModel->getCount(),
- 'active_redirects' => $this->redirectModel->getActiveCount(),
- 'inactive_redirects' => $this->redirectModel->getInactiveCount(),
- 'recent_redirects' => array_slice($this->redirectModel->getAll(), 0, 5)
- ];
-
- View::render('layouts/main.php', [
- 'title' => 'Redirects Dashboard',
- 'page_name' => 'apps-redirects-dashboard',
- 'page_content' => function() use ($stats) {
- View::render('layouts/page-title.php', [
- 'pagetitle' => 'Redirects',
- 'title' => 'Dashboard',
- 'breadcrumbs' => [
- ['label' => 'Home', 'url' => '/'],
- ['label' => 'Redirects', 'url' => '/redirects'],
- ['label' => 'Dashboard', 'url' => null]
- ]
- ]);
- View::render('@redirects/dashboard', ['stats' => $stats, 'title' => 'Redirects Dashboard']);
- }
- ]);
- }
-
- public function redirects(): void
- {
- $filters = [
- 'status' => Sanitize::string($_GET['status'] ?? ''),
- 'search' => Sanitize::string($_GET['search'] ?? '')
- ];
-
- $redirects = $this->redirectModel->getAll($filters);
-
- View::render('layouts/main.php', [
- 'title' => 'All Redirects',
- 'page_name' => 'apps-redirects-list',
- 'page_content' => function() use ($redirects, $filters) {
- View::render('layouts/page-title.php', [
- 'pagetitle' => 'Redirects',
- 'title' => 'All Redirects',
- 'breadcrumbs' => [
- ['label' => 'Home', 'url' => '/'],
- ['label' => 'Redirects', 'url' => '/redirects'],
- ['label' => 'All Redirects', 'url' => null]
- ]
- ]);
- View::render('@redirects/redirects/index', ['redirects' => $redirects, 'filters' => $filters, 'title' => 'All Redirects']);
- }
- ]);
- }
-
- public function createRedirect(): void
- {
- $config = require __DIR__ . '/../config.php';
-
- View::render('layouts/main.php', [
- 'title' => 'Create Redirect',
- 'page_name' => 'apps-redirects-create',
- 'page_content' => function() use ($config) {
- View::render('layouts/page-title.php', [
- 'pagetitle' => 'Redirects',
- 'title' => 'Create Redirect',
- 'breadcrumbs' => [
- ['label' => 'Home', 'url' => '/'],
- ['label' => 'Redirects', 'url' => '/redirects'],
- ['label' => 'All Redirects', 'url' => '/redirects/redirects'],
- ['label' => 'Create Redirect', 'url' => null]
- ]
- ]);
- View::render('@redirects/redirects/create', ['config' => $config, 'title' => 'Create Redirect']);
- }
- ]);
- }
-
- public function editRedirect(int $id): void
- {
- $redirect = $this->redirectModel->getById($id);
- if (!$redirect) {
- header('Location: /redirects/redirects');
- exit;
- }
-
- $filters = $this->filterModel->getByRedirectId($id);
- $config = require __DIR__ . '/../config.php';
-
- View::render('layouts/main.php', [
- 'title' => 'Edit Redirect',
- 'page_name' => 'apps-redirects-edit',
- 'page_content' => function() use ($redirect, $filters, $config) {
- View::render('layouts/page-title.php', [
- 'pagetitle' => 'Redirects',
- 'title' => 'Edit Redirect',
- 'breadcrumbs' => [
- ['label' => 'Home', 'url' => '/'],
- ['label' => 'Redirects', 'url' => '/redirects'],
- ['label' => 'All Redirects', 'url' => '/redirects/redirects'],
- ['label' => 'Edit Redirect', 'url' => null]
- ]
- ]);
- View::render('@redirects/redirects/edit', ['redirect' => $redirect, 'filters' => $filters, 'config' => $config, 'title' => 'Edit Redirect']);
- }
- ]);
- }
-
- public function viewRedirect(int $id): void
- {
- $redirect = $this->redirectModel->getById($id);
- if (!$redirect) {
- header('Location: /redirects/redirects');
- exit;
- }
-
- $filters = $this->filterModel->getByRedirectId($id);
- $stats = $this->statsModel->getStatsByRedirect($id);
- $recentActivity = $this->statsModel->getRecentActivity($id, 10);
-
- View::render('layouts/main.php', [
- 'title' => 'View Redirect',
- 'page_name' => 'apps-redirects-view',
- 'page_content' => function() use ($redirect, $filters, $stats, $recentActivity) {
- View::render('layouts/page-title.php', [
- 'pagetitle' => 'Redirects',
- 'title' => 'View Redirect',
- 'breadcrumbs' => [
- ['label' => 'Home', 'url' => '/'],
- ['label' => 'Redirects', 'url' => '/redirects'],
- ['label' => 'All Redirects', 'url' => '/redirects/redirects'],
- ['label' => 'View Redirect', 'url' => null]
- ]
- ]);
- View::render('@redirects/redirects/view', ['redirect' => $redirect, 'filters' => $filters, 'stats' => $stats, 'recentActivity' => $recentActivity, 'title' => 'View Redirect']);
- }
- ]);
- }
-
- public function stats(): void
- {
- $startDate = Sanitize::string($_GET['start_date'] ?? date('Y-m-d', strtotime('-30 days')));
- $endDate = Sanitize::string($_GET['end_date'] ?? date('Y-m-d'));
-
- $stats = [
- 'overview' => $this->getOverviewStats($startDate, $endDate),
- 'by_country' => $this->getStatsByCountry($startDate, $endDate),
- 'by_device' => $this->getStatsByDevice($startDate, $endDate),
- 'by_browser' => $this->getStatsByBrowser($startDate, $endDate),
- 'by_hour' => $this->getStatsByHour($startDate, $endDate)
- ];
-
- // Get filter options from database
- $filterOptions = $this->getFilterOptions();
-
- View::render('layouts/main.php', [
- 'title' => 'Redirects Analytics',
- 'page_name' => 'apps-redirects-stats',
- 'page_content' => function() use ($stats, $startDate, $endDate, $filterOptions) {
- View::render('layouts/page-title.php', [
- 'pagetitle' => 'Redirects',
- 'title' => 'Analytics',
- 'breadcrumbs' => [
- ['label' => 'Home', 'url' => '/'],
- ['label' => 'Redirects', 'url' => '/redirects'],
- ['label' => 'Analytics', 'url' => null]
- ]
- ]);
- View::render('@redirects/stats/index', [
- 'stats' => $stats,
- 'startDate' => $startDate,
- 'endDate' => $endDate,
- 'title' => 'Redirects Analytics',
- 'filterOptions' => $filterOptions
- ]);
- }
- ]);
- }
-
- public function settings(): void
- {
- View::render('layouts/main.php', [
- 'title' => 'Redirects Settings',
- 'page_name' => 'apps-redirects-settings',
- 'page_content' => function() {
- View::render('layouts/page-title.php', [
- 'pagetitle' => 'Redirects',
- 'title' => 'Settings',
- 'breadcrumbs' => [
- ['label' => 'Home', 'url' => '/'],
- ['label' => 'Redirects', 'url' => '/redirects'],
- ['label' => 'Settings', 'url' => null]
- ]
- ]);
- View::render('@redirects/settings', ['title' => 'Redirects Settings']);
- }
- ]);
- }
-
- public function processRedirect(string $cuid): void
- {
- $startTime = microtime(true);
-
- $redirect = $this->redirectModel->getByCuid($cuid);
- if (!$redirect || $redirect['status'] != 1) {
- http_response_code(404);
- echo 'Redirect not found';
- return;
- }
-
- // Verificar se expirou
- if ($redirect['expires_at'] && strtotime($redirect['expires_at']) < time()) {
- http_response_code(410);
- echo 'Redirect expired';
- return;
- }
-
- // Processar redirect com filtros
- $targetUrl = $this->processor->processRedirect($redirect);
-
- $responseTime = round((microtime(true) - $startTime) * 1000);
-
- // Registrar estatísticas se ativado
- if ($redirect['tracking_enabled']) {
- $this->recordStats($redirect['id'], $targetUrl, $responseTime);
- }
-
- // Fazer redirect
- header("Location: " . $targetUrl);
- exit;
- }
-
- /**
- * API para dados de redirects - para Alpine.js
- */
- public function apiRedirects(): void
- {
- try {
- header('Content-Type: application/json');
- // Simple API key validation for server-to-server calls
- $authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
- $token = null;
- if (stripos($authHeader, 'Bearer ') === 0) {
- $token = trim(substr($authHeader, 7));
- }
- $expectedKey = $_ENV['REDIRECTS_API_KEY'] ?? getenv('REDIRECTS_API_KEY');
- if (!$expectedKey || !$token || !hash_equals($expectedKey, $token)) {
- http_response_code(401);
- echo json_encode(['success' => false, 'message' => 'Unauthorized']);
- return;
- }
-
- $db = DatabaseManager::getInstance();
- // Query explícita, sem SELECT * e sem dummy data
- $redirects = $db->fetchAll(
- "SELECT
- r.id,
- r.cuid,
- r.analytics_slug,
- r.name,
- r.source_url,
- r.target_url,
- r.status,
- r.redirect_type,
- r.tracking_enabled,
- r.created_at,
- r.updated_at,
- COALESCE(rs.total_clicks, 0) AS total_clicks,
- COALESCE(rs.unique_clicks, 0) AS unique_clicks
- FROM redirects r
- LEFT JOIN (
- SELECT
- redirect_id,
- COUNT(*) AS total_clicks,
- COUNT(DISTINCT ip_address) AS unique_clicks
- FROM redirect_stats
- GROUP BY redirect_id
- ) rs ON rs.redirect_id = r.id
- WHERE r.status >= 0
- ORDER BY r.created_at DESC"
- ) ?: [];
-
- $stats = [
- 'total' => (int)count($redirects),
- 'active' => (int)array_sum(array_map(static function(array $r) { return (int)($r['status'] === 'active' || (string)$r['status'] === '1'); }, $redirects)),
- 'inactive' => (int)array_sum(array_map(static function(array $r) { return (int)($r['status'] === 'inactive' || (string)$r['status'] === '0'); }, $redirects)),
- 'total_clicks' => (int)array_sum(array_map(static function(array $r) { return (int)($r['total_clicks'] ?? 0); }, $redirects))
- ];
-
- echo json_encode([
- 'success' => true,
- 'data' => [
- 'redirects' => $redirects,
- 'stats' => $stats,
- 'pagination' => [
- 'page' => 1,
- 'limit' => count($redirects),
- 'total' => count($redirects),
- 'pages' => 1
- ]
- ],
- 'timestamp' => date('Y-m-d H:i:s')
- ]);
-
- } catch (\Exception $e) {
- ErrorReporter::report($e, ['context' => 'api_redirects']);
- http_response_code(500);
- echo json_encode([
- 'success' => false,
- 'error' => 'Erro ao carregar redirects',
- 'timestamp' => date('Y-m-d H:i:s')
- ]);
- }
- }
-
- private function getOverviewStats(string $startDate, string $endDate): array
- {
- try {
- $db = \App\Core\DatabaseManager::getInstance();
-
- $sql = "SELECT
- COUNT(*) as total_clicks,
- COUNT(DISTINCT session_id) as unique_clicks,
- COUNT(DISTINCT ip_address) as unique_ips,
- COALESCE(AVG(response_time_ms), 0) as avg_response_time
- FROM redirect_stats
- WHERE DATE(timestamp) BETWEEN ? AND ?";
-
- $result = $db->fetch($sql, [$startDate, $endDate]);
-
- return [
- 'total_clicks' => (int)($result['total_clicks'] ?? 0),
- 'unique_clicks' => (int)($result['unique_clicks'] ?? 0),
- 'unique_ips' => (int)($result['unique_ips'] ?? 0),
- 'avg_response_time' => round((float)($result['avg_response_time'] ?? 0), 2)
- ];
- } catch (\Exception $e) {
- // Fallback para dados vazios se a tabela não existir
- return [
- 'total_clicks' => 0,
- 'unique_clicks' => 0,
- 'unique_ips' => 0,
- 'avg_response_time' => 0
- ];
- }
- }
-
- private function getStatsByCountry(string $startDate, string $endDate): array
- {
- try {
- $db = \App\Core\DatabaseManager::getInstance();
-
- $sql = "SELECT
- country_code,
- country_name,
- COUNT(*) as clicks,
- COUNT(DISTINCT session_id) as unique_clicks
- FROM redirect_stats
- WHERE DATE(timestamp) BETWEEN ? AND ?
- GROUP BY country_code, country_name
- ORDER BY clicks DESC
- LIMIT 10";
-
- return $db->fetchAll($sql, [$startDate, $endDate]) ?: [];
- } catch (\Exception $e) {
- return [];
- }
- }
-
- private function getStatsByDevice(string $startDate, string $endDate): array
- {
- try {
- $db = \App\Core\DatabaseManager::getInstance();
-
- $sql = "SELECT
- device_type,
- COUNT(*) as clicks,
- COUNT(DISTINCT session_id) as unique_clicks
- FROM redirect_stats
- WHERE DATE(timestamp) BETWEEN ? AND ?
- GROUP BY device_type
- ORDER BY clicks DESC";
-
- return $db->fetchAll($sql, [$startDate, $endDate]) ?: [];
- } catch (\Exception $e) {
- return [];
- }
- }
-
- private function getStatsByBrowser(string $startDate, string $endDate): array
- {
- try {
- $db = \App\Core\DatabaseManager::getInstance();
-
- $sql = "SELECT
- browser,
- COUNT(*) as clicks,
- COUNT(DISTINCT session_id) as unique_clicks
- FROM redirect_stats
- WHERE DATE(timestamp) BETWEEN ? AND ?
- GROUP BY browser
- ORDER BY clicks DESC
- LIMIT 10";
-
- return $db->fetchAll($sql, [$startDate, $endDate]) ?: [];
- } catch (\Exception $e) {
- return [];
- }
- }
-
- private function getStatsByHour(string $startDate, string $endDate): array
- {
- try {
- $db = \App\Core\DatabaseManager::getInstance();
-
- $sql = "SELECT
- hour_of_day,
- COUNT(*) as clicks,
- COUNT(DISTINCT session_id) as unique_clicks
- FROM redirect_stats
- WHERE DATE(timestamp) BETWEEN ? AND ?
- GROUP BY hour_of_day
- ORDER BY hour_of_day";
-
- return $db->fetchAll($sql, [$startDate, $endDate]) ?: [];
- } catch (\Exception $e) {
- return [];
- }
- }
-
- private function recordStats(int $redirectId, string $targetUrl, int $responseTime): void
- {
- $data = [
- 'redirect_id' => $redirectId,
- 'session_id' => session_id() ?: (string) new Cuid2(),
- 'ip_address' => $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0',
- 'ip_long' => ip2long($_SERVER['REMOTE_ADDR'] ?? '0.0.0.0'),
- 'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? null,
- 'referer' => $_SERVER['HTTP_REFERER'] ?? null,
- 'country_code' => $_SERVER['HTTP_CF_IPCOUNTRY'] ?? null,
- 'country_name' => null, // Será preenchido pelo processor
- 'city' => $_SERVER['HTTP_CF_IPCITY'] ?? null,
- 'region_code' => $_SERVER['HTTP_CF_IPREGION'] ?? null,
- 'region_name' => null, // Será preenchido pelo processor
- 'timezone' => $_SERVER['HTTP_CF_IPTIMEZONE'] ?? null,
- 'asn' => $_SERVER['HTTP_CF_IPASN'] ?? null,
- 'isp' => $_SERVER['HTTP_CF_IPISP'] ?? null,
- 'browser' => null, // Será preenchido pelo processor
- 'browser_version' => null,
- 'os' => null, // Será preenchido pelo processor
- 'os_version' => null,
- 'device_type' => 'desktop', // Será preenchido pelo processor
- 'language' => $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? null,
- 'hour_of_day' => (int)date('G'),
- 'day_of_week' => (int)date('N'),
- 'month' => (int)date('n'),
- 'year' => (int)date('Y'),
- 'response_time_ms' => $responseTime,
- 'target_url_used' => $targetUrl,
- 'filter_matched' => null // Será preenchido pelo processor
- ];
-
- $this->statsModel->create($data);
- }
-
- /**
- * Get filter options for analytics dropdowns
- */
- private function getFilterOptions(): array
- {
- $db = DatabaseManager::getInstance();
-
- try {
- // Get available redirects
- $redirects = $db->fetchAll("
- SELECT id, name, cuid
- FROM redirects
- WHERE status = 1
- ORDER BY name
- ");
-
- // Get available countries (fallback to code when name is null/empty)
- $countries = $db->fetchAll("
- SELECT DISTINCT
- country_code,
- COALESCE(NULLIF(country_name, ''), country_code) AS country_name
- FROM redirect_stats
- WHERE country_code IS NOT NULL AND country_code != ''
- ORDER BY country_name
- ");
-
- // Get available browsers
- $browsers = $db->fetchAll("
- SELECT DISTINCT browser
- FROM redirect_stats
- ORDER BY browser
- ");
-
- // Get available operating systems
- $operatingSystems = $db->fetchAll("
- SELECT DISTINCT os
- FROM redirect_stats
- ORDER BY os
- ");
-
- return [
- 'redirects' => $redirects ?: [],
- 'countries' => $countries ?: [],
- 'browsers' => $browsers ?: [],
- 'operatingSystems' => $operatingSystems ?: [],
- 'devices' => [
- ['type' => 'desktop', 'name' => 'Desktop'],
- ['type' => 'mobile', 'name' => 'Mobile'],
- ['type' => 'tablet', 'name' => 'Tablet'],
- ['type' => 'bot', 'name' => 'Bot']
- ]
- ];
- } catch (\Exception $e) {
- ErrorReporter::report($e, ['context' => 'redirects_filter_options']);
- return [
- 'redirects' => [],
- 'countries' => [],
- 'browsers' => [],
- 'operatingSystems' => [],
- 'devices' => []
- ];
- }
- }
-}
\ No newline at end of file
diff --git a/crm/Redirects/Database/Migrations/ExtendRedirectsForAnalytics.php b/crm/Redirects/Database/Migrations/ExtendRedirectsForAnalytics.php
deleted file mode 100644
index 0fdcfd6..0000000
--- a/crm/Redirects/Database/Migrations/ExtendRedirectsForAnalytics.php
+++ /dev/null
@@ -1,163 +0,0 @@
-db->query($sql);
-
- // Add indexes for performance
- $this->db->query("
- ALTER TABLE redirects
- ADD INDEX idx_analytics_enabled (analytics_enabled),
- ADD INDEX idx_analytics_campaign_id (analytics_campaign_id),
- ADD INDEX idx_analytics_tracker_id (analytics_tracker_id)
- ");
-
- // Create analytics_redirects_mapping table for seamless integration
- $this->db->query("
- CREATE TABLE IF NOT EXISTS analytics_redirects_mapping (
- id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
- redirect_id BIGINT UNSIGNED NOT NULL,
- analytics_event_id BIGINT UNSIGNED NULL,
- analytics_session_id BIGINT UNSIGNED NULL,
- redirect_type ENUM('301', '302', 'meta', 'javascript') NOT NULL DEFAULT '302',
- source_url VARCHAR(500) NOT NULL,
- target_url VARCHAR(500) NOT NULL,
- fallback_url VARCHAR(500) NULL,
- filter_matched VARCHAR(100) NULL,
- response_time_ms INT UNSIGNED NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
- INDEX idx_redirect_id (redirect_id),
- INDEX idx_analytics_event_id (analytics_event_id),
- INDEX idx_analytics_session_id (analytics_session_id),
- INDEX idx_created_at (created_at)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
- ");
-
- // Create analytics_redirects_events table for event tracking
- $this->db->query("
- CREATE TABLE IF NOT EXISTS analytics_redirects_events (
- id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
- redirect_id BIGINT UNSIGNED NOT NULL,
- event_type ENUM('redirect', 'click', 'conversion', 'error') NOT NULL DEFAULT 'redirect',
- event_data JSON NOT NULL COMMENT 'Event data including geo, device, browser info',
- ip_address VARCHAR(45) NOT NULL,
- ip_long BIGINT NOT NULL,
- session_id VARCHAR(64) NULL,
- user_agent TEXT NULL,
- referer TEXT NULL,
- country_code VARCHAR(2) NULL,
- country_name VARCHAR(100) NULL,
- city VARCHAR(100) NULL,
- region_code VARCHAR(10) NULL,
- region_name VARCHAR(100) NULL,
- timezone VARCHAR(50) NULL,
- browser VARCHAR(50) NULL,
- browser_version VARCHAR(20) NULL,
- os VARCHAR(50) NULL,
- os_version VARCHAR(20) NULL,
- device_type ENUM('desktop', 'mobile', 'tablet', 'bot') DEFAULT 'desktop',
- language VARCHAR(10) NULL,
- hour_of_day TINYINT NOT NULL,
- day_of_week TINYINT NOT NULL,
- month TINYINT NOT NULL,
- year SMALLINT NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- INDEX idx_redirect_id (redirect_id),
- INDEX idx_event_type (event_type),
- INDEX idx_ip_long (ip_long),
- INDEX idx_session_id (session_id),
- INDEX idx_country_code (country_code),
- INDEX idx_device_type (device_type),
- INDEX idx_browser (browser),
- INDEX idx_os (os),
- INDEX idx_created_at (created_at)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
- ");
-
- // Create analytics_redirects_daily table for daily aggregations
- $this->db->query("
- CREATE TABLE IF NOT EXISTS analytics_redirects_daily (
- id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
- redirect_id BIGINT UNSIGNED NOT NULL,
- date DATE NOT NULL,
- total_redirects INT NOT NULL DEFAULT 0,
- total_clicks INT NOT NULL DEFAULT 0,
- total_conversions INT NOT NULL DEFAULT 0,
- total_errors INT NOT NULL DEFAULT 0,
- unique_visitors INT NOT NULL DEFAULT 0,
- unique_ips INT NOT NULL DEFAULT 0,
- avg_response_time DECIMAL(10,2) NOT NULL DEFAULT 0.00,
- bounce_rate DECIMAL(5,2) NOT NULL DEFAULT 0.00,
- conversion_rate DECIMAL(5,2) NOT NULL DEFAULT 0.00,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
- UNIQUE KEY unique_redirect_date (redirect_id, date),
- INDEX idx_redirect_id (redirect_id),
- INDEX idx_date (date)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
- ");
-
- echo "✅ Analytics integration tables created successfully!\n";
- }
-
- /**
- * Reverse the migration
- */
- public function down(): void
- {
- // Remove analytics fields from redirects table
- $this->db->query("
- ALTER TABLE redirects
- DROP COLUMN analytics_enabled,
- DROP COLUMN analytics_campaign_id,
- DROP COLUMN analytics_tracker_id,
- DROP COLUMN analytics_metadata,
- DROP COLUMN last_analytics_sync,
- DROP COLUMN analytics_hash
- ");
-
- // Remove analytics indexes
- $this->db->query("
- ALTER TABLE redirects
- DROP INDEX idx_analytics_enabled,
- DROP INDEX idx_analytics_campaign_id,
- DROP INDEX idx_analytics_tracker_id
- ");
-
- // Drop analytics tables
- $this->db->query("DROP TABLE IF EXISTS analytics_redirects_mapping");
- $this->db->query("DROP TABLE IF EXISTS analytics_redirects_events");
- $this->db->query("DROP TABLE IF EXISTS analytics_redirects_daily");
-
- echo "✅ Analytics integration tables removed successfully!\n";
- }
-}
diff --git a/crm/Redirects/Database/Migrations/IntegrateRedirectsWithSiteGroups.php b/crm/Redirects/Database/Migrations/IntegrateRedirectsWithSiteGroups.php
deleted file mode 100644
index 4465abb..0000000
--- a/crm/Redirects/Database/Migrations/IntegrateRedirectsWithSiteGroups.php
+++ /dev/null
@@ -1,223 +0,0 @@
-db->query($sql);
-
- // Add indexes for performance
- $this->db->query("
- ALTER TABLE redirects
- ADD INDEX idx_site_group_id (site_group_id),
- ADD INDEX idx_creative_id (creative_id),
- ADD INDEX idx_multisite_type (multisite_type),
- ADD INDEX idx_multisite_status (multisite_status),
- ADD INDEX idx_traffic_weight (traffic_weight),
- ADD INDEX idx_is_primary_redirect (is_primary_redirect)
- ");
-
- // Create redirect_site_group_mapping table for advanced multisite management
- $this->db->query("
- CREATE TABLE IF NOT EXISTS redirect_site_group_mapping (
- id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
- redirect_id BIGINT UNSIGNED NOT NULL,
- site_group_id BIGINT UNSIGNED NOT NULL,
- creative_id BIGINT UNSIGNED NULL,
- mapping_type ENUM('primary', 'fallback', 'geo_specific', 'device_specific', 'time_specific') NOT NULL DEFAULT 'primary',
- priority INT NOT NULL DEFAULT 0 COMMENT 'Priority for this mapping (higher = more important)',
- geo_targeting JSON NULL COMMENT 'Geographic targeting rules',
- device_targeting JSON NULL COMMENT 'Device targeting rules',
- time_targeting JSON NULL COMMENT 'Time-based targeting rules',
- traffic_percentage DECIMAL(5,2) NOT NULL DEFAULT 100.00 COMMENT 'Percentage of traffic for this mapping',
- is_active BOOLEAN DEFAULT TRUE,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
-
- UNIQUE KEY unique_redirect_site_group (redirect_id, site_group_id),
- INDEX idx_redirect_id (redirect_id),
- INDEX idx_site_group_id (site_group_id),
- INDEX idx_creative_id (creative_id),
- INDEX idx_mapping_type (mapping_type),
- INDEX idx_priority (priority),
- INDEX idx_is_active (is_active)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
- COMMENT='Advanced mapping between redirects, site groups and creatives for multisite management'
- ");
-
- // Create redirect_multisite_analytics table for unified analytics
- $this->db->query("
- CREATE TABLE IF NOT EXISTS redirect_multisite_analytics (
- id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
- redirect_id BIGINT UNSIGNED NOT NULL,
- site_group_id BIGINT UNSIGNED NULL,
- creative_id BIGINT UNSIGNED NULL,
- date DATE NOT NULL,
- total_redirects INT NOT NULL DEFAULT 0,
- total_clicks INT NOT NULL DEFAULT 0,
- total_conversions INT NOT NULL DEFAULT 0,
- unique_visitors INT NOT NULL DEFAULT 0,
- unique_ips INT NOT NULL DEFAULT 0,
- avg_response_time DECIMAL(10,2) NOT NULL DEFAULT 0.00,
- traffic_source VARCHAR(50) NULL COMMENT 'Traffic source (direct, organic, paid, social)',
- device_breakdown JSON NULL COMMENT 'Device type breakdown',
- geo_breakdown JSON NULL COMMENT 'Geographic breakdown',
- conversion_funnel JSON NULL COMMENT 'Conversion funnel data',
- revenue_data JSON NULL COMMENT 'Revenue and ROI data',
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
-
- UNIQUE KEY unique_multisite_date (redirect_id, site_group_id, creative_id, date),
- INDEX idx_redirect_id (redirect_id),
- INDEX idx_site_group_id (site_group_id),
- INDEX idx_creative_id (creative_id),
- INDEX idx_date (date),
- INDEX idx_traffic_source (traffic_source)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
- COMMENT='Unified analytics for redirects in multisite context'
- ");
-
- // Create redirect_multisite_templates table for template management
- $this->db->query("
- CREATE TABLE IF NOT EXISTS redirect_multisite_templates (
- id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
- site_group_id BIGINT UNSIGNED NOT NULL,
- template_name VARCHAR(255) NOT NULL,
- template_type ENUM('redirect', 'landing', 'popup', 'interstitial', 'custom') NOT NULL DEFAULT 'redirect',
- template_config JSON NOT NULL COMMENT 'Template configuration and settings',
- html_template LONGTEXT NULL COMMENT 'HTML template content',
- css_template LONGTEXT NULL COMMENT 'CSS template content',
- js_template LONGTEXT NULL COMMENT 'JavaScript template content',
- variables_schema JSON NULL COMMENT 'Template variables schema',
- is_active BOOLEAN DEFAULT TRUE,
- created_by BIGINT UNSIGNED NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
-
- INDEX idx_site_group_id (site_group_id),
- INDEX idx_template_type (template_type),
- INDEX idx_is_active (is_active),
- INDEX idx_created_by (created_by)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
- COMMENT='Templates for multisite redirects and landing pages'
- ");
-
- // Add foreign key constraints
- try {
- $this->db->query("
- ALTER TABLE redirects
- ADD CONSTRAINT fk_redirects_site_group
- FOREIGN KEY (site_group_id) REFERENCES advertising_site_groups(id)
- ON DELETE SET NULL ON UPDATE CASCADE
- ");
- echo "✅ Added foreign key constraint to advertising_site_groups\n";
- } catch (\Exception $e) {
- echo "⚠️ Foreign key constraint to site_groups skipped: " . $e->getMessage() . "\n";
- }
-
- try {
- $this->db->query("
- ALTER TABLE redirects
- ADD CONSTRAINT fk_redirects_creative
- FOREIGN KEY (creative_id) REFERENCES advertising_creatives(id)
- ON DELETE SET NULL ON UPDATE CASCADE
- ");
- echo "✅ Added foreign key constraint to advertising_creatives\n";
- } catch (\Exception $e) {
- echo "⚠️ Foreign key constraint to creatives skipped: " . $e->getMessage() . "\n";
- }
-
- echo "✅ Multisites integration tables created successfully!\n";
- echo "🎯 Redirects now integrated with Site Groups and Creatives system\n";
- echo "🌐 Unified multisites management system ready\n";
- }
-
- /**
- * Reverse the migration
- */
- public function down(): void
- {
- // Remove foreign key constraints first
- try {
- $this->db->query("ALTER TABLE redirects DROP FOREIGN KEY fk_redirects_site_group");
- echo "✅ Removed foreign key constraint to site_groups\n";
- } catch (\Exception $e) {
- echo "⚠️ Foreign key constraint removal skipped: " . $e->getMessage() . "\n";
- }
-
- try {
- $this->db->query("ALTER TABLE redirects DROP FOREIGN KEY fk_redirects_site_group");
- echo "✅ Removed foreign key constraint to creatives\n";
- } catch (\Exception $e) {
- echo "⚠️ Foreign key constraint removal skipped: " . $e->getMessage() . "\n";
- }
-
- // Remove indexes
- $this->db->query("
- ALTER TABLE redirects
- DROP INDEX idx_site_group_id,
- DROP INDEX idx_creative_id,
- DROP INDEX idx_multisite_type,
- DROP INDEX idx_multisite_status,
- DROP INDEX idx_traffic_weight,
- DROP INDEX idx_is_primary_redirect
- ");
-
- // Remove columns
- $this->db->query("
- ALTER TABLE redirects
- DROP COLUMN site_group_id,
- DROP COLUMN creative_id,
- DROP COLUMN multisite_type,
- DROP COLUMN site_group_settings,
- DROP COLUMN creative_settings,
- DROP COLUMN traffic_weight,
- DROP COLUMN is_primary_redirect,
- DROP COLUMN multisite_status
- ");
-
- // Drop tables
- $this->db->query("DROP TABLE IF EXISTS redirect_site_group_mapping");
- $this->db->query("DROP TABLE IF EXISTS redirect_multisite_analytics");
- $this->db->query("DROP TABLE IF EXISTS redirect_multisite_templates");
-
- echo "✅ Multisites integration reverted successfully\n";
- }
-
- /**
- * Get migration description
- */
- public function getDescription(): string
- {
- return "Integrate Redirects with Site Groups and Creatives for unified multisites system";
- }
-}
diff --git a/crm/Redirects/Models/RedirectFilterModel.php b/crm/Redirects/Models/RedirectFilterModel.php
deleted file mode 100644
index 1301ea7..0000000
--- a/crm/Redirects/Models/RedirectFilterModel.php
+++ /dev/null
@@ -1,120 +0,0 @@
-db = DatabaseManager::getInstance();
- }
-
- public function getByRedirectId(int $redirectId): array
- {
- $sql = "SELECT * FROM redirect_filters WHERE redirect_id = :redirect_id AND is_active = 1 ORDER BY priority DESC, id ASC";
- return $this->db->fetchAll($sql, [':redirect_id' => $redirectId]) ?: [];
- }
-
- public function create(array $data): bool
- {
- $sql = "INSERT INTO redirect_filters (
- redirect_id, filter_type, filter_value, filter_operator,
- filter_value_secondary, priority, is_active
- ) VALUES (
- ?, ?, ?, ?, ?, ?, ?
- )";
-
- $params = [
- $data['redirect_id'],
- $data['filter_type'],
- $data['filter_value'],
- $data['filter_operator'] ?? 'equals',
- $data['filter_value_secondary'] ?? null,
- $data['priority'] ?? 0,
- (int)($data['is_active'] ?? 1)
- ];
-
- return $this->db->query($sql, $params) > 0;
- }
-
- public function update(int $id, array $data): bool
- {
- $sql = "UPDATE redirect_filters SET
- filter_type = ?, filter_value = ?, filter_operator = ?,
- filter_value_secondary = ?, priority = ?, is_active = ?,
- updated_at = CURRENT_TIMESTAMP
- WHERE id = ?";
-
- $params = [
- $data['filter_type'],
- $data['filter_value'],
- $data['filter_operator'] ?? 'equals',
- $data['filter_value_secondary'] ?? null,
- $data['priority'] ?? 0,
- (int)($data['is_active'] ?? 1),
- $id
- ];
-
- return $this->db->query($sql, $params) > 0;
- }
-
- /**
- * Soft delete redirect filter (update status to -1)
- */
- public function delete(int $id): bool
- {
- $sql = "UPDATE redirect_filters SET status = '-1', updated_at = CURRENT_TIMESTAMP WHERE id = :id";
- return $this->db->query($sql, [':id' => $id]) > 0;
- }
-
- /**
- * Soft delete redirect filters by redirect ID (update status to -1)
- */
- public function deleteByRedirectId(int $redirectId): bool
- {
- $sql = "UPDATE redirect_filters SET status = '-1', updated_at = CURRENT_TIMESTAMP WHERE redirect_id = :redirect_id";
- return $this->db->query($sql, [':redirect_id' => $redirectId]) > 0;
- }
-
- public function getFilterTypes(): array
- {
- return [
- 'browser' => 'Browser',
- 'os' => 'Operating System',
- 'device_type' => 'Device Type',
- 'country' => 'Country',
- 'city' => 'City',
- 'region' => 'Region',
- 'timezone' => 'Timezone',
- 'language' => 'Language',
- 'referer' => 'Referer',
- 'hour' => 'Hour of Day',
- 'asn' => 'ASN',
- 'isp' => 'ISP'
- ];
- }
-
- public function getOperators(): array
- {
- return [
- 'equals' => 'Equals',
- 'contains' => 'Contains',
- 'starts_with' => 'Starts with',
- 'ends_with' => 'Ends with',
- 'regex' => 'Regular Expression',
- 'in' => 'In list',
- 'not_in' => 'Not in list',
- 'greater_than' => 'Greater than',
- 'less_than' => 'Less than',
- 'between' => 'Between'
- ];
- }
-
- public function getDb(): DatabaseManager
- {
- return $this->db;
- }
-}
\ No newline at end of file
diff --git a/crm/Redirects/Models/RedirectModel.php b/crm/Redirects/Models/RedirectModel.php
deleted file mode 100644
index 9cb023d..0000000
--- a/crm/Redirects/Models/RedirectModel.php
+++ /dev/null
@@ -1,346 +0,0 @@
-db = DatabaseManager::getInstance();
- }
-
- public function getAll(array $filters = []): array
- {
- // ✅ MySQL > PHP: Tudo processado na query para performance
- $sql = "SELECT
- r.id,
- r.cuid,
- r.analytics_slug,
- r.name,
- r.source_url,
- r.target_url,
- r.status,
- r.redirect_type,
- r.tracking_enabled,
- r.created_at,
- r.updated_at,
- COALESCE(rs.total_clicks, 0) as total_clicks,
- COALESCE(rs.unique_clicks, 0) as unique_clicks
- FROM redirects r
- LEFT JOIN (
- SELECT
- redirect_id,
- COUNT(*) as total_clicks,
- COUNT(DISTINCT ip_address) as unique_clicks
- FROM redirect_stats
- GROUP BY redirect_id
- ) rs ON rs.redirect_id = r.id
- WHERE r.status >= 0";
-
- $params = [];
-
- // ✅ MySQL > PHP: Filtros aplicados na query, não em PHP
- if (isset($filters['status']) && $filters['status'] !== '') {
- $sql .= " AND r.status = ?";
- $params[] = (int)$filters['status'];
- }
-
- if (!empty($filters['search'])) {
- $sql .= " AND (r.name LIKE ? OR r.source_url LIKE ? OR r.target_url LIKE ?)";
- $searchTerm = '%' . $filters['search'] . '%';
- $params[] = $searchTerm;
- $params[] = $searchTerm;
- $params[] = $searchTerm;
- }
-
- // ✅ MySQL > PHP: Ordenação na query
- $sql .= " ORDER BY r.created_at DESC";
-
- return $this->db->fetchAll($sql, $params) ?: [];
- }
-
- public function getById(int $id): ?array
- {
- // ✅ MySQL > PHP: Query otimizada com JOIN para estatísticas
- $sql = "SELECT
- r.id,
- r.cuid,
- r.analytics_slug,
- r.name,
- r.source_url,
- r.target_url,
- r.fallback_url,
- r.status,
- r.redirect_type,
- r.tracking_enabled,
- r.max_clicks,
- r.expires_at,
- r.created_by,
- r.created_at,
- r.updated_at,
- COALESCE(rs.total_clicks, 0) as total_clicks,
- COALESCE(rs.unique_clicks, 0) as unique_clicks
- FROM redirects r
- LEFT JOIN (
- SELECT
- redirect_id,
- COUNT(*) as total_clicks,
- COUNT(DISTINCT ip_address) as unique_clicks
- FROM redirect_stats
- WHERE redirect_id = ?
- GROUP BY redirect_id
- ) rs ON rs.redirect_id = r.id
- WHERE r.id = ? AND r.status >= 0";
-
- $result = $this->db->fetch($sql, [$id, $id]);
- return $result ?: null;
- }
-
- public function getByCuid(string $cuid): ?array
- {
- // ✅ MySQL > PHP: Query otimizada para buscar por CUID
- $sql = "SELECT
- r.id,
- r.cuid,
- r.analytics_slug,
- r.name,
- r.source_url,
- r.target_url,
- r.fallback_url,
- r.status,
- r.redirect_type,
- r.tracking_enabled,
- r.max_clicks,
- r.expires_at,
- r.created_by,
- r.created_at,
- r.updated_at,
- COALESCE(rs.total_clicks, 0) as total_clicks,
- COALESCE(rs.unique_clicks, 0) as unique_clicks
- FROM redirects r
- LEFT JOIN (
- SELECT
- redirect_id,
- COUNT(*) as total_clicks,
- COUNT(DISTINCT ip_address) as unique_clicks
- FROM redirect_stats
- WHERE redirect_id = r.id
- GROUP BY redirect_id
- ) rs ON rs.redirect_id = r.id
- WHERE r.cuid = ? AND r.status >= 0";
-
- $result = $this->db->fetch($sql, [$cuid]);
- return $result ?: null;
- }
-
- public function create(array $data): bool
- {
- $cuid = $this->generateCuid();
- $analyticsSlug = $this->generateAnalyticsSlug();
-
- $sql = "INSERT INTO redirects (
- cuid, analytics_slug, name, source_url, target_url, fallback_url,
- status, redirect_type, tracking_enabled, max_clicks,
- expires_at, created_by
- ) VALUES (
- ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
- )";
-
- $params = [
- $cuid,
- $analyticsSlug,
- $data['name'] ?? '',
- $data['source_url'] ?? '',
- $data['target_url'] ?? '',
- $data['fallback_url'] ?? null,
- (int)($data['status'] ?? 1),
- $data['redirect_type'] ?? '302',
- (int)($data['tracking_enabled'] ?? 1),
- $data['max_clicks'] ?? null,
- $data['expires_at'] ?? null,
- $data['created_by'] ?? 1
- ];
-
- return $this->db->query($sql, $params) > 0;
- }
-
- public function update(int $id, array $data): bool
- {
- $sql = "UPDATE redirects SET
- name = ?, source_url = ?, target_url = ?, fallback_url = ?,
- status = ?, redirect_type = ?, tracking_enabled = ?,
- max_clicks = ?, expires_at = ?, updated_at = CURRENT_TIMESTAMP
- WHERE id = ?";
-
- $params = [
- $data['name'] ?? '',
- $data['source_url'] ?? '',
- $data['target_url'] ?? '',
- $data['fallback_url'] ?? null,
- (int)($data['status'] ?? 1),
- $data['redirect_type'] ?? '302',
- (int)($data['tracking_enabled'] ?? 1),
- $data['max_clicks'] ?? null,
- $data['expires_at'] ?? null,
- $id
- ];
-
- return $this->db->query($sql, $params) > 0;
- }
-
- public function delete(int $id): bool
- {
- $sql = "UPDATE redirects SET status = -1 WHERE id = :id";
- return $this->db->query($sql, [':id' => $id]) > 0;
- }
-
- public function getActiveRedirects(): array
- {
- return $this->getAll(['status' => 1]);
- }
-
- public function getRedirectStats(int $redirectId, ?string $startDate = null, ?string $endDate = null): array
- {
- $sql = "SELECT
- DATE(created_at) as date,
- COUNT(*) as total_clicks,
- COUNT(DISTINCT ip_address) as unique_clicks,
- AVG(response_time) as avg_response_time
- FROM redirect_stats
- WHERE redirect_id = ?";
-
- $params = [$redirectId];
-
- if ($startDate) {
- $sql .= " AND created_at >= ?";
- $params[] = $startDate;
- }
-
- if ($endDate) {
- $sql .= " AND created_at <= ?";
- $params[] = $endDate;
- }
-
- $sql .= " GROUP BY DATE(created_at) ORDER BY date DESC";
-
- return $this->db->fetchAll($sql, $params) ?: [];
- }
-
- public function getCount(): int
- {
- $result = $this->db->fetch("SELECT COUNT(*) as count FROM redirects WHERE status >= 0");
- return (int)($result['count'] ?? 0);
- }
-
- public function getCountByStatus(): array
- {
- $sql = "SELECT status, COUNT(*) as count FROM redirects WHERE status >= 0 GROUP BY status";
- return $this->db->fetchAll($sql) ?: [];
- }
-
- public function getActiveCount(): int
- {
- $result = $this->db->fetch("SELECT COUNT(*) as count FROM redirects WHERE status = 1");
- return (int)($result['count'] ?? 0);
- }
-
- public function getInactiveCount(): int
- {
- $result = $this->db->fetch("SELECT COUNT(*) as count FROM redirects WHERE status = 0");
- return (int)($result['count'] ?? 0);
- }
-
- public function getDb(): DatabaseManager
- {
- return $this->db;
- }
-
- /**
- * Create redirect and associated creative
- */
- public function createWithCreative(array $data): bool
- {
- return $this->db->transaction(function($db) use ($data) {
- // Create redirect
- $redirectCreated = $this->create($data);
- if (!$redirectCreated) {
- return false;
- }
-
- // Get the created redirect ID
- $redirectId = $db->lastInsertId();
-
- // Create associated creative
- $creativeService = new \App\Modules\Redirects\Services\RedirectCreativeService();
- $creativeCreated = $creativeService->createCreativeFromRedirect($data);
-
- if (!$creativeCreated) {
- return false;
- }
-
- return true;
- });
- }
-
- /**
- * Update redirect and associated creative
- */
- public function updateWithCreative(int $id, array $data): bool
- {
- return $this->db->transaction(function($db) use ($id, $data) {
- // Update redirect
- $redirectUpdated = $this->update($id, $data);
- if (!$redirectUpdated) {
- return false;
- }
-
- // Update associated creative
- $creativeService = new \App\Modules\Redirects\Services\RedirectCreativeService();
- $creativeUpdated = $creativeService->updateCreativeFromRedirect($id, $data);
-
- if (!$creativeUpdated) {
- return false;
- }
-
- return true;
- });
- }
-
- /**
- * Delete redirect and associated creative
- */
- public function deleteWithCreative(int $id): bool
- {
- return $this->db->transaction(function($db) use ($id) {
- // Delete redirect (soft delete)
- $redirectDeleted = $this->delete($id);
- if (!$redirectDeleted) {
- return false;
- }
-
- // Delete associated creative (soft delete)
- $creativeService = new \App\Modules\Redirects\Services\RedirectCreativeService();
- $creativeDeleted = $creativeService->deleteCreativeByRedirectId($id);
-
- if (!$creativeDeleted) {
- return false;
- }
-
- return true;
- });
- }
-
- private function generateCuid(): string
- {
- return (string) new \Visus\Cuid2\Cuid2();
- }
-
- private function generateAnalyticsSlug(): string
- {
- // Usar cuid2 para gerar slug único para analytics (diferente do cuid principal)
- return (string) new \Visus\Cuid2\Cuid2();
- }
-}
\ No newline at end of file
diff --git a/crm/Redirects/Models/RedirectStatsModel.php b/crm/Redirects/Models/RedirectStatsModel.php
deleted file mode 100644
index c6be214..0000000
--- a/crm/Redirects/Models/RedirectStatsModel.php
+++ /dev/null
@@ -1,210 +0,0 @@
-db = DatabaseManager::getInstance();
- }
-
- public function create(array $data): bool
- {
- $sql = "INSERT INTO redirect_stats (
- redirect_id, session_id, ip_address, ip_long, user_agent, referer,
- country_code, country_name, city, region_code, region_name, timezone,
- asn, isp, browser, browser_version, os, os_version, device_type,
- language, hour_of_day, day_of_week, month, year,
- response_time_ms, target_url_used, filter_matched, raw_request
- ) VALUES (
- ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
- )";
-
- $params = [
- $data['redirect_id'],
- $data['session_id'],
- $data['ip_address'],
- $data['ip_long'],
- $data['user_agent'] ?? null,
- $data['referer'] ?? null,
- $data['country_code'] ?? null,
- $data['country_name'] ?? null,
- $data['city'] ?? null,
- $data['region_code'] ?? null,
- $data['region_name'] ?? null,
- $data['timezone'] ?? null,
- $data['asn'] ?? null,
- $data['isp'] ?? null,
- $data['browser'] ?? null,
- $data['browser_version'] ?? null,
- $data['os'] ?? null,
- $data['os_version'] ?? null,
- $data['device_type'] ?? 'desktop',
- $data['language'] ? substr($data['language'], 0, 10) : null,
- $data['hour_of_day'],
- $data['day_of_week'],
- $data['month'],
- $data['year'],
- $data['response_time_ms'] ?? null,
- $data['target_url_used'] ?? null,
- $data['filter_matched'] ?? null,
- $data['raw_request'] ?? null
- ];
-
- return $this->db->query($sql, $params) > 0;
- }
-
- public function getStatsByRedirect(int $redirectId, ?string $startDate = null, ?string $endDate = null): array
- {
- $sql = "SELECT
- COUNT(*) as total_clicks,
- COUNT(DISTINCT session_id) as unique_clicks,
- COUNT(DISTINCT ip_address) as unique_ips,
- AVG(response_time_ms) as avg_response_time
- FROM redirect_stats
- WHERE redirect_id = ?";
-
- $params = [$redirectId];
-
- if ($startDate) {
- $sql .= " AND DATE(timestamp) >= ?";
- $params[] = $startDate;
- }
-
- if ($endDate) {
- $sql .= " AND DATE(timestamp) <= ?";
- $params[] = $endDate;
- }
-
- return $this->db->fetch($sql, $params) ?: [];
- }
-
- public function getStatsByCountry(int $redirectId, ?string $startDate = null, ?string $endDate = null): array
- {
- $sql = "SELECT
- country_code, country_name,
- COUNT(*) as clicks,
- COUNT(DISTINCT session_id) as unique_clicks
- FROM redirect_stats
- WHERE redirect_id = ? AND country_code IS NOT NULL";
-
- $params = [$redirectId];
-
- if ($startDate) {
- $sql .= " AND DATE(timestamp) >= ?";
- $params[] = $startDate;
- }
-
- if ($endDate) {
- $sql .= " AND DATE(timestamp) <= ?";
- $params[] = $endDate;
- }
-
- $sql .= " GROUP BY country_code, country_name ORDER BY clicks DESC";
-
- return $this->db->fetchAll($sql, $params) ?: [];
- }
-
- public function getStatsByDevice(int $redirectId, ?string $startDate = null, ?string $endDate = null): array
- {
- $sql = "SELECT
- device_type,
- COUNT(*) as clicks,
- COUNT(DISTINCT session_id) as unique_clicks
- FROM redirect_stats
- WHERE redirect_id = ? AND device_type IS NOT NULL";
-
- $params = [$redirectId];
-
- if ($startDate) {
- $sql .= " AND DATE(timestamp) >= ?";
- $params[] = $startDate;
- }
-
- if ($endDate) {
- $sql .= " AND DATE(timestamp) <= ?";
- $params[] = $endDate;
- }
-
- $sql .= " GROUP BY device_type ORDER BY clicks DESC";
-
- return $this->db->fetchAll($sql, $params) ?: [];
- }
-
- public function getStatsByBrowser(int $redirectId, ?string $startDate = null, ?string $endDate = null): array
- {
- $sql = "SELECT
- browser,
- COUNT(*) as clicks,
- COUNT(DISTINCT session_id) as unique_clicks
- FROM redirect_stats
- WHERE redirect_id = ? AND browser IS NOT NULL";
-
- $params = [$redirectId];
-
- if ($startDate) {
- $sql .= " AND DATE(timestamp) >= ?";
- $params[] = $startDate;
- }
-
- if ($endDate) {
- $sql .= " AND DATE(timestamp) <= ?";
- $params[] = $endDate;
- }
-
- $sql .= " GROUP BY browser ORDER BY clicks DESC";
-
- return $this->db->fetchAll($sql, $params) ?: [];
- }
-
- public function getStatsByHour(int $redirectId, ?string $startDate = null, ?string $endDate = null): array
- {
- $sql = "SELECT
- hour_of_day,
- COUNT(*) as clicks,
- COUNT(DISTINCT session_id) as unique_clicks
- FROM redirect_stats
- WHERE redirect_id = ?";
-
- $params = [$redirectId];
-
- if ($startDate) {
- $sql .= " AND DATE(timestamp) >= ?";
- $params[] = $startDate;
- }
-
- if ($endDate) {
- $sql .= " AND DATE(timestamp) <= ?";
- $params[] = $endDate;
- }
-
- $sql .= " GROUP BY hour_of_day ORDER BY hour_of_day";
-
- return $this->db->fetchAll($sql, $params) ?: [];
- }
-
- public function getRecentActivity(int $redirectId, int $limit = 10): array
- {
- // Sanitize limit to prevent SQL injection
- $limit = max(1, min(1000, (int)$limit));
-
- $sql = "SELECT
- ip_address, user_agent, browser, os, device_type,
- country_code, city, timestamp, target_url_used
- FROM redirect_stats
- WHERE redirect_id = ?
- ORDER BY timestamp DESC
- LIMIT " . $limit;
-
- return $this->db->fetchAll($sql, [$redirectId]) ?: [];
- }
-
- public function getDb(): DatabaseManager
- {
- return $this->db;
- }
-}
\ No newline at end of file
diff --git a/crm/Redirects/Module.php b/crm/Redirects/Module.php
deleted file mode 100644
index d3cac9d..0000000
--- a/crm/Redirects/Module.php
+++ /dev/null
@@ -1,78 +0,0 @@
- 'Redirects',
- 'version' => '1.0.0',
- 'description' => 'Sistema de redirects inteligentes com targeting server-side',
- 'author' => 'BitReport Unip. LDA',
- 'enabled' => true,
- 'dependencies' => ['Core', 'Analytics'],
- 'features' => [
- 'redirect_management' => true,
- 'server_side_targeting' => true,
- 'geo_targeting' => true,
- 'device_targeting' => true,
- 'browser_targeting' => true,
- 'time_targeting' => true,
- 'analytics_tracking' => true,
- 'performance_optimization' => true
- ]
- ];
- }
-
- public static function registerRoutes($router): void
- {
- require __DIR__ . '/Routes/web.php';
- require __DIR__ . '/Routes/api.php';
- require __DIR__ . '/Routes/public.php';
- }
-
- public static function registerServices(): void
- {
- // Registar namespace das views do módulo
- View::addNamespace('redirects', __DIR__ . '/Views');
-
- // Registar serviços do módulo no ServiceContainer
- $container = \App\Core\ServiceContainer::getInstance();
-
- // Registar modelos
- $container->registerModuleService('Redirects', 'model.RedirectModel', function() {
- return new \App\Modules\Redirects\Models\RedirectModel();
- }, true);
-
- $container->registerModuleService('Redirects', 'model.RedirectFilterModel', function() {
- return new \App\Modules\Redirects\Models\RedirectFilterModel();
- }, true);
-
- $container->registerModuleService('Redirects', 'model.RedirectStatsModel', function() {
- return new \App\Modules\Redirects\Models\RedirectStatsModel();
- }, true);
-
- // Registar serviços
- if (file_exists(__DIR__ . '/Services/RedirectProcessor.php')) {
- require_once __DIR__ . '/Services/RedirectProcessor.php';
- $container->registerModuleService('Redirects', 'RedirectProcessor', function() {
- return new \App\Modules\Redirects\Services\RedirectProcessor();
- }, true);
- }
-
-
- }
-
- public static function registerMenu(): void
- {
- // Carregar ficheiro de menu do módulo
- $menuFile = __DIR__ . '/menu.php';
- if (file_exists($menuFile)) {
- require $menuFile;
- }
- }
-}
\ No newline at end of file
diff --git a/crm/Redirects/Routes/api.php b/crm/Redirects/Routes/api.php
deleted file mode 100644
index 7ad9c05..0000000
--- a/crm/Redirects/Routes/api.php
+++ /dev/null
@@ -1,41 +0,0 @@
-get('/api/redirects/stats', [RedirectsApiController::class, 'statsApi']);
-
-// Redirect creatives endpoint para integração com Advertising module (deve vir ANTES das rotas com {id})
-$router->get('/api/redirects/creatives', [RedirectsApiController::class, 'getRedirectCreatives']);
-$router->post('/api/redirects/creatives/migrate', [RedirectsApiController::class, 'migrateRedirectsToCreatives']);
-
-// Dados dinâmicos para formulários de redirects
-$router->get('/api/redirects/types', [RedirectsApiController::class, 'getRedirectTypes']);
-$router->get('/api/redirects/statuses', [RedirectsApiController::class, 'getStatuses']);
-$router->get('/api/redirects/filter-types', [RedirectsApiController::class, 'getFilterTypes']);
-$router->get('/api/redirects/filter-operators', [RedirectsApiController::class, 'getFilterOperators']);
-
-// Settings API endpoint
-$router->get('/api/redirects/settings', [RedirectsApiController::class, 'getSettings']);
-$router->post('/api/redirects/settings', [RedirectsApiController::class, 'updateSettings']);
-
-// CRUD endpoints
-$router->get('/api/redirects', [RedirectsApiController::class, 'index'], [\App\Core\AuthMiddleware::class, 'apiOrAuth']);
-$router->post('/api/redirects', [RedirectsApiController::class, 'create']);
-$router->get('/api/redirects/{id}', [RedirectsApiController::class, 'show']);
-$router->put('/api/redirects/{id}', [RedirectsApiController::class, 'update']);
-$router->delete('/api/redirects/{id}', [RedirectsApiController::class, 'delete']);
-
-// Stats endpoints por redirect específico
-$router->get('/api/redirects/{id}/stats', [RedirectsApiController::class, 'getStats']);
-$router->get('/api/redirects/{id}/filters', [RedirectsApiController::class, 'getFilters']);
-$router->post('/api/redirects/{id}/filters', [RedirectsApiController::class, 'addFilter']);
-$router->delete('/api/redirects/{id}/filters/{filterId}', [RedirectsApiController::class, 'deleteFilter']);
-
-// Site groups endpoint para integração com multisites
-$router->get('/api/redirects/{id}/site-groups', [RedirectsApiController::class, 'getSiteGroups']);
-$router->post('/api/redirects/{id}/site-groups', [RedirectsApiController::class, 'associateSiteGroup']);
-$router->put('/api/redirects/{id}/site-groups/{mappingId}', [RedirectsApiController::class, 'updateSiteGroup']);
-$router->delete('/api/redirects/{id}/site-groups/{mappingId}', [RedirectsApiController::class, 'removeSiteGroup']);
\ No newline at end of file
diff --git a/crm/Redirects/Routes/public.php b/crm/Redirects/Routes/public.php
deleted file mode 100644
index 3342ead..0000000
--- a/crm/Redirects/Routes/public.php
+++ /dev/null
@@ -1,12 +0,0 @@
-get('/public/redirects', [PublicRedirectsController::class, 'dashboard']);
-$router->get('/public/redirects/redirects', [PublicRedirectsController::class, 'redirects']);
-$router->get('/public/redirects/redirects/{int:id}', [PublicRedirectsController::class, 'viewRedirect']);
-$router->get('/public/redirects/stats', [PublicRedirectsController::class, 'stats']);
-$router->get('/public/redirects/stats/api', [PublicRedirectsController::class, 'statsApi']);
-
-// Rota pública para processar redirects (sem autenticação)
-$router->get('/r/{cuid}', [PublicRedirectsController::class, 'processRedirect']);
\ No newline at end of file
diff --git a/crm/Redirects/Routes/web.php b/crm/Redirects/Routes/web.php
deleted file mode 100644
index 9ab4e06..0000000
--- a/crm/Redirects/Routes/web.php
+++ /dev/null
@@ -1,17 +0,0 @@
-get('/redirects', [RedirectsController::class, 'dashboard']);
-$router->get('/redirects/api', [RedirectsController::class, 'apiRedirects']);
-$router->get('/redirects/stats', [RedirectsController::class, 'stats']);
-$router->get('/redirects/settings', [RedirectsController::class, 'settings']);
-$router->get('/redirects/create', [RedirectsController::class, 'createRedirect']); // Shortcut route
-$router->get('/redirects/redirects', [RedirectsController::class, 'redirects']);
-$router->get('/redirects/redirects/create', [RedirectsController::class, 'createRedirect']);
-$router->get('/redirects/edit/{int:id}', [RedirectsController::class, 'editRedirect']); // Shortcut route
-$router->get('/redirects/view/{int:id}', [RedirectsController::class, 'viewRedirect']); // Shortcut route
-$router->get('/redirects/redirects/{int:id}/edit', [RedirectsController::class, 'editRedirect']);
-$router->get('/redirects/redirects/{int:id}', [RedirectsController::class, 'viewRedirect']);
-
-
\ No newline at end of file
diff --git a/crm/Redirects/Services/RedirectAutoCreatorService.php b/crm/Redirects/Services/RedirectAutoCreatorService.php
deleted file mode 100644
index 88ecc71..0000000
--- a/crm/Redirects/Services/RedirectAutoCreatorService.php
+++ /dev/null
@@ -1,245 +0,0 @@
-db = DatabaseManager::getInstance();
- }
-
- /**
- * Create a complete redirect setup: multisite + campaign + creative
- */
- public function createCompleteRedirect(array $redirectData): array
- {
- try {
- return $this->db->transaction(function() use ($redirectData) {
- // 1. Extract domain from source URL
- $domain = $this->extractDomain($redirectData['source_url']);
- if (!$domain) {
- throw new \Exception("Invalid source URL");
- }
-
- // 2. Create or get site group (multisite)
- $siteGroupId = $this->createOrGetSiteGroup($domain);
-
- // 3. Create or get campaign
- $campaignId = $this->createOrGetCampaign($domain, $siteGroupId);
-
- // 4. Create creative
- $creativeId = $this->createCreative($redirectData, $campaignId);
-
- // 5. Associate creative with campaign
- $this->associateCreativeWithCampaign($creativeId, $campaignId);
-
- return [
- 'success' => true,
- 'site_group_id' => $siteGroupId,
- 'campaign_id' => $campaignId,
- 'creative_id' => $creativeId,
- 'message' => 'Redirect created successfully with multisite and campaign'
- ];
- });
- } catch (\Exception $e) {
- ErrorReporter::report($e, [
- 'context' => 'redirect_auto_creation',
- 'redirect_data' => $redirectData
- ]);
- return [
- 'success' => false,
- 'message' => 'Failed to create redirect: ' . $e->getMessage()
- ];
- }
- }
-
- /**
- * Extract domain from URL
- */
- private function extractDomain(string $url): ?string
- {
- if (preg_match('/(?:https?:\/\/)?(?:www\.)?([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/', $url, $matches)) {
- return $matches[1];
- }
- return null;
- }
-
- /**
- * Create or get existing site group
- */
- private function createOrGetSiteGroup(string $domain): int
- {
- // Check if site group already exists
- $existing = $this->db->fetch(
- "SELECT id FROM advertising_site_groups WHERE name LIKE ? OR alias LIKE ?",
- ["%$domain%", "%$domain%"]
- );
-
- if ($existing) {
- return $existing['id'];
- }
-
- // Create new site group
- $siteGroupData = [
- 'cuid' => (new Cuid2())->toString(),
- 'name' => "Redirects - $domain",
- 'alias' => "redirects_" . str_replace(['.', '-'], '_', $domain),
- 'status' => 1
- ];
-
- $sql = "INSERT INTO advertising_site_groups (cuid, name, alias, status) VALUES (?, ?, ?, ?)";
- $this->db->query($sql, [$siteGroupData['cuid'], $siteGroupData['name'], $siteGroupData['alias'], $siteGroupData['status']]);
-
- return $this->db->lastInsertId();
- }
-
- /**
- * Create or get existing campaign
- */
- private function createOrGetCampaign(string $domain, int $siteGroupId): int
- {
- // Check if campaign already exists
- $existing = $this->db->fetch(
- "SELECT id FROM advertising_campaigns WHERE name LIKE ? AND site_group_id = ?",
- ["%$domain%", $siteGroupId]
- );
-
- if ($existing) {
- return $existing['id'];
- }
-
- // Create new campaign
- $campaignData = [
- 'cuid' => (new Cuid2())->toString(),
- 'name' => "Redirects - $domain",
- 'site_group_id' => $siteGroupId,
- 'status' => 1,
- 'type' => 'banner',
- 'timezone' => 'UTC',
- 'frequency_period' => 'day',
- 'expire_hours' => 24.00,
- 'expire_mobile_hours' => 24.00,
- 'allow_close' => 1,
- 'created_by' => 1
- ];
-
- $sql = "INSERT INTO advertising_campaigns (
- cuid, name, site_group_id, status, type, timezone,
- frequency_period, expire_hours, expire_mobile_hours, allow_close, created_by
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
-
- $this->db->query($sql, [
- $campaignData['cuid'], $campaignData['name'], $campaignData['site_group_id'],
- $campaignData['status'], $campaignData['type'], $campaignData['timezone'],
- $campaignData['frequency_period'], $campaignData['expire_hours'],
- $campaignData['expire_mobile_hours'], $campaignData['allow_close'], $campaignData['created_by']
- ]);
-
- return $this->db->lastInsertId();
- }
-
- /**
- * Create creative from redirect data
- */
- private function createCreative(array $redirectData, int $campaignId): string
- {
- $creativeData = [
- 'cuid' => (new Cuid2())->toString(),
- 'name' => $redirectData['name'],
- 'description' => "Redirect from {$redirectData['source_url']} to {$redirectData['target_url']}",
- 'view_url' => $redirectData['target_url'],
- 'creative_type' => 'redirect',
- 'is_active' => $redirectData['status'] ? 1 : 0,
- 'width' => 300,
- 'height' => 250,
- 'file_name' => "redirect_{$redirectData['name']}.html",
- 'file_path' => "/redirects/redirect_{$redirectData['name']}.html",
- 'file_size' => 1024,
- 'mime_type' => 'text/html'
- ];
-
- $sql = "INSERT INTO advertising_creatives (
- cuid, name, description, view_url, creative_type, is_active,
- width, height, file_name, file_path, file_size, mime_type
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
-
- $this->db->query($sql, [
- $creativeData['cuid'], $creativeData['name'], $creativeData['description'],
- $creativeData['view_url'], $creativeData['creative_type'], $creativeData['is_active'],
- $creativeData['width'], $creativeData['height'], $creativeData['file_name'],
- $creativeData['file_path'], $creativeData['file_size'], $creativeData['mime_type']
- ]);
-
- return $creativeData['cuid'];
- }
-
- /**
- * Associate creative with campaign
- */
- private function associateCreativeWithCampaign(string $creativeId, int $campaignId): void
- {
- $sql = "INSERT INTO advertising_campaign_trackers (campaign_id, tracker_id, format_id, country, order_position)
- VALUES (?, (SELECT id FROM advertising_creatives WHERE cuid = ?), 1, 'PT', 0)";
-
- $this->db->query($sql, [$campaignId, $creativeId]);
- }
-
- /**
- * Update existing redirect with new creative
- */
- public function updateRedirectCreative(int $redirectId, array $redirectData): array
- {
- try {
- return $this->db->transaction(function() use ($redirectId, $redirectData) {
- // Find existing creative by redirect ID
- $creative = $this->db->fetch(
- "SELECT c.cuid, c.id FROM advertising_creatives c
- WHERE c.description LIKE ? AND c.creative_type = 'redirect'
- ORDER BY c.created_at DESC LIMIT 1",
- ["%Redirect from " . $redirectData['source_url'] . "%"]
- );
-
- if (!$creative) {
- throw new \Exception("Creative not found for redirect ID $redirectId");
- }
-
- // Update creative
- $sql = "UPDATE advertising_creatives SET
- name = ?, view_url = ?, is_active = ?,
- description = ?, updated_at = CURRENT_TIMESTAMP
- WHERE id = ?";
-
- $this->db->query($sql, [
- $redirectData['name'],
- $redirectData['target_url'],
- $redirectData['status'] ? 1 : 0,
- "Redirect from {$redirectData['source_url']} to {$redirectData['target_url']}",
- $creative['id']
- ]);
-
- return [
- 'success' => true,
- 'creative_id' => $creative['cuid'],
- 'message' => 'Redirect updated successfully'
- ];
- });
- } catch (\Exception $e) {
- ErrorReporter::report($e, [
- 'context' => 'redirect_update',
- 'redirect_id' => $redirectId,
- 'redirect_data' => $redirectData
- ]);
- return [
- 'success' => false,
- 'message' => 'Failed to update redirect: ' . $e->getMessage()
- ];
- }
- }
-}
diff --git a/crm/Redirects/Services/RedirectCreativeService.php b/crm/Redirects/Services/RedirectCreativeService.php
deleted file mode 100644
index 1482647..0000000
--- a/crm/Redirects/Services/RedirectCreativeService.php
+++ /dev/null
@@ -1,217 +0,0 @@
-db = DatabaseManager::getInstance();
- $this->redirectModel = new RedirectModel();
- }
-
- /**
- * Create a creative from a redirect
- */
- public function createCreativeFromRedirect(array $redirectData): bool
- {
- // Generate unique CUID for creative
- $cuid = $this->generateCuid();
-
- // Create creative using standard fields
- $sql = "INSERT INTO advertising_creatives (
- cuid, name, file_name, file_path, file_size, mime_type,
- width, height, alt_text, is_active, description,
- creative_type, view_url, target_country
- ) VALUES (
- ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
- )";
-
- $params = [
- $cuid,
- $redirectData['name'],
- $this->generateFileName($redirectData['name']),
- '/redirects/' . $cuid . '.html', // Virtual file path
- 1024, // Standard size for redirects
- 'text/html',
- 300, // Standard width
- 250, // Standard height
- 'Redirect: ' . $redirectData['name'],
- 1, // Active
- 'Redirect from ' . $redirectData['source_url'] . ' to ' . $redirectData['target_url'],
- 'redirect', // Creative type
- $redirectData['target_url'], // View URL = target URL
- null // Target country (can be set later)
- ];
-
- return $this->db->query($sql, $params) > 0;
- }
-
- /**
- * Update a creative when redirect is updated
- */
- public function updateCreativeFromRedirect(int $redirectId, array $redirectData): bool
- {
- // Find the creative associated with this redirect
- $creative = $this->getCreativeByRedirectId($redirectId);
- if (!$creative) {
- // If no creative exists, create one
- return $this->createCreativeFromRedirect($redirectData);
- }
-
- $sql = "UPDATE advertising_creatives SET
- name = ?,
- description = ?,
- view_url = ?,
- updated_at = CURRENT_TIMESTAMP
- WHERE id = ?";
-
- $params = [
- $redirectData['name'],
- 'Redirect from ' . $redirectData['source_url'] . ' to ' . $redirectData['target_url'],
- $redirectData['target_url'],
- $creative['id']
- ];
-
- return $this->db->query($sql, $params) > 0;
- }
-
- /**
- * Migrate all existing redirects to creatives
- */
- public function migrateAllRedirects(): array
- {
- $results = [];
-
- // Get all redirects that don't have associated creatives
- $sql = "SELECT r.* FROM redirects r
- LEFT JOIN advertising_creatives ac ON ac.creative_type = 'redirect'
- AND ac.description LIKE CONCAT('%Redirect from ', r.id, '%')
- WHERE r.status >= 0 AND ac.id IS NULL";
-
- $redirects = $this->db->fetchAll($sql);
-
- foreach ($redirects as $redirect) {
- try {
- $success = $this->createCreativeFromRedirect($redirect);
- $results[] = [
- 'redirect_id' => $redirect['id'],
- 'redirect_name' => $redirect['name'],
- 'success' => $success,
- 'message' => $success ? 'Creative created successfully' : 'Failed to create creative'
- ];
- } catch (\Exception $e) {
- $results[] = [
- 'redirect_id' => $redirect['id'],
- 'redirect_name' => $redirect['name'],
- 'success' => false,
- 'message' => 'Error: ' . $e->getMessage()
- ];
- }
- }
-
- return $results;
- }
-
- /**
- * Get creative by redirect ID
- */
- public function getCreativeByRedirectId(int $redirectId): ?array
- {
- // First, get the redirect to find its target_url
- $redirect = $this->db->fetch("SELECT target_url FROM redirects WHERE id = ?", [$redirectId]);
- if (!$redirect) {
- return null;
- }
-
- // Find creative by view_url (which should match target_url)
- $sql = "SELECT * FROM advertising_creatives
- WHERE creative_type = 'redirect'
- AND view_url = ?";
-
- return $this->db->fetch($sql, [$redirect['target_url']]) ?: null;
- }
-
- /**
- * Get all redirect creatives
- */
- public function getAllRedirectCreatives(): array
- {
- $sql = "SELECT * FROM advertising_creatives
- WHERE creative_type = 'redirect'
- AND is_active = 1
- ORDER BY created_at DESC";
-
- return $this->db->fetchAll($sql) ?: [];
- }
-
- /**
- * Delete creative when redirect is deleted
- */
- public function deleteCreativeByRedirectId(int $redirectId): bool
- {
- try {
- $creative = $this->getCreativeByRedirectId($redirectId);
- if (!$creative) {
- // Se não existe creative associado, consideramos sucesso
- return true;
- }
-
- $sql = "UPDATE advertising_creatives SET
- is_active = 0,
- deleted_at = CURRENT_TIMESTAMP
- WHERE id = ?";
-
- return $this->db->query($sql, [$creative['id']]) > 0;
- } catch (\Exception $e) {
- // Log do erro mas não falha a operação
- error_log("Error deleting creative for redirect {$redirectId}: " . $e->getMessage());
- return true; // Consideramos sucesso para não bloquear a eliminação do redirect
- }
- }
-
- /**
- * Generate unique CUID for creative
- */
- private function generateCuid(): string
- {
- return 'creative_' . uniqid() . '_' . time();
- }
-
- /**
- * Generate file name for creative
- */
- private function generateFileName(string $name): string
- {
- return 'redirect_' . preg_replace('/[^a-zA-Z0-9]/', '_', $name) . '.html';
- }
-
- /**
- * Get redirect statistics for creative
- */
- public function getRedirectStatsForCreative(int $creativeId): array
- {
- $creative = $this->db->fetch("SELECT * FROM advertising_creatives WHERE id = ?", [$creativeId]);
- if (!$creative || $creative['creative_type'] !== 'redirect') {
- return [];
- }
-
- // Extract redirect ID from description or use creative ID as reference
- // This is a simplified approach - in production you might want a proper mapping table
- $redirectId = $creativeId; // Simplified for now
-
- return $this->redirectModel->getRedirectStats($redirectId);
- }
-}
diff --git a/crm/Redirects/Services/RedirectProcessor.php b/crm/Redirects/Services/RedirectProcessor.php
deleted file mode 100644
index 3b58900..0000000
--- a/crm/Redirects/Services/RedirectProcessor.php
+++ /dev/null
@@ -1,16 +0,0 @@
-
-
-
-
-
- Filter Type *
-
- Select filter type...
-
-
-
-
-
- Operator *
-
- Select operator...
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/crm/Redirects/Views/dashboard.php b/crm/Redirects/Views/dashboard.php
deleted file mode 100644
index c7f51f4..0000000
--- a/crm/Redirects/Views/dashboard.php
+++ /dev/null
@@ -1,289 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
Total Redirects
-
= number_format($stats['total_redirects']) ?>
-
-
-
-
-
-
-
-
-
-
-
-
-
Active Redirects
-
= number_format($stats['active_redirects']) ?>
-
-
-
-
-
-
-
-
-
-
-
-
-
Inactive Redirects
-
= number_format($stats['inactive_redirects']) ?>
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
No redirects yet
-
Create your first redirect to get started
-
Create Redirect
-
-
-
-
-
-
- Name
- Target URL
- Status
- Created
- Actions
-
-
-
-
-
-
-
-
-
-
-
-
-
-
= htmlspecialchars($redirect['name']) ?>
- = htmlspecialchars($redirect['id']) ?>
-
-
-
-
-
- = htmlspecialchars($redirect['target_url']) ?>
-
-
-
-
- Active
-
- Inactive
-
- Deleted
-
-
-
- = date('M j, Y', strtotime($redirect['created_at'])) ?>
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
How Redirects Work
-
-
-
-
-
-
-
-
-
1. Create Redirect
-
Set up your source and target URLs with optional filters
-
-
-
-
-
-
-
-
-
-
2. Add Filters
-
Target by country, browser, device, time, and more
-
-
-
-
-
-
-
-
-
-
3. Track Analytics
-
Monitor performance and user behavior in real-time
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/crm/Redirects/Views/redirects/create.php b/crm/Redirects/Views/redirects/create.php
deleted file mode 100644
index 8bb6cb6..0000000
--- a/crm/Redirects/Views/redirects/create.php
+++ /dev/null
@@ -1,412 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/crm/Redirects/Views/redirects/edit.php b/crm/Redirects/Views/redirects/edit.php
deleted file mode 100644
index 3fdfac5..0000000
--- a/crm/Redirects/Views/redirects/edit.php
+++ /dev/null
@@ -1,138 +0,0 @@
-
-
-
-
-
-
-
-
-
- Loading...
-
-
A carregar dados do redirect...
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/crm/Redirects/Views/redirects/index.php b/crm/Redirects/Views/redirects/index.php
deleted file mode 100644
index 17f6fdb..0000000
--- a/crm/Redirects/Views/redirects/index.php
+++ /dev/null
@@ -1,366 +0,0 @@
-
-
-
-
-
-
- Loading...
-
-
A carregar redirects...
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Redirects ( )
-
-
- Criar Redirect
-
-
-
-
-
-
-
Nenhum redirect encontrado
-
Crie o seu primeiro redirect para começar
-
Criar Redirect
-
-
-
-
-
-
-
- Nome
- URL de Origem
- URL de Destino
- Estado
- Tipo
- Rastreamento
- Criado
- Ações
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/crm/Redirects/Views/redirects/view.php b/crm/Redirects/Views/redirects/view.php
deleted file mode 100644
index b4d63f0..0000000
--- a/crm/Redirects/Views/redirects/view.php
+++ /dev/null
@@ -1,356 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
Name: = htmlspecialchars($redirect['name']) ?>
-
Status:
-
- = $redirect['status'] == 1 ? 'Active' : 'Inactive' ?>
-
-
-
Redirect Type: = htmlspecialchars($redirect['redirect_type']) ?>
-
Tracking:
-
- = $redirect['tracking_enabled'] ? 'Enabled' : 'Disabled' ?>
-
-
-
-
-
Created: = date('M j, Y H:i', strtotime($redirect['created_at'])) ?>
-
Updated: = date('M j, Y H:i', strtotime($redirect['updated_at'])) ?>
-
-
Expires: = date('M j, Y H:i', strtotime($redirect['expires_at'])) ?>
-
-
-
Max Clicks: = number_format($redirect['max_clicks']) ?>
-
-
-
-
-
-
-
-
-
Source URL
-
= htmlspecialchars($redirect['source_url']) ?>
-
-
-
Target URL
-
= htmlspecialchars($redirect['target_url']) ?>
-
-
-
Fallback URL
-
= $redirect['fallback_url'] ? htmlspecialchars($redirect['fallback_url']) : 'None ' ?>
-
-
-
-
-
-
-
-
-
Analytics Público
-
Partilha este link para permitir acesso público aos analytics deste redirect
-
-
- Analytics slug não encontrado. Contacte o administrador.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
No filters configured. All visitors will be redirected to the target URL.
-
-
-
-
-
- Type
- Value
- Operator
- Priority
- Status
- Actions
-
-
-
-
-
- = htmlspecialchars(ucfirst($filter['filter_type'])) ?>
- = htmlspecialchars($filter['filter_value']) ?>
- = htmlspecialchars(ucfirst(str_replace('_', ' ', $filter['filter_operator']))) ?>
- = $filter['priority'] ?>
-
-
- = $filter['is_active'] ? 'Active' : 'Inactive' ?>
-
-
-
- Edit
- Delete
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
= number_format($stats['total_clicks'] ?? 0) ?>
-
Total Clicks
-
-
-
= number_format($stats['unique_clicks'] ?? 0) ?>
-
Unique Clicks
-
-
-
-
-
-
= number_format($stats['unique_ips'] ?? 0) ?>
-
Unique IPs
-
-
-
= number_format($stats['avg_response_time'] ?? 0, 1) ?>ms
-
Avg Response
-
-
-
-
-
-
-
-
-
-
-
No recent activity
-
-
-
-
-
-
-
Click from = htmlspecialchars($activity['ip_address']) ?>
-
- = date('M j, Y H:i', strtotime($activity['timestamp'])) ?>
-
- • = htmlspecialchars($activity['country_code']) ?>
-
-
- • = htmlspecialchars($activity['browser']) ?>
-
-
-
-
-
= htmlspecialchars($activity['device_type']) ?>
-
-
-
= htmlspecialchars($activity['city']) ?>
-
-
-
- → = htmlspecialchars($activity['target_url_used']) ?>
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/crm/Redirects/Views/settings.php b/crm/Redirects/Views/settings.php
deleted file mode 100644
index d72d484..0000000
--- a/crm/Redirects/Views/settings.php
+++ /dev/null
@@ -1,308 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
- Version: 1.0.0
-
-
- Author: BitReport Unip. LDA
-
-
- Last Updated: = date('M j, Y') ?>
-
-
- Status:
- Active
-
-
-
-
-
-
-
-
-
-
- Export Data
-
-
- Clear Old Data
-
-
- Test Geo Detection
-
-
- Reset to Defaults
-
-
-
-
-
-
-
-
-
-
- Database Tables:
- ✓ All Present
-
-
- Geo Detection:
- ✓ Working
-
-
- Tracking:
- ✓ Active
-
-
- Performance:
- ✓ Optimized
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/crm/Redirects/Views/stats/index.php b/crm/Redirects/Views/stats/index.php
deleted file mode 100644
index 5e720dd..0000000
--- a/crm/Redirects/Views/stats/index.php
+++ /dev/null
@@ -1,441 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Intervalo de Datas
-
-
- Todo o Tempo
- Últimos 7 Dias
- Últimos 30 Dias
- Últimos 90 Dias
- Este Mês
- Este Ano
- Intervalo Personalizado
-
-
-
-
-
-
-
- Tracker
-
-
- All Trackers
-
-
-
-
-
-
-
-
-
-
- País
-
-
- All Countries
-
-
-
-
-
-
-
-
-
-
- Dispositivo
-
-
- All Devices
- Desktop
- Mobile
- Tablet
- Bot
-
-
-
-
-
-
-
- Navegador
-
-
- All Browsers
-
-
-
-
-
-
-
-
-
-
- Sistema Operativo
-
-
- All Operating Systems
-
-
-
-
-
-
-
-
-
-
- Data Início
-
-
-
-
-
-
- Data Fim
-
-
-
-
-
-
-
-
-
-
- Filtrar
-
-
-
- Reset
-
-
-
- Exportar
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Tempo Médio de Resposta
-
0 ms
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- País
- Cliques
- Percentagem
-
-
-
-
-
-
-
-
-
-
-
-
-
- Nenhum dado disponível
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Dispositivo
- Cliques
- Percentagem
-
-
-
-
-
-
-
-
-
-
-
-
-
- Nenhum dado disponível
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/crm/Redirects/config.php b/crm/Redirects/config.php
deleted file mode 100644
index cea6db4..0000000
--- a/crm/Redirects/config.php
+++ /dev/null
@@ -1,92 +0,0 @@
- [
- 'default_status' => 'active',
- 'statuses' => ['active', 'inactive', 'deleted'],
- 'types' => ['301', '302', 'meta', 'javascript'],
- 'targeting_options' => [
- 'geo' => true,
- 'device' => true,
- 'browser' => true,
- 'time' => true,
- 'referer' => true
- ]
- ],
- 'tracking' => [
- 'enabled' => true,
- 'retention_days' => 90,
- 'aggregation_enabled' => true,
- 'max_filters_per_redirect' => 10
- ],
- 'filters' => [
- 'types' => [
- 'browser' => [
- 'label' => 'Browser',
- 'operators' => ['equals', 'contains', 'in', 'not_in'],
- 'values' => ['Chrome', 'Firefox', 'Safari', 'Edge', 'Opera', 'IE']
- ],
- 'os' => [
- 'label' => 'Operating System',
- 'operators' => ['equals', 'contains', 'in', 'not_in'],
- 'values' => ['Windows', 'macOS', 'Linux', 'iOS', 'Android']
- ],
- 'device_type' => [
- 'label' => 'Device Type',
- 'operators' => ['equals', 'in', 'not_in'],
- 'values' => ['desktop', 'mobile', 'tablet', 'bot']
- ],
- 'country' => [
- 'label' => 'Country',
- 'operators' => ['equals', 'in', 'not_in'],
- 'values' => ['PT', 'US', 'BR', 'ES', 'FR', 'DE', 'IT', 'NL', 'BE', 'CH']
- ],
- 'city' => [
- 'label' => 'City',
- 'operators' => ['equals', 'contains', 'starts_with', 'ends_with']
- ],
- 'region' => [
- 'label' => 'Region',
- 'operators' => ['equals', 'contains', 'starts_with', 'ends_with']
- ],
- 'timezone' => [
- 'label' => 'Timezone',
- 'operators' => ['equals', 'contains', 'in', 'not_in'],
- 'values' => ['Europe/Lisbon', 'America/New_York', 'America/Sao_Paulo', 'Europe/London']
- ],
- 'language' => [
- 'label' => 'Language',
- 'operators' => ['equals', 'starts_with', 'in', 'not_in'],
- 'values' => ['pt-PT', 'en-US', 'es-ES', 'fr-FR', 'de-DE', 'it-IT']
- ],
- 'referer' => [
- 'label' => 'Referer',
- 'operators' => ['contains', 'starts_with', 'ends_with', 'regex']
- ],
- 'hour' => [
- 'label' => 'Hour of Day',
- 'operators' => ['equals', 'greater_than', 'less_than', 'between'],
- 'values' => range(0, 23)
- ],
- 'asn' => [
- 'label' => 'ASN',
- 'operators' => ['equals', 'contains', 'in', 'not_in']
- ],
- 'isp' => [
- 'label' => 'ISP',
- 'operators' => ['equals', 'contains', 'starts_with', 'ends_with']
- ]
- ]
- ],
- 'performance' => [
- 'rate_limit_per_ip' => 100,
- 'cache_enabled' => true,
- 'cache_ttl' => 300, // 5 minutes
- 'max_response_time' => 1000 // 1 second
- ],
- 'security' => [
- 'allowed_domains' => [],
- 'blocked_domains' => [],
- 'validate_urls' => true,
- 'sanitize_inputs' => true
- ]
-];
\ No newline at end of file
diff --git a/crm/Redirects/menu.php b/crm/Redirects/menu.php
deleted file mode 100644
index 4dd6223..0000000
--- a/crm/Redirects/menu.php
+++ /dev/null
@@ -1,62 +0,0 @@
- 11,
- 'label' => 'Redirects',
- 'icon' => 'ri-link',
- 'url' => '/redirects',
- 'order' => 4,
- 'parent_id' => null,
- 'dev' => 0,
-]);
-
-// Submenus do Redirects
-MenuManager::registerMenus('Redirects', [
- [
- 'id' => 1101,
- 'label' => 'Dashboard',
- 'icon' => 'ri-dashboard-line',
- 'url' => '/redirects',
- 'order' => 1,
- 'parent_id' => 11,
- 'dev' => 0,
- ],
- [
- 'id' => 1102,
- 'label' => 'All Redirects',
- 'icon' => 'ri-list-check',
- 'url' => '/redirects/redirects',
- 'order' => 2,
- 'parent_id' => 11,
- 'dev' => 0,
- ],
- [
- 'id' => 1103,
- 'label' => 'Create Redirect',
- 'icon' => 'ri-add-line',
- 'url' => '/redirects/redirects/create',
- 'order' => 3,
- 'parent_id' => 11,
- 'dev' => 0,
- ],
- [
- 'id' => 1104,
- 'label' => 'Analytics',
- 'icon' => 'ri-bar-chart-line',
- 'url' => '/redirects/stats',
- 'order' => 4,
- 'parent_id' => 11,
- 'dev' => 0,
- ],
- [
- 'id' => 1105,
- 'label' => 'Settings',
- 'icon' => 'ri-settings-3-line',
- 'url' => '/redirects/settings',
- 'order' => 5,
- 'parent_id' => 11,
- 'dev' => 0,
- ],
-]);
\ No newline at end of file
diff --git a/crm/Routes/web.php b/crm/Routes/web.php
index a5a6574..ed67682 100644
--- a/crm/Routes/web.php
+++ b/crm/Routes/web.php
@@ -20,7 +20,10 @@ use App\Core\Router;
use App\Core\View;
// Register pages namespace
-View::addNamespace('pages', __DIR__ . '/../Views/pages');
+View::addNamespace('pages', __DIR__ . '/../Modules/Views');
+
+// Load pages routes
+require_once __DIR__ . '/../Modules/Routes/web.php';
// --- Module Loader ---
$modulesDir = __DIR__ . '/../Modules';
@@ -59,7 +62,7 @@ $router = Router::getInstance();
// Redirect to login if not authenticated, otherwise to redirects dashboard
$router->get('/', function() {
if (!\App\Core\Auth::check()) {
- header('Location: /login');
+ header('Location: /auth/login');
exit();
}
header('Location: /redirects');
@@ -70,7 +73,7 @@ $router->get('/', function() {
// Protect /dashboard route - require authentication
$router->get('/dashboard', function() {
if (!\App\Core\Auth::check()) {
- header('Location: /login');
+ header('Location: /auth/login');
exit();
}
header('Location: /redirects');
@@ -79,6 +82,7 @@ $router->get('/dashboard', function() {
+
// System status redirects
$router->get('/system/status', function() {
header('Content-Type: application/json');
@@ -86,19 +90,6 @@ $router->get('/system/status', function() {
exit;
});
-// --- Catch-all 404 Route ---
-$router->get('/{path}', function (
- $path
-) {
- http_response_code(404);
- View::render('@pages/404', [
- 'title' => '404 Error - Page not found',
- 'page_content' => function() use ($path) {
- View::render('components/404.php', ['page' => $path]);
- }
- ]);
-});
-
// --- Dashboard API Routes ---
$router->get('/api/dashboard/stats', [App\Api\DashboardController::class, 'stats']);
$router->get('/api/dashboard/available-widgets', [App\Api\DashboardController::class, 'getAvailableWidgets']);
@@ -123,3 +114,16 @@ $router->get('/tools/mb-search', function() {
// --- Public Campaign Analytics Routes ---
$router->get('/public/analytics/{slug}', [App\Modules\Controllers\PublicCampaignsController::class, 'analytics']);
$router->get('/api/campaigns/{slug}', [App\Modules\Controllers\PublicCampaignsController::class, 'getCampaignStats']);
+
+// --- Catch-all 404 Route (MUST BE LAST!) ---
+$router->get('/{path}', function (
+ $path
+) {
+ http_response_code(404);
+ View::render('@pages/404', [
+ 'title' => '404 Error - Page not found',
+ 'page_content' => function() use ($path) {
+ View::render('components/404.php', ['page' => $path]);
+ }
+ ]);
+});
diff --git a/crm/Views/assets/lang/pt.json b/crm/Views/assets/lang/pt.json
index 0519ecb..39722c3 100644
--- a/crm/Views/assets/lang/pt.json
+++ b/crm/Views/assets/lang/pt.json
@@ -1 +1,41 @@
-
\ No newline at end of file
+{
+ "t-users-title": "Utilizadores",
+ "t-logout": "Sair",
+ "common": {
+ "save": "Guardar",
+ "cancel": "Cancelar",
+ "delete": "Eliminar",
+ "edit": "Editar",
+ "close": "Fechar",
+ "search": "Pesquisar",
+ "loading": "A carregar...",
+ "error": "Erro",
+ "success": "Sucesso",
+ "confirm": "Confirmar"
+ },
+ "redirects": {
+ "title": "Redirects",
+ "create": "Criar Redirect",
+ "edit": "Editar Redirect",
+ "delete": "Eliminar Redirect",
+ "name": "Nome",
+ "source_url": "URL de Origem",
+ "target_url": "URL de Destino",
+ "status": "Estado",
+ "type": "Tipo",
+ "created_at": "Criado em",
+ "updated_at": "Atualizado em",
+ "clicks": "Cliques",
+ "active": "Ativo",
+ "inactive": "Inativo"
+ },
+ "campaigns": {
+ "title": "Campanhas",
+ "create": "Criar Campanha",
+ "edit": "Editar Campanha"
+ },
+ "dashboard": {
+ "title": "Dashboard",
+ "welcome": "Bem-vindo"
+ }
+}
diff --git a/crm/Views/components/faqs/general-questions.php b/crm/Views/components/faqs/general-questions.php
index 350b89e..7c3364b 100644
--- a/crm/Views/components/faqs/general-questions.php
+++ b/crm/Views/components/faqs/general-questions.php
@@ -7,7 +7,7 @@
-
General Questions
+ Questões Gerais
@@ -15,24 +15,39 @@
- If several languages coalesce, the grammar of the resulting language is more simple and regular than that of the individual languages. The new common language will be more simple and regular than the existing European languages. It will be as simple their most common words.
+ O MoneyFlix Redirect System é uma plataforma de gestão de links curtos e redirecionamentos com analytics integrado. Permite criar, gerir e monitorizar links de redirecionamento com rastreamento detalhado de clicks, origem geográfica, dispositivos e muito mais.
- The new common language will be more simple and regular than the existing European languages. It will be as simple as Occidental; in fact, it will be Occidental. To an English person, it will seem like simplified English, as a skeptical Cambridge friend of mine told me what Occidental is.
+ Para criar um redirect: 1) Aceda a "Redirects" no menu lateral, 2) Clique em "Criar Redirect", 3) Preencha o nome, URL de destino e configurações, 4) Clique em "Guardar". O sistema irá gerar automaticamente um link curto único e um slug de analytics para acompanhamento.
+
+
+
+
+
+
+
+ 301 - Permanente: Indica que o conteúdo foi movido permanentemente (melhor para SEO).
+ 302 - Temporário: Redirecionamento temporário (ideal para campanhas).
+ Meta Refresh: Redirect via HTML meta tag.
+ JavaScript: Redirect via JavaScript (permite tracking avançado).
diff --git a/crm/Views/components/faqs/header.php b/crm/Views/components/faqs/header.php
index d2413a6..5671f6c 100644
--- a/crm/Views/components/faqs/header.php
+++ b/crm/Views/components/faqs/header.php
@@ -6,11 +6,11 @@
-
Frequently asked questions
-
If you can not find answer to your question in our FAQ, you can always contact us or email us. We will answer you shortly!
+
Perguntas Frequentes
+
Encontre aqui respostas sobre como utilizar o MoneyFlix Redirect System - criar redirects, aceder a analytics e gerir as suas campanhas.
diff --git a/crm/Views/components/faqs/manage-account.php b/crm/Views/components/faqs/manage-account.php
index 5703c03..d21f57d 100644
--- a/crm/Views/components/faqs/manage-account.php
+++ b/crm/Views/components/faqs/manage-account.php
@@ -6,7 +6,7 @@
-
Manage Account
+ Analytics e Rastreamento
@@ -14,24 +14,36 @@
- If several languages coalesce, the grammar of the resulting language is more simple and regular than that of the individual languages. The new common language will be more simple and regular than the existing European languages. It will be as simple their most common words.
+ Cada redirect tem um link de analytics público que pode ser partilhado. Na lista de redirects, clique no menu de ações (três pontos) e selecione "Analytics Público". O link tem o formato: /public/analytics/{analytics_slug}. Este link é público e pode ser partilhado com terceiros para visualização de estatísticas.
- The new common language will be more simple and regular than the existing European languages. It will be as simple as Occidental; in fact, it will be Occidental. To an English person, it will seem like simplified English, as a skeptical Cambridge friend of mine told me what Occidental is.
+ O sistema rastreia: número total de clicks, clicks únicos (por IP), país de origem, tipo de dispositivo (desktop/mobile/tablet), navegador, sistema operativo, e timestamp de cada acesso. Todos os dados são apresentados em gráficos interativos e podem ser filtrados por período.
+
+
+
+
+
+
+
+ Cada redirect tem um CUID (identificador único) que pode ser usado como link curto. O formato é /r/{cuid}. Por exemplo: redirect.moneyflix.com/r/mf_bonus. Este link redireciona para o URL de destino e regista a estatística do acesso.
diff --git a/crm/Views/components/faqs/privacy-security.php b/crm/Views/components/faqs/privacy-security.php
index 55a51b4..196b956 100644
--- a/crm/Views/components/faqs/privacy-security.php
+++ b/crm/Views/components/faqs/privacy-security.php
@@ -10,7 +10,7 @@ use App\Core\View;
-
Privacy & Security
+ Gestão e Configurações
@@ -18,48 +18,48 @@ use App\Core\View;
- If several languages coalesce, the grammar of the resulting language is more simple and regular than that of the individual languages. The new common language will be more simple and regular than the existing European languages. It will be as simple their most common words.
+ Na lista de redirects, clique no menu de ações (três pontos) ao lado de cada redirect. Pode selecionar "Editar" para modificar as configurações, ou "Apagar" para eliminar o redirect. Note que eliminar um redirect é permanente e as estatísticas associadas serão perdidas.
- The new common language will be more simple and regular than the existing European languages. It will be as simple as Occidental; in fact, it will be Occidental. To an English person, it will seem like simplified English, as a skeptical Cambridge friend of mine told me what Occidental is.
+ Sim! Ao criar ou editar um redirect, pode definir uma data de expiração e também um número máximo de clicks. Quando o redirect expira ou atinge o limite de clicks, é automaticamente desativado e pode redirecionar para um URL de fallback alternativo.
- he wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains.But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete.
+ Na lista de redirects, clique no menu de ações e selecione "Testar". Isso abrirá o link de redirect numa nova aba, permitindo verificar se está a funcionar corretamente antes de partilhar com terceiros. O teste também será contabilizado nas estatísticas.
- Cras ultricies mi eu turpis hendrerit fringilla. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In ac dui quis mi consectetuer lacinia. Nam pretium turpis et arcu arcu tortor, suscipit eget, imperdiet nec, imperdiet iaculis aliquam ultrices mauris.
+ Apenas utilizadores autenticados podem criar e gerir redirects. No entanto, as páginas de analytics públicos (/public/analytics/{slug}) são acessíveis a qualquer pessoa com o link, permitindo partilhar estatísticas com clientes ou parceiros sem necessidade de login.
diff --git a/crm/Views/layouts/auth.php b/crm/Views/layouts/auth.php
index fe55922..b8807fa 100644
--- a/crm/Views/layouts/auth.php
+++ b/crm/Views/layouts/auth.php
@@ -54,6 +54,6 @@ $branding = Branding::get();
-
+