<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * DB-driven static/content page (About, Help, Legal, etc.)
 *
 * @property int    $id
 * @property string $slug
 * @property string $title
 * @property string $body           HTML or Markdown content
 * @property string $layout         'default' | 'legal' | 'help'
 * @property string|null $meta_title
 * @property string|null $meta_description
 * @property bool   $is_published
 * @property \Carbon\Carbon|null $published_at
 */
class Page extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'slug',
        'title',
        'body',
        'layout',
        'meta_title',
        'meta_description',
        'is_published',
        'published_at',
    ];

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

    // ── Scopes ───────────────────────────────────────────────────────────

    public function scopePublished($query)
    {
        return $query->where('is_published', true)
                     ->where(fn ($q) => $q->whereNull('published_at')->orWhere('published_at', '<=', now()));
    }

    // ── Accessors ────────────────────────────────────────────────────────

    public function getUrlAttribute(): string
    {
        return url('/pages/' . $this->slug);
    }

    public function getCanonicalUrlAttribute(): string
    {
        return $this->url;
    }
}
