<?php

namespace App\Entities\Panel;

use CodeIgniter\Entity\Entity;

class User extends Entity
{
    protected $attributes = [
        'role' => '',
    ];
    protected $datamap = [
        // 'role' => [],
    ];
    protected $dates   = ['created_at', 'updated_at', 'deleted_at'];
    protected $casts   = [
        'role' => 'csv',
    ];

    public function hasRole($role)
    {
        $roles = $this->role;
        if (is_string($role)) $role = [$role];
        foreach ($roles as $r) {
            if (in_array($r, $role)) return true;
        }
        return false;
    }
    public function passwordVerify($plain_password)
    {
        return password_verify(base64_encode(
            hash('sha384', $plain_password, true)
        ), $this->attributes['password_hash']);
    }
    public function setPassword(string $password)
    {
        $config = config('App');
        try {
            if (
                (defined('PASSWORD_ARGON2I') && $config->hashAlgorithm == PASSWORD_ARGON2I)
                ||
                (defined('PASSWORD_ARGON2ID') && $config->hashAlgorithm == PASSWORD_ARGON2ID)
            ) {
                $hashOptions = [
                    'memory_cost' => $config->hashMemoryCost,
                    'time_cost'   => $config->hashTimeCost,
                    'threads'     => $config->hashThreads
                ];
            } else {
                $hashOptions = [
                    'cost' => $config->hashCost
                ];
            }

            $pw = password_hash(
                base64_encode(
                    hash('sha384', $password, true)
                ),
                $config->hashAlgorithm,
                $hashOptions
            );
            $this->attributes['password_hash'] = $pw;
        } catch (\Throwable $th) {
            $pw = password_hash(
                base64_encode(
                    hash('sha384', $password, true)
                ),
                PASSWORD_DEFAULT,
                ['cost' => 10]
            );
            $this->attributes['password_hash'] = $pw;
        }
        return $this;
    }
}
