<?php

namespace App\Core;

class View
{
    private static string $viewsPath = '';

    public static function setViewsPath(string $path): void
    {
        self::$viewsPath = rtrim($path, '/');
    }

    public static function getViewsPath(): string
    {
        if (empty(self::$viewsPath)) {
            self::$viewsPath = dirname(__DIR__) . '/Views';
        }
        return self::$viewsPath;
    }

    public static function render(string $view, array $data = [], ?string $layout = 'main'): string
    {
        $viewPath = self::getViewsPath() . '/' . str_replace('.', '/', $view) . '.php';
        
        if (!file_exists($viewPath)) {
            throw new \Exception("Представление не найдено: {$viewPath}");
        }

        extract($data);

        ob_start();
        require $viewPath;
        $content = ob_get_clean();

        if ($layout !== null) {
            $layoutPath = self::getViewsPath() . '/layouts/' . $layout . '.php';
            
            if (!file_exists($layoutPath)) {
                throw new \Exception("Layout не найден: {$layoutPath}");
            }

            ob_start();
            require $layoutPath;
            $content = ob_get_clean();
        }

        return $content;
    }

    public static function partial(string $partial, array $data = []): string
    {
        $partialPath = self::getViewsPath() . '/partials/' . $partial . '.php';
        
        if (!file_exists($partialPath)) {
            throw new \Exception("Partial не найден: {$partialPath}");
        }

        extract($data);

        ob_start();
        require $partialPath;
        return ob_get_clean();
    }

    public static function escape(string $value): string
    {
        return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
    }

    public static function e(string $value): string
    {
        return self::escape($value);
    }

    public static function formatPrice($price): string
    {
        return number_format((float)$price, 0, '', ' ') . ' ₽';
    }

    public static function formatDate(string $date, string $format = 'd.m.Y'): string
    {
        return date($format, strtotime($date));
    }

    public static function formatDateTime(string $date, string $format = 'd.m.Y H:i'): string
    {
        return date($format, strtotime($date));
    }

    public static function getFlashMessages(): array
    {
        $messages = $_SESSION['flash'] ?? [];
        unset($_SESSION['flash']);
        return $messages;
    }

    public static function isAuthenticated(): bool
    {
        return isset($_SESSION['isLoggedIn']) && $_SESSION['isLoggedIn'] === true;
    }

    public static function isAdmin(): bool
    {
        return self::isAuthenticated() && isset($_SESSION['isAdmin']) && $_SESSION['isAdmin'] === true;
    }

    public static function currentUser(): ?array
    {
        if (!self::isAuthenticated()) {
            return null;
        }

        return [
            'id' => $_SESSION['user_id'] ?? null,
            'email' => $_SESSION['user_email'] ?? '',
            'full_name' => $_SESSION['full_name'] ?? '',
            'is_admin' => $_SESSION['isAdmin'] ?? false,
            'login_time' => $_SESSION['login_time'] ?? null
        ];
    }

    public static function url(string $path): string
    {
        return '/' . ltrim($path, '/');
    }

    public static function asset(string $path): string
    {
        return '/assets/' . ltrim($path, '/');
    }
}
