<?php

namespace App\Models;

use App\Traits\Auditable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Route extends Model
{
    use HasFactory, Auditable;

    protected $fillable = [
        'path',
        'description',
        'is_public',
    ];

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

    /**
     * The roles that belong to the route.
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class, 'role_route');
    }

    /**
     * Check if the given role has access to this route
     *
     * @param Role|int $role
     * @return bool
     */
    public function hasRole($role)
    {
        if ($this->is_public) {
            return true;
        }

        if (is_numeric($role)) {
            return $this->roles()->where('roles.id', $role)->exists();
        }

        return $this->roles()->where('roles.id', $role->id)->exists();
    }

    /**
     * Check if the route matches the given path
     *
     * @param string $path
     * @return bool
     */
    public static function matchPath($path)
    {
        $routes = self::all();
        
        foreach ($routes as $route) {
            $pattern = str_replace(['*', '/'], ['.*', '\/'], $route->path);
            if (preg_match('/^' . $pattern . '$/', $path)) {
                return $route;
            }
        }

        return null;
    }
}
