<?php

namespace App\Livewire;

use App\Models\Blog;
use Livewire\Component;
use Livewire\Attributes\Computed;
use App\Traits\HasBreadcrumb;
use Illuminate\Support\Str;

class BlogDetail extends Component
{
    use HasBreadcrumb;

    public Blog $blog;
    public $metaDescription;
    public $metaKeywords;
    public $ogTitle;
    public $ogDescription;
    public $ogImage;
    public $ogType = 'article';
    public $canonical;

    public function mount(Blog $blog)
    {
        // Check if blog is published
        if (!$blog->is_published || $blog->published_at > now()) {
            abort(404);
        }

        // Increment views
        $blog->incrementViews();
        
        $this->breadcrumbPage = 'blog';
        
        // Set SEO meta data
        $this->metaDescription = $blog->summary ?? Str::limit(strip_tags($blog->description), 155);
        $this->metaKeywords = $blog->tags ? implode(', ', $blog->tags) : 'blog, technology, ' . $blog->category;
        $this->ogTitle = $blog->title;
        $this->ogDescription = $this->metaDescription;
        $this->ogImage = $blog->image ? \Storage::url($blog->image) : asset('assets/img/og-default.jpg');
        $this->canonical = route('blogs.show', $blog->slug);
    }

    #[Computed]
    public function relatedBlogs()
    {
        return Blog::published()
            ->where('id', '!=', $this->blog->id)
            ->where(function ($query) {
                if ($this->blog->category) {
                    $query->where('category', $this->blog->category);
                }
            })
            ->ordered()
            ->limit(3)
            ->get();
    }

    public function getTitle(): string
    {
        return $this->blog->title . ' - Blog - Niifam Technology Consulting';
    }

    public function render()
    {
        return view('livewire.blog-detail')
            ->title($this->getTitle());
    }
}
