<?php

/**
 * Created by Reliese Model.
 */

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
use Spatie\Feed\Feedable;
use Spatie\Feed\FeedItem;

/**
 * Class Post
 *
 * @property int $id
 * @property int|null $serp_url_id
 * @property string|null $title
 * @property string|null $slug
 * @property string|null $main_keyword
 * @property string|null $keywords
 * @property string|null $bites
 * @property int|null $author_id
 * @property string|null $featured_image
 * @property string|null $body
 * @property int $views_count
 * @property string $status
 * @property Carbon|null $published_at
 * @property Carbon|null $created_at
 * @property Carbon|null $updated_at
 * @property SerpUrl|null $serp_url
 * @property Author|null $author
 * @property Collection|PostCategory[] $post_categories
 */
class Post extends Model implements Feedable
{
    protected $table = 'posts';

    protected $casts = [
        'serp_url_id' => 'int',
        'author_id' => 'int',
        'views_count' => 'int',
        'published_at' => 'datetime',
        'keywords' => 'array',
        'metadata' => 'object',
    ];

    protected $fillable = [
        'serp_url_id',
        'title',
        'slug',
        'main_keyword',
        'keywords',
        'bites',
        'author_id',
        'featured_image',
        'body',
        'views_count',
        'status',
        'published_at',
        'metadata',
        'society_impact',
        'society_impact_level',
    ];

    protected function featuredImage(): Attribute
    {
        return Attribute::make(
            get: function ($value = null) {
                if (! is_empty($value)) {
                    return Storage::disk('r2')->url($value);
                }

                return null;
            }
        );
    }

    protected function getFeaturedThumbImageAttribute()
    {
        $value = $this->featured_image;

        //dd($value);

        if (! is_empty($value)) {
            // Extract the file extension
            $extension = pathinfo($value, PATHINFO_EXTENSION);

            // Construct the thumbnail filename by appending '_thumb' before the extension
            $thumbnail = str_replace(".{$extension}", "_thumb.{$extension}", $value);

            return $thumbnail;

            // Return the full URL to the thumbnail image
            //return Storage::disk('r2')->url($thumbnail);
        }

        return null;
    }

    public function serp_url()
    {
        return $this->belongsTo(SerpUrl::class);
    }

    public function author()
    {
        return $this->belongsTo(Author::class);
    }

    public function post_categories()
    {
        return $this->hasMany(PostCategory::class);
    }

    public function post_entities()
    {
        return $this->hasMany(PostEntity::class);
    }

    public function category()
    {
        return $this->hasOneThrough(
            Category::class,      // The target model
            PostCategory::class, // The through model
            'post_id',           // The foreign key on the through model
            'id',                // The local key on the parent model (Post)
            'id',                // The local key on the through model (PostCategory)
            'category_id'        // The foreign key on the target model (Category)
        );
    }

    public function entities()
    {
        return $this->hasManyThrough(
            Entity::class,      // The target model
            PostEntity::class, // The through model
            'post_id',           // The foreign key on the through model
            'id',                // The local key on the parent model (Post)
            'id',                // The local key on the through model (PostEntity)
            'entity_id'        // The foreign key on the target model (Entity)
        );
    }

    public function toFeedItem(): FeedItem
    {
        return FeedItem::create([
            'id' => $this->id,
            'title' => $this->title,
            'summary' => $this->bites,
            'updated' => $this->updated_at,
            'link' => route('front.post', ['slug' => $this->slug, 'category_slug' => $this->category->slug]),
            'authorName' => 'FutureWalker',
        ]);
    }

    public static function getFeedItems()
    {
        return self::with('category')->where('status', 'publish')->latest('published_at')->take(20)->get();
    }
}
