<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
use Spatie\Permission\Models\Role;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use App\Models\Settings\Dr;
use App\Models\Settings\Service;
use App\Models\Settings\Dd;
use App\Models\Settings\Establishment;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, HasRoles, SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'email',
        'last_name',
        'first_name',
        'password',
        'role_id',
        'service_id',
        'establishment_id',
        'dd_id',
        'dr_id',
        'phone',
        'picture',
        'choice',
        'active',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'password'          => 'hashed',
    ];
    

     /**
     * Get the role associated with this employee.
     */
    public function role(): BelongsTo
    {
        // return $this->belongsTo(Role::class);
        return $this->belongsTo(Role::class, 'role_id', 'id');
    }


    /**
     * Get the Dr associated with this employee.
     */
    public function dr(): BelongsTo
    {
        return $this->belongsTo(Dr::class);
    }

    /**
     * Get the service associated with this employee.
     */
    public function service(): BelongsTo
    {
        return $this->belongsTo(Service::class);
    }

    /**
     * Get the dd associated with this employee.
     */
    public function dd(): BelongsTo
    {
        return $this->belongsTo(Dd::class);
    }


    /**
     * Get the establishment associated with this employee.
     */
    public function establishment(): BelongsTo
    {
        return $this->belongsTo(Establishment::class);
    }


    // Get permissions
    public function getRolePermissions($roleId){

        // Get role instance
        $role =  Role::find($roleId);

        // Get all permission at role
        $permissionsRole = $role->permissions;

        // Return data
        return $permissionsRole;
    }
    

    // Treat permission array
    public function rolePermissionsArray($permissions) {

        // Default 
        $permissionArray = [];

        foreach ($permissions as $permission) {

            $permissionArray[] = $permission->id;            
        }

        // Return value
        return $permissionArray;
    }



    /** Get data
     * @param mixed $status
     * @param string $searchValue
     * @param array $columnsFilter
     * 
     * @return array
     */
    public function getModelData(mixed $status, string $searchValue, array $columnsFilter) : array
    {
        $query = User::with('role')
        ->when($searchValue, function ($query) use ($searchValue, $columnsFilter) {
            $query->where(function ($subQuery) use ($columnsFilter, $searchValue) {
                $subQuery->where($columnsFilter[0], 'LIKE', '%' . $searchValue . '%');
                for ($i = 1; $i < count($columnsFilter); $i++) {
                    $subQuery->orWhere($columnsFilter[$i], 'LIKE', '%' . $searchValue . '%');
                }
            });
        })
            ->when($status, function ($query) use ($status) {
                $query->where('status', $status);
            })
            ->where('deleted_at', null)
            ->where('active', 1);

        $data = $query->offset($_REQUEST['start'])
            ->limit($_REQUEST['length'])
            ->orderBy('id', 'desc')
            ->get()
            ->toArray();

        // Construct the response array for DataTables
        // Return data
        return array(
            "recordsTotal" => $query->count(),
            "recordsFiltered" => $query->count(),
            "data" => $data
        );

    }


}
