<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Theme extends Model
{
    protected $fillable = [
        'name',
        'slug',
        'description',
        'is_active',
        'primary_color',
        'secondary_color',
        'accent_color',
        'font_family_body',
        'font_family_heading',
        'font_color_body',
        'font_color_heading',
        'font_color_link',
        'heading_size_scale',
        'heading_weight',
        'heading_spacing',
        'background_body',
        'background_card',
        'background_card_hero',
        'background_sidebar',
        'background_header',
        'background_footer',
        'scrollbar_track_color',
        'scrollbar_thumb_color',
        'scrollbar_width',
        'divider_color',
        'divider_style',
        'divider_width',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'heading_size_scale' => 'array',
    ];

    /**
     * Get the currently active theme
     */
    public static function getActive(): ?Theme
    {
        return static::where('is_active', true)->first();
    }

    /**
     * Set this theme as active and deactivate others
     */
    public function activate(): bool
    {
        return DB::transaction(function () {
            static::where('is_active', true)->update(['is_active' => false]);
            return $this->update(['is_active' => true]);
        });
    }

    /**
     * Get theme as CSS custom properties
     */
    public function toCssVariables(): array
    {
        return [
            '--theme-primary' => $this->primary_color,
            '--theme-secondary' => $this->secondary_color,
            '--theme-accent' => $this->accent_color,
            '--theme-font-body' => $this->font_family_body,
            '--theme-font-heading' => $this->font_family_heading,
            '--theme-color-body' => $this->font_color_body,
            '--theme-color-heading' => $this->font_color_heading,
            '--theme-color-link' => $this->font_color_link,
            '--theme-bg-body' => $this->background_body,
            '--theme-bg-card' => $this->background_card,
            '--theme-bg-card-hero' => $this->background_card_hero,
            '--theme-bg-sidebar' => $this->background_sidebar,
            '--theme-bg-header' => $this->background_header,
            '--theme-bg-footer' => $this->background_footer,
            '--theme-scrollbar-track' => $this->scrollbar_track_color,
            '--theme-scrollbar-thumb' => $this->scrollbar_thumb_color,
            '--theme-scrollbar-width' => $this->scrollbar_width,
            '--theme-divider-color' => $this->divider_color,
            '--theme-divider-style' => $this->divider_style,
            '--theme-divider-width' => $this->divider_width,
            '--theme-heading-weight' => $this->heading_weight,
            '--theme-heading-spacing' => $this->heading_spacing,
        ];
    }
}
