<?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 Laravel\Passport\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use DB;
use Exception;

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

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $guarded = []; //It is the exact opposite of $fillable, sort of like telling the database to accept everything, except the fields you specify inside the $guarded array.

    // protected $fillable = [
    //     'user_name',
    //     'email',
    //     'password',
    //     'role',
    //     'status',
    //     'created_by'
    // ];

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

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

    public static function createUser($user,$role,$register = 0)
    {
        if($register == 1)
        {
            $created_by = null;               
            $register_page = ($role=='DRIVER')?1:0;
        }
        else
        {
            $created_by = Auth::user()->id;
            $register_page = 0; 
        }
        //$password = ($role=='DRIVER')?null:Hash::make($user->password);
        $password = Hash::make($user->password);
        $is_approved = ($role == "SALES_PERSON")?1:0;

        $phone = Utility::getValidPhone($user->country_code_id,$user->phone);
        
        $newUser = User::create([            
            "user_name" => trim($user->first_name)." ".trim($user->last_name),
            "email" => trim($user->email),                
            "phone" => $phone,                
            "country_code_id" => trim($user->country_code_id),                
            "password" => $password,
            "role" => $role,
            "is_approved" => $is_approved,
            "register_page" => $register_page,
            "created_by" => $created_by         
        ]);        
        $newUser->assignRole($role);
        return $newUser->id;
    }
    
    public static function updateOrCreateUser($user,$role,$register =0)
    {
        if($register == 1)
        {
            $created_by = null;            
            $register_page = ($role=='DRIVER')?1:0;            
        }
        else
        {
            $created_by = Auth::user()->id;
            $register_page = 0;  
        }
        // $password = ($role=='DRIVER')?null:Hash::make($user->password);
        $is_approved = ($role == "SALES_PERSON")?1:0;
        $phone = Utility::getValidPhone($user->country_code_id,$user->phone);
        $matchThese = ['email'=>$user->email,'phone'=>$phone,'country_code_id'=>$user->country_code_id];
        $newUser = User::updateOrCreate($matchThese,[
                            'user_name'=> trim($user->first_name)." ".trim($user->last_name), 
                            'role'=>$role,
                            'is_approved' => $is_approved,
                            // 'phone'=>$user->phone,
                            'created_by'=>$created_by,
                            'register_page'=>$register_page                       
                        ]);
        $newUser->assignRole($role);
        return $newUser->id;
    }

    public static function updateUser($user,$role)
    {
        $phone = Utility::getValidPhone($user->country_code_id,$user->phone);

        $updateUser = User::find($user->user_id);
        $updateUser->email = $user->email;
        $updateUser->phone = $phone;
        $updateUser->country_code_id = $user->country_code_id;
        $updateUser->user_name = trim($user->first_name)." ".trim($user->last_name);
        $updateUser->role = $role;
        $updateUser->save();
        
        $updateUser->assignRole($role);
        return $updateUser->id;
    }

    public static function updateUserPhoneInfo($user,$role)
    {
        $phone = Utility::getValidPhone($user->country_code_id,$user->phone);
        $updateUser = User::find($phone);
        $updateUser->email = $user->email;
        $updateUser->phone = $phone;
        $updateUser->user_name = trim($user->first_name)." ".trim($user->last_name);
        $updateUser->role = $role;
        $updateUser->save();
        
        $updateUser->assignRole($role);
        return $updateUser->id;
    }
    
    public static function getMerchant($user_id)
    {
        $merchant = Merchant::where('user_id',$user_id)->first();
        return $merchant;
    }

    public static function checkExistPhone($phone)
    {
        $is_exist = User::where('phone', $phone)->exists();
        return $is_exist;
    }
    public function address()
    {
        return $this->hasOne('App\Models\AddressBook','user_id','id');
    }
    public function customer()
    {
        return $this->hasOne('App\Models\Customer','user_id','id');
    }
    public function merchant()
    {
        return $this->hasOne('App\Models\Merchant','user_id','id');
    }
    public function salesPerson()
    {
        return $this->hasOne('App\Models\SalesPerson','user_id','id');
    }
    public function scopeIsNotDeleted($query) 
    {
        return $query->where('is_deleted','!=',1);
    }
    public static function registerDevices($request,$user_id = 0)
    {
        $device_type = request()->header('device-type');
// return $device_type;
        if ($device_type == 'iOS') { /* iphone */
            $type = 1;
        } elseif ($device_type == 'Android') { /* android */
            $type = 2;
        } elseif ($device_type == 'Desktop') { /* other */
            $type = 3;
        }
        $device_data = array();      
        $device_data['device_id'] = request()->header('device-id');
        $device_data['device_type'] = $type;
        $device_data['device_token'] = request()->header('device-token');
        $device_data['device_ip'] = request()->header('device-ip');
        $device_data['app_version'] = request()->header('app-version');
        $device_data['build_no'] = request()->header('build-no');
        $device_data['device_brand'] = request()->header('device-brand');
        $device_data['device_model'] = request()->header('device-model');
        $device_data['device_os'] = request()->header('device-os');
        $device_data['device_ram'] = request()->header('device-ram');
        $device_data['device_processor'] = request()->header('device-processor');
        $device_data['device_location'] = request()->header('device-location');
        $device_data['device_latitude'] = request()->header('device-latitude');
        $device_data['device_longitude'] = request()->header('device-longitude');
        $device_data['device_url'] = __FUNCTION__; 
        $device_data['created_at'] = date('Y-m-d H:i:s');
        $device_data['updated_at'] = date('Y-m-d H:i:s'); 
        $device_data['status'] = '1';  

        // if (!empty($request->user_id) && $usr) { 
        //     $device_data['user_id'] = $request->user_id;                 
        // } 
        $device_data['user_id'] = (!empty($request->user_id))?$request->user_id:$user_id;
            //check device exist
            $device_id = DB::table('user_devices')->where('device_id', '=', $device_data['device_id'])->get();

            if (count($device_id) > 0) {

                // $dataexist = DB::table('user_devices')->where('device_id', '=', $device_data['device_id'])->where('user_id', '==', '0')->get();

                DB::table('user_devices')
                    ->where('device_id', $request->device_id)
                    ->update($device_data);

                // if (count($dataexist) >= 0) {
                //     $userData = DB::table('users')->where('id', '=', $request->user_id)->get();
                //     //notification
                //     $myVar = new AlertController();
                //     $alertSetting = $myVar->createUserAlert($userData);
                // }
            } else {
                $device_id = DB::table('user_devices')->insertGetId($device_data);
            }

            $responseData = array('success' => '1', 'data' => array(), 'message' => "Device is registered.");
       
        $deviceResponse = json_encode($responseData);

        return $deviceResponse;
    }

    public static function updateRegisterPage($user_id,$register_page)
    {
        DB::table('users')
        ->where('id', $user_id)
        ->update([
            "register_page" => $register_page
        ]);
        $responseData = array('success' => '1', 'data' => array(), 'message' => "updated register page.");
        $userResponse = json_encode($responseData);
        return $userResponse;
    }
    public function approveStatus()
    {
        return $this->hasOne('App\Models\ApproveStatus','approve_status_value','is_approved');
    }
   
}
