<?php
/**
 * Kontroler Dashboard
 */

require_once __DIR__ . '/BaseController.php';

class DashboardController extends BaseController
{
    /**
     * Strona główna / Dashboard
     */
    public function index(): void
    {
        $userModel = new User();
        $deviceModel = new Device();
        $playlistModel = new Playlist();

        $data = [
            'pageTitle' => 'Dashboard'
        ];

        if ($this->auth->isAdmin()) {
            // === DASHBOARD ADMINA ===
            $data['userStats'] = $userModel->getStats();
            $data['deviceStats'] = $deviceModel->getStats();
            $data['playlistStats'] = $playlistModel->getStats();
            
            // Statystyki resellerów
            $data['resellerStats'] = $this->getResellerStats($userModel);
            
            // Ostatnie logi z badge_class
            $recentLogs = $this->logger->getLogs(10);
            foreach ($recentLogs as &$log) {
                $log['badge_class'] = $this->getBadgeClass($log['action']);
            }
            $data['recentLogs'] = $recentLogs;
            $data['recentApiLogs'] = $this->logger->getApiLogs(10);
            
            // Ostatni użytkownicy
            $data['recentUsers'] = $userModel->getAll(5);
            
        } elseif ($this->auth->isReseller()) {
            // === DASHBOARD RESELLERA ===
            $resellerId = $this->currentUser['id'];
            
            // Wykorzystanie limitów
            $data['resellerUsage'] = $userModel->getResellerUsage($resellerId);
            
            // Moi użytkownicy
            $data['myUsers'] = $userModel->getByParentId($resellerId, 5);
            $data['myUsersCount'] = $userModel->countByParentId($resellerId);
            
            // Moje urządzenia
            $data['myDevices'] = $deviceModel->getByUserId($resellerId, 5);
            $data['myDevicesCount'] = $deviceModel->countByUserId($resellerId);
            
            // Moje playlisty
            $data['myPlaylistsCount'] = $playlistModel->countByUserId($resellerId);
            
            // Urządzenia moich userów
            $visibleUserIds = $userModel->getVisibleUserIds($this->currentUser);
            $data['totalManagedDevices'] = $deviceModel->countByUserIds($visibleUserIds);
            $data['totalManagedPlaylists'] = $playlistModel->countByUserIds($visibleUserIds);
            
            // Ostatnia aktywność moich userów
            $data['recentUserLogins'] = $this->getRecentUserLogins($userModel, $resellerId);
            
        } else {
            // === DASHBOARD UŻYTKOWNIKA ===
            $userId = $this->currentUser['id'];
            
            // Moje urządzenia
            $data['myDevices'] = $deviceModel->getByUserId($userId, 5);
            $data['myDevicesCount'] = $deviceModel->countByUserId($userId);
            
            // Moje playlisty
            $data['myPlaylistsCount'] = $playlistModel->countByUserId($userId);
            
            // Limity
            $data['deviceLimit'] = $this->currentUser['device_limit'];
            $data['playlistLimit'] = $this->currentUser['playlist_limit'] ?? 100;
            
            // Ostatnie playlisty
            $data['recentPlaylists'] = $playlistModel->getByUserId($userId, 5);
        }

        $this->render('dashboard.tpl', $data);
    }
    
    /**
     * Statystyki resellerów dla admina
     */
    private function getResellerStats(User $userModel): array
    {
        $db = Database::getInstance();
        
        // Lista resellerów z ich wykorzystaniem (własne + przydzielone)
        $resellers = $db->fetchAll(
            "SELECT u.id, u.username, u.max_users, u.max_devices, u.max_playlists,
                    (SELECT COUNT(*) FROM users WHERE parent_id = u.id) as users_count,
                    (SELECT COUNT(*) FROM devices WHERE user_id = u.id) as devices_own,
                    (SELECT COALESCE(SUM(device_limit), 0) FROM users WHERE parent_id = u.id) as devices_allocated,
                    (SELECT COUNT(*) FROM playlists p JOIN devices d ON p.device_id = d.id WHERE d.user_id = u.id) as playlists_own,
                    (SELECT COALESCE(SUM(playlist_limit), 0) FROM users WHERE parent_id = u.id) as playlists_allocated
             FROM users u
             WHERE u.role = 'reseller'
             ORDER BY u.username"
        );
        
        // Oblicz łączne wykorzystanie
        foreach ($resellers as &$r) {
            $r['devices_used'] = (int)$r['devices_own'] + (int)$r['devices_allocated'];
            $r['playlists_used'] = (int)$r['playlists_own'] + (int)$r['playlists_allocated'];
        }
        
        return $resellers;
    }
    
    /**
     * Ostatnie logowania userów resellera
     */
    private function getRecentUserLogins(User $userModel, int $resellerId): array
    {
        $db = Database::getInstance();
        
        return $db->fetchAll(
            "SELECT id, username, last_login 
             FROM users 
             WHERE parent_id = :parent_id AND last_login IS NOT NULL
             ORDER BY last_login DESC 
             LIMIT 5",
            ['parent_id' => $resellerId]
        );
    }
    
    /**
     * Określ klasę badge na podstawie akcji
     */
    private function getBadgeClass(string $action): string
    {
        if (strpos($action, 'failed') !== false || strpos($action, 'error') !== false) {
            return 'danger';
        }
        if (strpos($action, 'deleted') !== false || strpos($action, 'block') !== false) {
            return 'warning';
        }
        if (strpos($action, 'created') !== false || strpos($action, 'success') !== false) {
            return 'success';
        }
        if (strpos($action, 'login') !== false) {
            return 'primary';
        }
        return 'info';
    }
}
