<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Support\Facades\Auth;

class Permission extends Model
{
    use SoftDeletes;

    protected $fillable = ['name', 'route_name', 'parent_id', 'is_parent', 'created_by'];

    /**
     * @return BelongsTo
     */
    public function createdBy()
    {
        return $this->belongsTo('App\User', 'created_by')->withDefault();
    }

    /**
     * @return BelongsToMany
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class, 'role_permission', 'permission_id', 'role_id');
    }

    /**
     * @param $routeName
     * @return bool
     */
    public static function checkAccessAllow($routeName)
    {
        $allowRoutes = ["dashboard"];
        if (in_array($routeName, $allowRoutes)) {
            return true;
        }
        if (Auth::check()) {
            $role = Role::find(Auth::user()->role_id);

            // First check exact match
            $permission = Permission::where('route_name', $routeName)->first();

            // Match with master route name
            if (!$permission) {
                $parts = explode(".", $routeName);
                if (!$permission) {
                    $permission = Permission::where('route_name', $parts[0])->first();
                }

                if (!$permission) {
                    $urlParts   = explode("-", $routeName);
                    $permission = Permission::where('route_name', $urlParts[0])->first();
                }

                if (!$permission) {
                    $parentRoute = Permission::getDependantRoutes($parts[0]);
                    $permission  = Permission::where('route_name', $parentRoute)->first();
                }
            }

            if ($permission) {
                if ($permission->count() > 0) {
                    if ((!is_null($role) && $role->permissions->contains($permission)) || Auth::user()->role_id == 1) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * @param $route
     * @return mixed
     */
    public static function getDependantRoutes($route)
    {
        $dependant = ["role" => "user"];
        if (isset($dependant[$route])) {
            return $dependant[$route];
        } else {
            return $route;
        }
    }

    /**
     * Return permissions
     *
     * @return array
     */
    public static function getPermissions(){

        function buildTree(array $elements, $parentId = 0) {
            $branch = array();
            foreach ($elements as $element) {
                if ($element['parent_id'] == $parentId) {
                    $children = buildTree($elements, $element['id']);
                    if ($children) {
                        $element['children'] = $children;
                    }
                    $branch[] = $element;
                }
            }
            return $branch;
        }

        return buildTree(self::orderBy('priority', 'DESC')->get()->toArray());
    }
}
