<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Traits\HasRoles;
use Spatie\Permission\Models\Role;
use App\Models\UserHasCabang;

class Admin extends Authenticatable
{
    use Notifiable, HasRoles;
    use SoftDeletes;

    /**
     * Set the default guard for this model.
     *
     * @var string
     */
    protected $guard_name = 'admin';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'username', 'name', 'email', 'password', 'region_id', 'rayon_id', 'phone'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public static function getpermissionGroups()
    {
        $permission_groups = DB::table('permissions')
            ->select('group_name as name')
            ->groupBy('group_name')
            ->get();
        return $permission_groups;
    }

    public static function getpermissionsByGroupName($group_name)
    {
        $permissions = DB::table('permissions')
            ->select('name', 'id')
            ->where('group_name', $group_name)
            ->get();
        return $permissions;
    }

    public static function roleHasPermissions($role, $permissions)
    {
        $hasPermission = true;
        foreach ($permissions as $permission) {
            if (!$role->hasPermissionTo($permission->name)) {
                $hasPermission = false;
                return $hasPermission;
            }
        }
        return $hasPermission;
    }

    public function getCabangAndRegionHead()
    {
        // Fetch the UserHasCabang entry for this admin
        $userHasCabang = $this->hasOne(UserHasCabang::class, 'user_id')->with('cabang')->first();

        if ($userHasCabang && $userHasCabang->cabang) {
            $cabang = $userHasCabang->cabang;

            // Fetch the cabang head
            $cabangHead = $cabang->head;

            // Fetch the region and its head
            $region = $cabang->region;
            $regionHead = $region ? $region->head : null;

            return [
                'cabang_head' => $cabangHead,
                'region_head' => $regionHead,
            ];
        }

        return [
            'cabang_head' => null,
            'region_head' => null,
        ];
    }

    public function getMyCabangAndRegion()
    {
        // Fetch the UserHasCabang entry for this admin
        $userHasCabang = $this->hasOne(UserHasCabang::class, 'user_id')->with('cabang')->first();

        if ($userHasCabang && $userHasCabang->cabang) {
            $cabang = $userHasCabang->cabang;

            // Fetch the region
            $region = $cabang->region;

            return [
                'cabang' => $cabang ? $cabang->name : '-',
                'region' => $region ? $region->name : '-',
            ];
        }

        return [
            'cabang' => '-',
            'region' => '-',
        ];
    }

    public function getMyCabangAndRegionId()
    {
        // Fetch the UserHasCabang entry for this admin
        $userHasCabang = $this->hasOne(UserHasCabang::class, 'user_id')->with('cabang')->first();

        if ($userHasCabang && $userHasCabang->cabang) {
            $cabang = $userHasCabang->cabang;

            // Fetch the region
            $region = $cabang->region;

            return [
                'cabang' => $cabang ? $cabang->id : '-',
                'region' => $region ? $region->id : '-',
            ];
        }

        return [
            'cabang' => '-',
            'region' => '-',
        ];
    }

    public function cabang()
    {
        return $this->hasOne(UserHasCabang::class, 'user_id')->with('cabang');
    }

    public function region()
    {
        return $this->hasOne(UserHasCabang::class, 'user_id')->with('cabang.region');
    }

    public function getRayon()
    {
        return $this->belongsTo(Rayon::class, 'rayon_id');
    }

    public function getRegion()
    {
        return $this->belongsTo(Region::class, 'region_id');
    }

    public static function getUserByRoleName($roleName)
    {
        $role = Role::where('name', $roleName)->first();

        if ($role) {
            return $role->users()->with('cabang.cabang')->get();
        }

        return [];
    }

    public static function getUserByRoleNameAndCabang($roleName, $cabang_id)
    {
        $users = self::getUserByRoleName($roleName);

        return $users->filter(function ($user) use ($cabang_id) {
            return $user->cabang ? $user->cabang->id == $cabang_id : false;
        });
    }

    public static function getUserWhereRoleIsNot($roleName)
    {
        return self::whereDoesntHave('roles', function ($query) use ($roleName) {
            $query->where('name', $roleName);
        })->get();
    }
}
