<?php

namespace App\Models;
use App\Models\User_balance;
use App\Models\Account_io;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use DB;

class Users extends Authenticatable
{
    use HasApiTokens;
    use HasFactory;

    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'account_type',
            'account_setup',
            'role',
            'client_type',
            'username',
            'fname',
            'lname',
            'email',
            'password',
            'currency',
            'country',
            'act_session',
            'act_code',
            'ref_by',
            'email_verify',
            'status'
    ];
    
    protected $table = 'users';

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

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

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'profile_photo_url',
    ];
    
    public function account()
    {
    return Account_io::where('user', $this->id)->where('id', $this->account_id)->first();
    }
    
    public function wallets()
    {
        return $this->hasMany(Account_io::class , 'user', 'id')->get();
    }
    public function permissions()
    {
        return $this->hasOne(User_permission::class , 'user', 'id')->first();
    }
    
    public static function get_all_leads($user){
        $leads = '';
        if($user->role == 'admin'){
          $leads = self::where('client_type' , 'leads')->where('role' , 'user')->OrderBy('created_at', 'desc')->get();  
        }elseif($user->role == 'manager'){
          $leads = self::where('client_type' , 'leads')->where('role' , 'user')->where('manager_id',  $user->id)->OrderBy('created_at', 'desc')->get();  
        }
        return $leads;
    }
    
    public static function get_all_user($request , $user , $type='active'){
        $leads = '';
         if(filter_var($request->get('lx'), FILTER_VALIDATE_INT) !== false){
            $limit = $request->get('lx');
        }else{
            $limit = 20;
        }
        dd('yes');
        if($user->role == 'admin'){
         if($type == 'on-hold'){
              $leads = self::where('role' , 'user')->where('status' , 'on hold')->OrderBy('created_at', 'desc')->paginate($limit);  
            }else{
              $leads = self::where('role' , 'user')->where('status' , $type)->OrderBy('created_at', 'desc')->paginate($limit);  
            }
        }elseif($user->role == 'manager'){
          $leads = self::where('role' , 'user')->where('status' , $type)->where('manager_id',  $user->id)->OrderBy('created_at', 'desc')->paginate($limit);  
        }
        return $leads;
    }
    
    public static function get_all_count(){
    
    $total_all = DB::table('users')->where('role' , 'user')->count();  
    return $total_all;
    }
    
    public static function get_active_count(){
        $total_pending = DB::table('users')->where('role' , 'user')->where('status','active')->count(); 
        return $total_pending;
    }
    
    public static function get_inactive_count(){
        $total_pending = DB::table('users')->where('role' , 'user')->where('status','inactive')->count();
        return $total_pending;
    }
    
    public static function get_disabled_count(){
        $total_pending = DB::table('users')->where('role' , 'user')->where('status','disabled')->count();
        return $total_pending;
    }
    
    
    public static function get_all_clients_by_search($request , $user){
        $leads = '';
         if(filter_var($request->get('lx'), FILTER_VALIDATE_INT) !== false){
            $limit = $request->get('lx');
        }else{
            $limit = 10;
        }
        
        if($user->role == 'admin'){
           
          
         
          if($request->dvalue != "" || $request->dvalue != NULL ){
             
             if($request->dname = 'email'){
                 $leads = self::where('client_type' , 'clients')->where('role' , 'user')->where('email','LIKE','%'.$request->dvalue.'%')->OrderBy('created_at', 'desc')->paginate($limit); 
                 return $leads;
             } 
             elseif($request->dname = 'country'){
                 $leads = self::where('client_type' , 'clients')->where('role' , 'user')->where('country',$request->dvalue)->OrderBy('created_at', 'desc')->paginate($limit); 
                 return $leads;
             } 
          }
          
          $leads = self::where('client_type' , 'clients')->where('role' , 'user')->OrderBy('created_at', 'desc')->paginate($limit); 
        }
         elseif($user->role == 'manager'){
          $leads = self::where('client_type' , 'clients')->where('role' , 'user')->where('manager_id',  $user->id)->OrderBy('created_at', 'desc')->paginate($limit);  
        }
        return $leads;
    }
    
    public function user_curr(){
        $curr = $this->currency;
        if(empty($curr)){
          $curr = system_settings('currency');  
        }
        
        return $curr;
    }
    
    public static function get_all_clientx($user){
        $leads = '';
        if($user->role == 'admin'){
          $leads = self::where('client_type' , 'clients')->where('role' , 'user')->OrderBy('created_at', 'desc')->get();  
        }elseif($user->role == 'manager'){
          $leads = self::where('client_type' , 'clients')->where('role' , 'user')->where('manager_id',  $user->id)->OrderBy('created_at', 'desc')->get();  
        }
        return $leads;
    }
    
    public function manager(){
        return $this->belongsTo(Users::class , 'manager_id', 'id')->where('id' , $this->manager_id)->first();
    }
    
    public function get_full_name(){
       return $this->fname ." ". $this->lname;
    }
    
    public function exportClients($user){
      
        $users = Users::get_all_clientx($user);
        
        $columns = array('Id', 'Fullname', 'Email', 'Phone', 'Country', 'Brand', 'Registered', 'Manager', 'Status', 'Balance', 'Last Online');
        $callback = function() use($users, $columns) {
            $file = fopen('php://output', 'w');
            fputcsv($file, $columns);

            foreach ($users as $task) {
                $row['Id']  = $task->username;
                $row['Fullname']    = $task->get_full_name();
                $row['Email']  = $task->email;
                $row['Phone']  = $task->phone;
                $row['Country']  = $task->country;
                $row['Brand']  = $task->brand;
                $row['Registered']  = $task->created_at;
                if(!empty($task->manager())){
                $row['Manager']    = $task->manager()->get_full_name();
            }else{
               $row['Manager']    = ''; 
            }
                $row['Status']  = $task->status;
                $row['Balance']  = number_format($task->account()->real_account,2,'.',',');
                $row['Last Online']  = $task->last_login;
                
                
                

                fputcsv($file, array($row['Id'], $row['Fullname'], $row['Email'], $row['Phone'], $row['Country'], $row['Brand'], $row['Registered'], $row['Manager'], $row['Status'], $row['Balance'], $row['Last Online']));
            }

            fclose($file);
        };
        return $callback;
    
    }
    
    public function refer(){
        return $this->belongsTo(User::class , 'ref_by', 'id')->where('id' , $this->ref_by)->first();
    }
}
