<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class CustomPage extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'title',
        'slug',
        'content',
        'meta_description',
        'meta_keywords',
        'active',
        'show_in_footer',
        'show_in_header',
        'order',
        'created_by',
        'updated_by'
    ];

    protected $casts = [
        'active' => 'boolean',
        'show_in_footer' => 'boolean',
        'show_in_header' => 'boolean',
        'order' => 'integer',
    ];

    /**
     * Boot the model.
     */
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($page) {
            if (empty($page->slug)) {
                $page->slug = Str::slug($page->title);
            }
            
            if (Auth::check()) {
                $page->created_by = Auth::id();
                $page->updated_by = Auth::id();
            }
        });

        static::updating(function ($page) {
            if (Auth::check()) {
                $page->updated_by = Auth::id();
            }
        });
    }

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

    /**
     * Get the updater of the page.
     */
    public function updater()
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

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

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

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