<?php

namespace App\Models;

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

class Role extends Model
{
    use HasFactory;

    protected $table = 'roles';

    protected $fillable = [
        'title',
    ];

    protected $dates = [
        'created_at',
        'updated_at',
    ];

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    /**
     * Define the many-to-many relationship with permissions.
     */
    public function permissions()
    {
        return $this->belongsToMany(Permission::class);
    }

    /**
     * Safely sync permissions to prevent invalid IDs from breaking FK constraints.
     */
    public function syncPermissions($permissionIds)
    {
        // Filter out any IDs that don't exist in the permissions table
        $validIds = Permission::whereIn('id', (array) $permissionIds)->pluck('id')->toArray();

        return $this->permissions()->sync($validIds);
    }

    public function role()
    {
        return $this->belongsTo(Role::class);
    }

    public function hasPermission($permission)
    {
        return $this->role && $this->role->permissions->contains('title', $permission);
    }

    public function users()
    {
        return $this->hasMany(User::class, 'role_id');
    }
}
