<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class HelpArticle extends Model
{
    protected $fillable = [
        'slug', 'title', 'content', 'excerpt', 'category', 'icon',
        'sort_order', 'is_published', 'helpful_count', 'not_helpful_count',
        'related_feature',
    ];

    protected function casts(): array
    {
        return [
            'is_published' => 'boolean',
            'sort_order' => 'integer',
            'helpful_count' => 'integer',
            'not_helpful_count' => 'integer',
        ];
    }

    public function scopePublished(Builder $query): Builder
    {
        return $query->where('is_published', true);
    }

    public function scopeCategory(Builder $query, string $category): Builder
    {
        return $query->where('category', $category);
    }

    public function scopeSearch(Builder $query, string $term): Builder
    {
        return $query->where(function ($q) use ($term) {
            $q->where('title', 'like', "%{$term}%")
              ->orWhere('content', 'like', "%{$term}%")
              ->orWhere('excerpt', 'like', "%{$term}%");
        });
    }

    public function scopeForFeature(Builder $query, string $feature): Builder
    {
        return $query->where('related_feature', $feature);
    }

    /**
     * Brand-aware accessors for the user-facing article body.
     *
     * Help articles are seeded with the literal product name ("MailTrixy")
     * baked in (~20 articles across 7 categories). On a reseller install
     * the customer's actual brand name lives in `SystemSetting('site_name')`
     * — so we replace at read time. We also honour an explicit `{brand}`
     * placeholder so newly-authored articles can be written brand-agnostic
     * from day one without hunting for the right product name to type.
     *
     * Doing this at READ time (vs. one-shot replace at seed time) means
     * the customer can rename the platform later and existing help content
     * updates instantly — no re-seed, no migration.
     */
    protected function rewriteBrand(?string $value): ?string
    {
        if ($value === null || $value === '') {
            return $value;
        }
        $brand = \App\Helpers\BrandingHelper::name();
        // Replace the explicit placeholder first, then the literal — order
        // matters if future content uses both forms in one article.
        return str_replace(['{brand}', 'MailTrixy'], $brand, $value);
    }

    public function getContentAttribute(?string $value): ?string
    {
        return $this->rewriteBrand($value);
    }

    public function getExcerptAttribute(?string $value): ?string
    {
        return $this->rewriteBrand($value);
    }

    public function getTitleAttribute(?string $value): ?string
    {
        return $this->rewriteBrand($value);
    }
}
