<?php

namespace App\Models;

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

class PolicyDocument extends Model
{
    use HasFactory;

    protected $fillable = [
        'association_id',
        'title',
        'slug',
        'type',
        'content',
        'version',
        'is_active',
        'last_updated_by',
    ];

    protected $casts = [
        'is_active' => 'boolean',
    ];

    public static function boot()
    {
        parent::boot();
        static::saving(function ($model) {
            if (!$model->slug) {
                $model->slug = Str::slug($model->title);
            }
        });
    }

    /**
     * Get the association that owns the policy document.
     */
    public function association(): BelongsTo
    {
        return $this->belongsTo(Association::class);
    }

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

    /**
     * Scope a query to only include global policies.
     */
    public function scopeGlobal($query)
    {
        return $query->whereNull('association_id');
    }

    /**
     * Scope a query to only include policies for a specific association.
     */
    public function scopeForAssociation($query, $associationId)
    {
        return $query->where('association_id', $associationId);
    }
}
