<?php

namespace Modules\VetSite\Entities;

use Illuminate\Database\Eloquent\Model;
use Modules\VetSite\Support\ThemeRegistry;

class VsSite extends Model
{
    protected $table = 'vs_sites';
    protected $guarded = ['id'];

    protected $casts = [
        'enabled'                => 'boolean',
        'custom_domain_verified' => 'boolean',
        'contact'                => 'array',
        'social'                 => 'array',
        'hours'                  => 'array',
        'nav'                    => 'array',
        'options'                => 'array',
    ];

    public function pages()
    {
        return $this->hasMany(VsPage::class, 'site_id')->orderBy('sort');
    }

    /** Get (or lazily create) the website row for a business. */
    public static function forBusiness($businessId): self
    {
        return static::firstOrCreate(
            ['business_id' => $businessId],
            ['enabled' => false, 'status' => 'draft', 'theme' => 'aurora']
        );
    }

    public function homePage(): ?VsPage
    {
        return $this->pages()->where('is_home', true)->first()
            ?? $this->pages()->where('status', 'published')->first();
    }

    /** Pages that appear in the site navigation. */
    public function navPages()
    {
        return $this->pages()
            ->where('status', 'published')
            ->where('show_in_nav', true)
            ->orderBy('sort')
            ->get();
    }

    public function isPublished(): bool
    {
        return $this->enabled && $this->status === 'published';
    }

    public function logoUrl(): ?string
    {
        return $this->logo_path ? asset('uploads/' . $this->logo_path) : null;
    }

    public function faviconUrl(): ?string
    {
        return $this->favicon_path ? asset('uploads/' . $this->favicon_path) : null;
    }

    public function ogImageUrl(): ?string
    {
        return $this->og_image_path ? asset('uploads/' . $this->og_image_path) : null;
    }

    /** Theme metadata (falls back to aurora if the stored theme is unknown). */
    public function themeMeta(): array
    {
        return ThemeRegistry::get($this->theme ?: 'aurora');
    }

    /**
     * Resolved colour palette — clinic overrides first, then theme defaults.
     */
    public function palette(): array
    {
        $defaults = $this->themeMeta()['palette'] ?? [];

        return [
            'primary'   => $this->primary_color   ?: ($defaults['primary']   ?? '#2563eb'),
            'secondary' => $this->secondary_color ?: ($defaults['secondary'] ?? '#0f172a'),
            'accent'    => $this->accent_color    ?: ($defaults['accent']    ?? '#f59e0b'),
        ];
    }

    public function fonts(): array
    {
        $meta = $this->themeMeta();

        return [
            'heading' => $this->font_heading ?: ($meta['fonts']['heading'] ?? 'Poppins'),
            'body'    => $this->font_body    ?: ($meta['fonts']['body'] ?? 'Inter'),
        ];
    }
}
