<?php
/**
 * Kontroler Raportów
 */

require_once __DIR__ . '/BaseController.php';

class ReportController extends BaseController
{
    private Reports $reports;
    private AuditLog $auditLog;
    private LoginSecurity $loginSecurity;
    
    public function __construct()
    {
        parent::__construct();
        
        if (!$this->auth->isAdmin()) {
            $this->redirect('dashboard', 'danger', 'Brak dostępu.');
            exit;
        }
        
        $this->reports = new Reports();
        $this->auditLog = new AuditLog();
        $this->loginSecurity = new LoginSecurity();
    }
    
    /**
     * Raport aktywności użytkowników
     */
    public function activity(): void
    {
        $days = (int)(get('days') ?: 30);
        $userId = get('user_id') ? (int)get('user_id') : null;
        
        $report = $this->reports->getUserActivityReport($days, $userId);
        
        $userModel = new User();
        $users = $userModel->getAll(1000);
        
        $this->render('reports/activity.tpl', [
            'pageTitle' => 'Raport aktywności',
            'report' => $report,
            'days' => $days,
            'userId' => $userId,
            'users' => $users
        ]);
    }
    
    /**
     * Raport API
     */
    public function api(): void
    {
        $days = (int)(get('days') ?: 30);
        $deviceId = get('device_id') ? (int)get('device_id') : null;
        
        $report = $this->reports->getApiReport($days, $deviceId);
        
        $deviceModel = new Device();
        $devices = $deviceModel->getAll(1000);
        
        $this->render('reports/api.tpl', [
            'pageTitle' => 'Raport API',
            'report' => $report,
            'days' => $days,
            'deviceId' => $deviceId,
            'devices' => $devices
        ]);
    }
    
    /**
     * Audit log (historia zmian)
     */
    public function audit(): void
    {
        $page = max(1, (int)(get('page') ?: 1));
        
        $filters = [
            'entity_type' => get('entity_type') ?: null,
            'action' => get('action') ?: null,
            'user_id' => get('user_id') ? (int)get('user_id') : null,
            'date_from' => get('date_from') ?: null,
            'date_to' => get('date_to') ?: null,
        ];
        
        $total = $this->auditLog->count($filters);
        $pagination = paginate($total, ITEMS_PER_PAGE, $page);
        
        $logs = $this->auditLog->getAll(ITEMS_PER_PAGE, $pagination['offset'], $filters);
        
        // Dekoduj JSON i sformatuj dla wyświetlenia
        foreach ($logs as &$log) {
            $log['old_values_decoded'] = $log['old_values'] ? json_decode($log['old_values'], true) : null;
            $log['new_values_decoded'] = $log['new_values'] ? json_decode($log['new_values'], true) : null;
            
            // Sformatowany JSON do wyświetlenia
            $log['old_values_formatted'] = $log['old_values_decoded'] 
                ? json_encode($log['old_values_decoded'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) 
                : null;
            $log['new_values_formatted'] = $log['new_values_decoded'] 
                ? json_encode($log['new_values_decoded'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) 
                : null;
        }
        
        $userModel = new User();
        $users = $userModel->getAll(1000);
        
        $this->render('reports/audit.tpl', [
            'pageTitle' => 'Historia zmian',
            'logs' => $logs,
            'pagination' => $pagination,
            'filters' => $filters,
            'users' => $users
        ]);
    }
    
    /**
     * Historia logowań
     */
    public function logins(): void
    {
        $page = max(1, (int)(get('page') ?: 1));
        
        $filters = [
            'user_id' => get('user_id') ? (int)get('user_id') : null,
            'ip_address' => get('ip') ?: null,
            'success' => get('success') !== '' && get('success') !== null ? (get('success') === '1') : null,
            'date_from' => get('date_from') ?: null,
            'date_to' => get('date_to') ?: null,
        ];
        
        $total = $this->loginSecurity->countLogins($filters);
        $pagination = paginate($total, ITEMS_PER_PAGE, $page);
        
        $logins = $this->loginSecurity->getAllLogins(ITEMS_PER_PAGE, $pagination['offset'], $filters);
        
        $userModel = new User();
        $users = $userModel->getAll(1000);
        
        $stats = $this->loginSecurity->getSecurityStats(30);
        
        $this->render('reports/logins.tpl', [
            'pageTitle' => 'Historia logowań',
            'logins' => $logins,
            'pagination' => $pagination,
            'filters' => $filters,
            'users' => $users,
            'stats' => $stats
        ]);
    }
    
    /**
     * Strona eksportu
     */
    public function export(): void
    {
        $this->render('reports/export.tpl', [
            'pageTitle' => 'Eksport danych'
        ]);
    }
    
    /**
     * Eksport użytkowników CSV
     */
    public function exportUsers(): void
    {
        $filters = [
            'role' => get('role') ?: null,
            'parent_id' => get('parent_id') ? (int)get('parent_id') : null,
        ];
        
        $csv = $this->reports->exportUsersCsv($filters);
        $filename = 'uzytkownicy_' . date('Y-m-d_His') . '.csv';
        
        $this->logger->log('export', "Eksport użytkowników do CSV", $this->currentUser['id']);
        $this->reports->sendCsvDownload($csv, $filename);
    }
    
    /**
     * Eksport urządzeń CSV
     */
    public function exportDevices(): void
    {
        $userId = get('user_id') ? (int)get('user_id') : null;
        
        $csv = $this->reports->exportDevicesCsv($userId);
        $filename = 'urzadzenia_' . date('Y-m-d_His') . '.csv';
        
        $this->logger->log('export', "Eksport urządzeń do CSV", $this->currentUser['id']);
        $this->reports->sendCsvDownload($csv, $filename);
    }
    
    /**
     * Eksport playlist CSV
     */
    public function exportPlaylists(): void
    {
        $userId = get('user_id') ? (int)get('user_id') : null;
        $deviceId = get('device_id') ? (int)get('device_id') : null;
        
        $csv = $this->reports->exportPlaylistsCsv($userId, $deviceId);
        $filename = 'playlisty_' . date('Y-m-d_His') . '.csv';
        
        $this->logger->log('export', "Eksport playlist do CSV", $this->currentUser['id']);
        $this->reports->sendCsvDownload($csv, $filename);
    }
    
    /**
     * Eksport historii logowań CSV
     */
    public function exportLogins(): void
    {
        $days = (int)(get('days') ?: 30);
        
        $csv = $this->reports->exportLoginHistoryCsv($days);
        $filename = 'logowania_' . date('Y-m-d_His') . '.csv';
        
        $this->logger->log('export', "Eksport historii logowań do CSV", $this->currentUser['id']);
        $this->reports->sendCsvDownload($csv, $filename);
    }
}
