<?php

require_once APP_ROOT . '/models/Collection.php';

class HomeController
{
    public function __construct()
    {
        // Remove login check from constructor to allow language switching
    }

    public function index(): void
    {
        if (!Session::isLoggedIn()) {
            header('Location: ' . APP_URL . '/login');
            exit;
        }
        
        $userId = Session::getUserId();
        
        // Check if user needs to accept cookies (for existing logged in users)
        require_once APP_ROOT . '/models/User.php';
        $userModel = new User();
        if (!$userModel->hasAcceptedCookies($userId) && !Session::get('show_cookie_consent')) {
            Session::set('show_cookie_consent', 'true');
            header('Location: ' . APP_URL . '/home');
            exit;
        }
        
        $collectionModel = new Collection();
        $collections = $collectionModel->getAllByUser($userId);

        foreach ($collections as &$col) {
            $col['subcollection_count'] = $collectionModel->countSubcollections($col['id']);
            $col['item_count'] = $collectionModel->countItems($col['id']);
        }
        unset($col);

        $templates = $collectionModel->getTemplates();
        foreach ($templates as &$tpl) {
            $tpl['subcollection_count'] = $collectionModel->countSubcollections($tpl['id']);
            $tpl['item_count'] = $collectionModel->countItems($tpl['id']);
        }
        unset($tpl);

        require APP_ROOT . '/views/home/index.php';
    }

    public function setLanguage(string $locale): void
    {
        $allowed = ['en', 'cs', 'de', 'el', 'es', 'fr', 'hu', 'it', 'nl', 'no', 'pl', 'pt', 'ro', 'ru', 'sr', 'sv', 'tr', 'cn', 'jp', 'il'];
        if (in_array($locale, $allowed)) {
            Lang::setLocale($locale);
            
            // Save to user preferences if logged in
            if (Session::isLoggedIn()) {
                require_once APP_ROOT . '/models/User.php';
                $userModel = new User();
                $userModel->updatePreference(Session::getUserId(), 'default_language', $locale);
            }
        }

        // Language switch URLs are state-changing endpoints, not indexable localized pages.
        // Redirect to the referring page when possible, otherwise the public landing page.
        $referer = $_SERVER['HTTP_REFERER'] ?? '';
        if (empty($referer) || strpos($referer, APP_URL) !== 0) {
            $referer = APP_URL . '/';
        }
        
        header('Location: ' . $referer);
        exit;
    }

    public function setLanguageWithRedirect(string $locale, string $path): void
    {
        $allowed = ['en', 'cs', 'de', 'el', 'es', 'fr', 'hu', 'it', 'nl', 'no', 'pl', 'pt', 'ro', 'ru', 'sr', 'sv', 'tr', 'cn', 'jp', 'il'];
        if (in_array($locale, $allowed)) {
            Lang::setLocale($locale);
            
            // Save to user preferences if logged in
            if (Session::isLoggedIn()) {
                require_once APP_ROOT . '/models/User.php';
                $userModel = new User();
                $userModel->updatePreference(Session::getUserId(), 'default_language', $locale);
            }
        }

        // Redirect to the actual path without the language prefix
        $redirectUrl = APP_URL . '/' . ltrim($path, '/');
        header('Location: ' . $redirectUrl);
        exit;
    }
}
