<?php

namespace App\Models;

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

class ContentPage extends Model
{
    use HasFactory;

    protected $primaryKey = 'page_id';

    protected $fillable = [
        'page_title',
        'page_slug',
        'page_content',
        'page_type',
        'is_published',
        'created_by'
    ];

    protected $attributes = [
        'is_published' => true, // Default to published
        'page_type' => 'general'
    ];

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

    /**
     * Get the user who created the page.
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by', 'user_id');
    }

    /**
     * Scope a query to only include published pages.
     */
    public function scopePublished($query)
    {
        return $query->where('is_published', true);
    }

    /**
     * Scope a query to only include pages of specific type.
     */
    public function scopeOfType($query, $type)
    {
        return $query->where('page_type', $type);
    }

    /**
     * Scope a query to order by sort order.
     */
    public function scopeOrdered($query)
    {
        return $query->orderBy('page_title');
    }

    /**
     * Check if page is published.
     */
    public function isPublished(): bool
    {
        return $this->is_published;
    }

    /**
     * Publish the page.
     */
    public function publish()
    {
        $this->update(['is_published' => true]);
    }

    /**
     * Unpublish the page.
     */
    public function unpublish()
    {
        $this->update(['is_published' => false]);
    }

    /**
     * Get page by slug.
     */
    public static function findBySlug($slug)
    {
        return static::published()->where('page_slug', $slug)->first();
    }
}
