<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage; // Import Storage facade
use Spatie\Permission\Traits\HasRoles;
use Laravel\Sanctum\HasApiTokens;

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

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

    /** 
     * The attributes that are mass assignable.
     *
     * @var array 
     */
    protected $fillable = [
        'title',               
        'profile_picture',               
        'first_name',         
        'middle_name',       
        'last_name',         
        'father_name',        
        'mobile',         
        'email',              
        'address',            
        'state_id',              
        'country_id',              
        'city',               
        'years_of_exp',      
        'company_name',      
        'company_pan_number',      
        'company_gst',        
        'education_qualification', 
        'my_referral_id',     
        'referral_id',      
        'password',
        'nominee_name',                
        'nominee_relationship',       
        'nominee_contact',           
        'bank_name',             
        'account_number',          
        'ifsc_code',                  
        'account_type', 
        'pan', 
        'company_gst_certificate', 
        'company_pan', 
        'aadhar_number', 
        'pan_card_doc', 
        'aadhar_card_doc', 
        'status', 
        'first_login', 
    ];

    /**
     * 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 function parent()
    {
        return $this->belongsTo(Admin::class, 'my_referral_id', 'referral_id');
    }
	
	public function children()
    {
        return $this->hasMany(Admin::class, 'referral_id', 'my_referral_id');
    }
	public static function getReferralHierarchy($userId)
    {
        $user = Admin::find($userId);
        return self::getChildrenRecursively($user);
    }
	 private static function getChildrenRecursively(Admin $user)
    {
        $children = $user->children;
        $result = collect([$user]);

        foreach ($children as $child) {
            $result = $result->merge(self::getChildrenRecursively($child));
        }

        return $result;
    }
	public function country()
    {
        return $this->belongsTo(Country::class, 'country_id', 'country_id');
    }

    public function state()
    {
        return $this->belongsTo(State::class, 'state_id', 'state_id');
    }

    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;
    }
	
	/**
     * Append the profile picture URL to the array output.
     *
     * @return array
     */
    public function toArray()
    {
        $array = parent::toArray(); // Get the original user data

        // Add role name instead of the full roles array
        $array['role_name'] = $this->getRoleNames()->first(); // Get the first role name (string)

        // Append the full URL for the profile picture
        if ($this->profile_picture) {
            $array['profile_picture_url'] =asset($this->profile_picture); // Generate the full URL
        }
		if ($this->aadhar_card_doc) {
            $array['aadhar_card_doc_url'] =asset($this->aadhar_card_doc); // Generate the full URL
        }
		if ($this->pan_card_doc) {
            $array['pan_card_doc_url'] =asset($this->pan_card_doc); // Generate the full URL
        } 
		if ($this->company_gst_certificate) {
            $array['company_gst_certificate_doc_url'] =asset($this->company_gst_certificate); // Generate the full URL
        }
		if ($this->company_pan) {
            $array['company_pan_doc_url'] =asset($this->company_pan); // Generate the full URL
        }

        return $array;
    }
}
