<?php

/**
 * Created by Reliese Model.
 */

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * Class Permission
 * 
 * @property int $id
 * @property string $name
 * @property string $slug
 * @property string|null $description
 * @property string|null $group
 * @property int $level
 * @property string|null $path
 * @property string $type
 * @property string|null $resource
 * @property int $order
 * @property bool $is_active
 * @property int|null $parent_id
 * @property Carbon|null $created_at
 * @property Carbon|null $updated_at
 * @property string|null $deleted_at
 * 
 * @property Permission|null $permission
 * @property Collection|Role[] $roles
 * @property Collection|Permission[] $permissions
 * @property Collection|User[] $users
 *
 * @package App\Models
 */
class Permission extends Model
{
	use SoftDeletes;
	protected $table = 'permissions';

	protected $casts = [
		'level' => 'int',
		'order' => 'int',
		'is_active' => 'bool',
		'parent_id' => 'int'
	];

	protected $fillable = [
		'name',
		'slug',
		'description',
		'group',
		'level',
		'path',
		'type',
		'resource',
		'order',
		'is_active',
		'parent_id'
	];

	public function permission()
	{
		return $this->belongsTo(Permission::class, 'parent_id');
	}

	public function roles()
	{
		return $this->belongsToMany(Role::class)
			->withPivot('id')
			->withTimestamps();
	}

	public function permissions()
	{
		return $this->hasMany(Permission::class, 'parent_id');
	}

	public function children()
	{
		return $this->hasMany(Permission::class, 'parent_id');
	}

	public function users()
	{
		return $this->belongsToMany(User::class, 'user_permission')
			->withPivot('id', 'granted', 'source', 'expires_at', 'deleted_at')
			->withTimestamps();
	}

	/**
	 * تحديث مسار الصلاحية
	 */
	public function updatePath()
	{
		if ($this->parent_id) {
			$parent = self::find($this->parent_id);
			if ($parent) {
				$this->path = $parent->path ? $parent->path . '.' . $this->id : $this->id;
			} else {
				$this->path = (string) $this->id;
			}
		} else {
			$this->path = (string) $this->id;
		}
		$this->save();

		// تحديث مسارات الأبناء
		foreach ($this->children as $child) {
			$child->updatePath();
		}
	}

	/**
	 * تحديث مستوى الصلاحية
	 */
	public function updateLevel()
	{
		if ($this->parent_id) {
			$parent = self::find($this->parent_id);
			if ($parent) {
				$this->level = $parent->level + 1;
			} else {
				$this->level = 0;
			}
		} else {
			$this->level = 0;
		}
		$this->save();

		// تحديث مستويات الأبناء
		foreach ($this->children as $child) {
			$child->updateLevel();
		}
	}
}
