<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Blog extends Model
{
    use HasFactory;

    protected $fillable = [
        'h1_en',
        'h1_ar',
        'title_en',
        'title_ar',
        'slug',
        'category_en',
        'category_ar',
        'tags_en',
        'tags_ar',
        'meta_title_en',
        'meta_title_ar',
        'meta_description_en',
        'meta_description_ar',
        'excerpt_en',
        'excerpt_ar',
        'content_en',
        'content_ar',
        'image',
        'is_published',
        'published_at',
    ];

    protected $casts = [
        'is_published' => 'boolean',
        'published_at' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

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

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

    public function getRouteKeyName(): string
    {
        return 'slug';
    }

    public function getH1Attribute(): ?string
    {
        return app()->getLocale() === 'ar'
            ? ($this->h1_ar ?: $this->h1_en)
            : ($this->h1_en ?: $this->h1_ar);
    }

    public function getTitleAttribute(): string
    {
        return app()->getLocale() === 'ar'
            ? ($this->title_ar ?: $this->title_en)
            : ($this->title_en ?: $this->title_ar);
    }

    public function getCategoryAttribute(): ?string
    {
        return app()->getLocale() === 'ar'
            ? ($this->category_ar ?: $this->category_en)
            : ($this->category_en ?: $this->category_ar);
    }

    public function getExcerptAttribute(): ?string
    {
        return app()->getLocale() === 'ar'
            ? ($this->excerpt_ar ?: $this->excerpt_en)
            : ($this->excerpt_en ?: $this->excerpt_ar);
    }

    public function getContentAttribute(): string
    {
        return app()->getLocale() === 'ar'
            ? ($this->content_ar ?: $this->content_en ?: '')
            : ($this->content_en ?: $this->content_ar ?: '');
    }

    public function getMetaTitleAttribute(): ?string
    {
        return app()->getLocale() === 'ar'
            ? ($this->meta_title_ar ?: $this->meta_title_en)
            : ($this->meta_title_en ?: $this->meta_title_ar);
    }

    public function getMetaDescriptionAttribute(): ?string
    {
        return app()->getLocale() === 'ar'
            ? ($this->meta_description_ar ?: $this->meta_description_en)
            : ($this->meta_description_en ?: $this->meta_description_ar);
    }

    public function getTagsAttribute(): array
    {
        $value = app()->getLocale() === 'ar'
            ? ($this->tags_ar ?: $this->tags_en)
            : ($this->tags_en ?: $this->tags_ar);

        return $this->parseTags($value);
    }

    public function getTagsEnListAttribute(): array
    {
        return $this->parseTags($this->tags_en);
    }

    public function getTagsArListAttribute(): array
    {
        return $this->parseTags($this->tags_ar);
    }

    public function getImageUrlAttribute(): ?string
    {
        return $this->image ? asset('storage/' . $this->image) : null;
    }

    public function getStatusAttribute(): string
    {
        return $this->is_published ? 'Published' : 'Draft';
    }

    public static function uniqueSlug(string $title, ?int $ignoreId = null): string
    {
        $base = Str::slug($title);

        if ($base === '') {
            $base = 'blog';
        }

        $slug = $base;
        $counter = 2;

        while (
            static::query()
                ->when($ignoreId, fn (Builder $query) => $query->where('id', '!=', $ignoreId))
                ->where('slug', $slug)
                ->exists()
        ) {
            $slug = $base . '-' . $counter;
            $counter++;
        }

        return $slug;
    }

    protected function parseTags(null|string|array $value): array
    {
        if (is_array($value)) {
            return array_values(array_filter(array_map('trim', $value)));
        }

        if (!$value) {
            return [];
        }

        return array_values(array_filter(array_map('trim', explode(',', $value))));
    }
}