<?php
namespace App\Services;

class ThemeService {
    private $pdo;

    public function __construct(\PDO $pdo) {
        $this->pdo = $pdo;
    }

    public function getAllThemes(): array {
        return $this->pdo->query("SELECT * FROM themes ORDER BY name")->fetchAll();
    }

    public function getActiveTheme(): ?array {
        $themeId = $this->pdo->query("SELECT id FROM themes WHERE is_default = 1 LIMIT 1")->fetchColumn();
        if (!$themeId) return null;
        $stmt = $this->pdo->prepare("SELECT * FROM themes WHERE id = ?");
        $stmt->execute([$themeId]);
        return $stmt->fetch() ?: null;
    }

    public function setActiveTheme(int $themeId): bool {
        $this->pdo->exec("UPDATE themes SET is_default = 0");
        $this->pdo->prepare("UPDATE themes SET is_default = 1 WHERE id = ?")->execute([$themeId]);
        $slug = $this->pdo->prepare("SELECT slug FROM themes WHERE id = ?");
        $slug->execute([$themeId]);
        $slug = $slug->fetchColumn();
        
        $stmt = $this->pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES ('default_theme', ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
        $stmt->execute([$slug]);
        return true;
    }

    public function getThemeCssVariables(int $themeId): string {
        $stmt = $this->pdo->prepare("SELECT css_variables FROM themes WHERE id = ?");
        $stmt->execute([$themeId]);
        $json = $stmt->fetchColumn();
        if (!$json) return '';
        
        $vars = json_decode($json, true);
        if (!is_array($vars)) return '';
        
        $css = ":root {\n";
        foreach ($vars as $key => $value) {
            $css .= "    {$key}: {$value};\n";
        }
        $css .= "}\n";
        return $css;
    }

    public function renderThemeCss(): string {
        $theme = $this->getActiveTheme();
        if (!$theme) return '';
        return '<style>' . $this->getThemeCssVariables($theme['id']) . '</style>';
    }

    public function getThemeByName(string $slug): ?array {
        $stmt = $this->pdo->prepare("SELECT * FROM themes WHERE slug = ?");
        $stmt->execute([$slug]);
        return $stmt->fetch() ?: null;
    }

    public function getThemeCount(): int {
        return (int)$this->pdo->query("SELECT COUNT(*) FROM themes")->fetchColumn();
    }

    public function getActiveThemeSlug(): string {
        return get_setting('default_theme', 'orbit-dark');
    }
}
