<?php

namespace AleshaCMS\CMS\Theme;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\File;

class ThemeManager
{
    protected string $activeTheme = 'default';
    protected array $themeConfig = [];

    public function __construct()
    {
        $this->activeTheme = Cache::remember('cms.active_theme', 3600, function () {
            return \AleshaCMS\Models\CMS\Setting::get('active_theme', 'default');
        });
    }

    public function getActive(): string
    {
        return $this->activeTheme;
    }

    public function setActive(string $theme): void
    {
        \AleshaCMS\Models\CMS\Setting::set('active_theme', $theme);
        Cache::forget('cms.active_theme');
        $this->activeTheme = $theme;
    }

    public function view(string $template, array $data = []): string
    {
        $view = $this->resolveView($template);
        return view($view, $data)->render();
    }

    public function resolveView(string $template): string
    {
        $themeView = "theme-{$this->activeTheme}::{$template}";

        if (view()->exists($themeView)) {
            return $themeView;
        }

        $defaultView = "theme-default::{$template}";

        if (view()->exists($defaultView)) {
            return $defaultView;
        }

        return $themeView;
    }

    public function getConfig(?string $theme = null): array
    {
        $theme = $theme ?? $this->activeTheme;
        $path = base_path("Themes/{$theme}/theme.json");

        if (!File::exists($path)) {
            return [];
        }

        return json_decode(File::get($path), true) ?? [];
    }

    public function getAvailableThemes(): array
    {
        $themesPath = base_path('Themes');
        $themes = [];

        if (!File::exists($themesPath)) {
            return $themes;
        }

        foreach (File::directories($themesPath) as $dir) {
            $slug = basename($dir);
            $configPath = "{$dir}/theme.json";
            $config = File::exists($configPath)
                ? json_decode(File::get($configPath), true)
                : ['name' => $slug, 'version' => '1.0.0'];

            $themes[] = array_merge($config, [
                'slug' => $slug,
                'is_active' => $slug === $this->activeTheme,
            ]);
        }

        return $themes;
    }

    public function supports(string $feature, ?string $theme = null): bool
    {
        $config = $this->getConfig($theme);
        return in_array($feature, $config['supports'] ?? []);
    }
}
