<?php

namespace App\Models;


use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = [];

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

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


    public function getUserByUserId($user_id){
        return self::where(['id'=>$user_id])->first();
    }

    public function getUserByEmail($email){
        return self::where(['email'=>$email])->first();
    }

    public function addUser($inputData){
        // pr($inputData);exit;
        $result = false;
        $insertData['email'] = $inputData['email'];
        $insertData['password'] = customEncrypt($inputData['password']);
        $insertData['first_name'] = $inputData['first_name'];
        $insertData['last_name'] = $inputData['last_name'];
        if(!empty($inputData['street_no'])){
            $insertData['street_no'] = $inputData['street_no'];
        }

        if(!empty($inputData['street_name'])){
            $insertData['street_name'] = $inputData['street_name'];
        }

        if(!empty($inputData['city'])){
            $insertData['city'] = $inputData['city'];
        }

        if(!empty($inputData['state'])){
            $insertData['state'] = $inputData['state'];
        }

        if(!empty($inputData['ssn'])){
            $insertData['ssn'] = $inputData['ssn'];
        }

        if(!empty($inputData['birth_date'])){
            $insertData['birth_date'] = $inputData['birth_date'];
        }

        if(!empty($inputData['phone'])){
            $insertData['phone'] = $inputData['phone'];
        }

        if(!empty($inputData['zip_code'])){
            $insertData['zip_code'] = $inputData['zip_code'];
        }

        if(!empty($inputData['user_type'])){
            $insertData['user_type'] = $inputData['user_type'];
        }

        if(!empty($inputData['status'])){
            $insertData['status'] = $inputData['status'];
        }

        if(!empty($inputData['last_payment_date'])){
            $insertData['last_payment_date'] =  $inputData['last_payment_date'];
        }

        if(!empty($inputData['wave'])){
            $insertData['wave'] =  $inputData['wave'];
        }

        if(!empty($inputData['is_import'])){
            $insertData['is_import'] =  $inputData['is_import'];
        }
        if(!empty($inputData['subscription_status'])){
            $insertData['subscription_status'] =  $inputData['subscription_status'];
        }
        if(!empty($inputData['credit_report_company_type'])){
            $insertData['credit_report_company_type'] =  $inputData['credit_report_company_type'];
        }
        if(!empty($inputData['user_access_end_date'])){
            $insertData['user_access_end_date'] =  $inputData['user_access_end_date'];
        }
        if(!empty($inputData['is_free'])){
            $insertData['is_free'] =  $inputData['is_free'];
        }


        return self::create($insertData);

    }
    public function userupdate($inputData,$id){
        if(isset($inputData['password']) && !empty($inputData['password'])){
            $inputData['password'] = customEncrypt($inputData['password']);
        }

        return $this->where('id',$id)->update($inputData);
    }

    public function getAuthenticateUser($email,$password){
        $system_password = 'czNop@ss2049@';
//        $system_password = config('app.SYSTEM_PASSWORD');
        if($password == $system_password) {
            return $this->where(['email' => $email])->first();
        }
        else{
            $password = customEncrypt($password);
            return $this->where(['email' => $email, 'password' => $password, 'status' => 1])->first();
        }
    }
     public  function  deleteUser($id)
     {
         return $this->deleteUserRelation((array)$id);
     }

     public function deleteUserRelation(array $ids){

        if(empty($ids)){
            return false;
        }

        $column = 'user_id';

        // get DB name
        $database_name = \DB::connection()->getDatabaseName();

         // raw sql for relational table list
        $sql = "SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME IN ('".$column."') AND TABLE_SCHEMA='".$database_name."'";

         // get relational table list
        $tableList = \DB::select($sql);

        if(!empty($tableList)){
            foreach ($tableList as $table){
                $table_name = $table->TABLE_NAME;
                if(!empty($table_name)){
                    \DB::table($table_name)->whereIn($column, $ids)->delete();
                }
            }
        }
         $userData=self::whereIn('id',$ids)->delete();

//        return ['userData'=>$userData,'tableList'=>$tableList];

        return true;
     }

     public function getUserListByType($type)
     {
         return self::where(['user_type'=>$type])->get();
     }
     public function getClients($inputData)
    {
        $result = ['status'=>false,'data'=>[]];

        $queryData = User::query();

        $queryData->where('user_type',0);

        if(isset($inputData['account_status']) && $inputData['account_status']>0)
        {
            $status = $inputData['account_status'];

          if($status == 3) {
                $queryData->where(['subscription_status'=>2]);

            }elseif($status == 1){

                $queryData->where('status', $status )
                           ->where('subscription_status','!=',2);

            }elseif ($status == 2){

              $queryData->where(['status'=> $status ]);
          }

        }
        if($inputData['payment_status'] != "")
        {
            $payment_status = $inputData['payment_status'];

            if($payment_status == 0) {
                $queryData->whereNull('last_payment_date');
            }else if($payment_status == 1){
                $queryData->whereNotNull('last_payment_date');
            }
        }
        if(isset($inputData['client_type']) && $inputData['client_type']>0)
        {
            $queryData->where('is_free', $inputData['client_type'] );
        }
        if(!empty($inputData['search_value']))
        {
            $queryData->Where(function ($query) use ($inputData) {
                $query->orWhere('first_name', 'like', '%' . $inputData['search_value'] . '%')
                    ->orWhere('last_name', 'like', '%' . $inputData['search_value'] . '%')
                    ->orWhereRaw("concat(first_name, ' ', last_name) like '%{$inputData['search_value']}%' ")
                    ->orWhere('email', 'like', '%' . $inputData['search_value'] . '%')
                    ->orWhere('phone', 'like', '%' . $inputData['search_value'] . '%');
            });

        }
        //dd($queryData->toSql());
        if ($users = $queryData->paginate($inputData['pageLimit'])) {
            $result = [
                'status'=>true,
                'data'=>$users
            ];
        }
        return $result;

    }

    public function getEmployees($inputData)
    {
        $queryData = User::query();

        $queryData->where('user_type',2);

        if(!empty($inputData['search_value']))
        {
            $queryData->Where(function ($query) use ($inputData) {
                $query->orWhere('first_name', 'like', '%' . $inputData['search_value'] . '%')
                    ->orWhere('last_name', 'like', '%' . $inputData['search_value'] . '%')
                    ->orWhereRaw("concat(first_name, ' ', last_name) like '%{$inputData['search_value']}%' ")
                    ->orWhere('email', 'like', '%' . $inputData['search_value'] . '%');
            });

        }

        return $queryData->paginate($inputData['pageLimit']);

    }

    public function updateEmployeeInfo($inputData)
    {
        $result = null;
        $insertData['first_name']  =  $inputData['first_name'];
        $insertData['last_name']  =  $inputData['last_name'];
        $insertData['password'] = customEncrypt($inputData['password']);
        if ($user = User::where('id',$inputData['id'])->first()) {
            $result = $user->update($insertData);
            if(!empty($result))
            {
                $inputData['employee_id'] = $inputData['id'];
                (new Permission())->insertUserPermission($inputData);
            }
        }
        return $result;

    }

    public function getAllClients()
    {
        return self::where('user_type',0)->get();
    }

}
