<?php
/**
 * Kontroler Profilu użytkownika
 */

require_once __DIR__ . '/BaseController.php';

class ProfileController extends BaseController
{
    private UserProfile $profileModel;
    private LoginSecurity $loginSecurity;
    
    public function __construct()
    {
        parent::__construct();
        
        $this->profileModel = new UserProfile();
        $this->loginSecurity = new LoginSecurity();
    }
    
    /**
     * Widok profilu
     */
    public function index(): void
    {
        $profile = $this->profileModel->getByUserId($this->currentUser['id']);
        $loginHistory = $this->loginSecurity->getLoginHistory($this->currentUser['id'], 10);
        
        $this->render('profile/index.tpl', [
            'pageTitle' => 'Mój profil',
            'profile' => $profile,
            'loginHistory' => $loginHistory
        ]);
    }
    
    /**
     * Edycja profilu
     */
    public function edit(): void
    {
        $profile = $this->profileModel->getByUserId($this->currentUser['id']);
        
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!$this->verifyCsrf()) {
                return;
            }
            
            $data = [
                'full_name' => trim(post('full_name', '')),
                'email' => trim(post('email', '')),
                'phone' => trim(post('phone', '')),
                'company' => trim(post('company', '')),
                'address' => trim(post('address', '')),
                'timezone' => post('timezone', 'Europe/Warsaw'),
                'language' => post('language', 'pl'),
                'theme' => post('theme', 'dark'),
                'notifications_email' => post('notifications_email') ? 1 : 0,
                'notifications_browser' => post('notifications_browser') ? 1 : 0
            ];
            
            // Walidacja email
            if (!empty($data['email']) && !filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
                $this->render('profile/edit.tpl', [
                    'pageTitle' => 'Edycja profilu',
                    'profile' => array_merge($profile, $data),
                    'error' => 'Nieprawidłowy adres email.'
                ]);
                return;
            }
            
            $this->profileModel->update($this->currentUser['id'], $data);
            $this->logger->log('profile_updated', 'Zaktualizowano profil', $this->currentUser['id']);
            
            $this->redirect('profile', 'success', 'Profil został zaktualizowany.');
            return;
        }
        
        $this->render('profile/edit.tpl', [
            'pageTitle' => 'Edycja profilu',
            'profile' => $profile,
            'timezones' => $this->getTimezones()
        ]);
    }
    
    /**
     * Upload avatara
     */
    public function uploadAvatar(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->redirect('profile/edit');
            return;
        }
        
        if (!$this->verifyCsrf()) {
            return;
        }
        
        if (empty($_FILES['avatar']) || $_FILES['avatar']['error'] === UPLOAD_ERR_NO_FILE) {
            $this->redirect('profile/edit', 'danger', 'Nie wybrano pliku.');
            return;
        }
        
        $result = $this->profileModel->processAvatarUpload($this->currentUser['id'], $_FILES['avatar']);
        
        if ($result['success']) {
            $this->logger->log('avatar_updated', 'Zaktualizowano avatar', $this->currentUser['id']);
            $this->redirect('profile/edit', 'success', 'Avatar został zaktualizowany.');
        } else {
            $this->redirect('profile/edit', 'danger', $result['error']);
        }
    }
    
    /**
     * Usuń avatar
     */
    public function removeAvatar(): void
    {
        if (!$this->verifyCsrf()) {
            return;
        }
        
        $this->profileModel->removeAvatar($this->currentUser['id']);
        $this->logger->log('avatar_removed', 'Usunięto avatar', $this->currentUser['id']);
        
        $this->redirect('profile/edit', 'success', 'Avatar został usunięty.');
    }
    
    /**
     * Historia logowań użytkownika
     */
    public function loginHistory(): void
    {
        $page = max(1, (int)(get('page') ?: 1));
        
        $total = $this->loginSecurity->countLogins(['user_id' => $this->currentUser['id']]);
        $pagination = paginate($total, ITEMS_PER_PAGE, $page);
        
        $logins = $this->loginSecurity->getAllLogins(
            ITEMS_PER_PAGE, 
            $pagination['offset'],
            ['user_id' => $this->currentUser['id']]
        );
        
        $this->render('profile/login_history.tpl', [
            'pageTitle' => 'Historia logowań',
            'logins' => $logins,
            'pagination' => $pagination
        ]);
    }
    
    /**
     * Lista stref czasowych
     */
    private function getTimezones(): array
    {
        return [
            'Europe/Warsaw' => 'Europa/Warszawa (CET)',
            'Europe/London' => 'Europa/Londyn (GMT)',
            'Europe/Berlin' => 'Europa/Berlin (CET)',
            'Europe/Paris' => 'Europa/Paryż (CET)',
            'Europe/Moscow' => 'Europa/Moskwa (MSK)',
            'America/New_York' => 'USA/Nowy Jork (EST)',
            'America/Los_Angeles' => 'USA/Los Angeles (PST)',
            'America/Chicago' => 'USA/Chicago (CST)',
            'Asia/Tokyo' => 'Azja/Tokio (JST)',
            'Asia/Shanghai' => 'Azja/Szanghaj (CST)',
            'Asia/Dubai' => 'Azja/Dubaj (GST)',
            'Australia/Sydney' => 'Australia/Sydney (AEST)',
            'UTC' => 'UTC'
        ];
    }
}
