<?php

namespace App\Entities\Mobile;

use CodeIgniter\Entity\Entity;

class User extends Entity
{
    protected $datamap = [];
    protected $dates   = ['created_at', 'updated_at', 'deleted_at'];
    protected $casts   = [];
    public function setPassword(string $password)
    {
        $this->attributes['password_hash'] = $this->generatePassword($password);
        return $this;
    }

    public function getPasswordHash()
    {
        return $this->attributes['password_hash'];
    }

    public function getPassword()
    {
        return $this->descryptPassword($this->attributes['password_hash']);
    }

    public function descryptPassword($password)
    {
        $config = new \Config\Encryption();
        $config->key = options('MOBILEPASSKEY');
        $encrypter = \Config\Services::encrypter($config);
        try {
            return $encrypter->decrypt($password);
        } catch (\Throwable $th) {
            return null;
        }
    }

    public function generatePassword($password)
    {
        $config      = new \Config\Encryption();
        $config->key = options('MOBILEPASSKEY');
        $encrypter   = \Config\Services::encrypter($config);
        return $encrypter->encrypt($password);
    }
}
