<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
use DB;
class User extends Authenticatable
{
    use HasFactory, Notifiable, HasRoles;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'image',
        'status',
        'type',
        'phone',
        'emirates',
        'area',
        'building',
        'flat_no'
    ];

    /**
     * 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 getLists($type)
    {
        try {
            $query = new Self;

            if(isset($_GET['search'])){
                if($_GET['search']!=''){
                    $keyword = $_GET['search'];
                    $query = $query->where(function($q) use ($keyword){
                        $q->where(DB::raw('LOWER(name)'), 'like', '%'.strtolower($keyword). '%')
                        ->orWhere(DB::raw('phone'),'like','%'.strtolower($keyword). '%')
                        ->orWhere(DB::raw('email'),'like','%'.strtolower($keyword). '%');
                    });
                }
            }
            $data = $query->where('type',$type)->orderBy('id','DESC')->paginate(config('constant.paginate.num_per_page'));
            foreach ($data as $row) {
                $row->wallet_amount = UserWallet::getWalletbalance($row->id);
            }
            return $data;
        }catch (\Exception $e) {
            return ['status' => false, 'message' => $e->getMessage() . ' '. $e->getLine() . ' '. $e->getFile()];
        }
    }

    public function userWallet()
    {
        return $this->hasMany(\App\Models\UserWallet::class, 'user_id');
    }
}
