<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Str;

class Tier extends Model
{
    use HasFactory;
    
    protected $fillable = [
        'title',
        'slug',
        'content',
        'excerpt',
        'status',
        'sort_order',
        'is_featured',
        'published_at',
        'meta_title',
        'meta_description',
        'meta_keywords',
        'meta_robots',
        'canonical_url',
        'og_data',
        'twitter_data',
        'schema_markup',
        'featured_image',
        'featured_image_alt',
        'featured_image_caption',
        'featured_image_meta',
        'gallery_images',
        'banner_image',
        'banner_image_alt',
        'author_id',
        'updated_by',
    ];

    protected $casts = [
        'published_at' => 'datetime',
        'is_featured' => 'boolean',
        'og_data' => 'array',
        'twitter_data' => 'array',
        'featured_image_meta' => 'array',
        'gallery_images' => 'array',
    ];
    
    /**
     * Boot the model.
     */
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($tier) {
            // Generate slug if not provided
            if (empty($tier->slug)) {
                $tier->slug = Str::slug($tier->title);
            }
        });

        static::updating(function ($tier) {
            // Update slug if title changed and slug was not manually set
            if ($tier->isDirty('title') && !$tier->isDirty('slug')) {
                $tier->slug = Str::slug($tier->title);
            }
        });
    }

    /**
     * Get the author of the tier.
     */
    public function author(): BelongsTo
    {
        return $this->belongsTo(User::class, 'author_id');
    }

    /**
     * Get the user who last updated the tier.
     */
    public function updatedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    /**
     * Get the URL for the tier.
     */
    public function getUrlAttribute(): string
    {
        return route('pages.tiers', $this->slug);
    }
}
