<?php

namespace Sartoric\ModularCms\Policies;

use Sartoric\ModularCms\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class UserPolicy
{
    use HandlesAuthorization;

    /**
     * Create a new policy instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    public function before(User $user)
    {
        // Superadmin can manage everything
        if ($user->isSuperAdmin()) {
            return true;
        }
    }

    public function update(User $user, User $user_model)
    {
        if (!$user->hasPermission('user-update')
            // No one except superadmin can edit superadmin users
            || ($user_model->isSuperAdmin() && !$user->hasPermission('user-sa-update'))) {
            return false;
        }
        return true;
    }

    public function create(User $user)
    {
        if (!$user->hasPermission('user-create')
            // No one except superadmin can create superadmin users
//            || ($user_model->isSuperAdmin() && !$user->hasPermission('user-sa-create'))
        ) {
            return false;
        }
        return true;
    }

    public function delete(User $user, User $user_model)
    {
        if (!$user->hasPermission('user-delete') ||
            // No one can delete superadmin
            $user_model->isSuperAdmin()) {
            return false;
        }
        return true;
    }

    public function editProfile(User $user, User $user_model)
    {
        if ($user->hasPermission('user-profile-edit')) {
            return true;
        }
        return false;
    }

    public function viewProfile(User $user, User $user_model)
    {
        if ($user->hasPermission('user-profile-view')) {
            return true;
        }
        return false;
    }

    public function selfUpdatePassword(User $user, User $user_model)
    {
        if (!$user->hasPermission('user-pwd-update') || ($user->id !== $user_model->id)) {
            return false;
        }
        return true;
    }
}
