<?php

/**
 * Admin User
 *
 * Manages Admin User.
 *
 * @author Florin Radica <florin.radica@mtcmedia.co.uk>
 * @since 04/07/2017
 */

namespace Mtc\Core;

use App\Casts\OptionalEncrypted;
use App\Src\Encryption;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

/**
 * Accessors
 *
 * @property int $id
 * @property string $username
 * @property string $password
 * @property string $email
 * @property string $signature
 * @property string $session_id
 * @property string $name
 * @property int $role
 *
 */
class AdminUser extends Model
{
    public $timestamps = false;
    protected $table = 'admin_users';
    protected $fillable = [
        'username',
        'email',
        'signature',
        'session_id',
        'name',
        'role',
        'credentials',
    ];

    protected $casts = [
        'email' => OptionalEncrypted::class,
        'name' => OptionalEncrypted::class,
        'username' => OptionalEncrypted::class,
        'credentials' => OptionalEncrypted::class,
    ];

    public static $searchable = [
        'username',
        'email',
    ];

    protected static function boot(): void
    {
        parent::boot();

        self::saved(static function (self $model): void {
            Encryption::updateHashes($model);
        });
    }

    public static function getCurrent()
    {
        $legacy_admin_user = new \AdminUser;

        return $legacy_admin_user->eloquent();
    }

    public function scopeWhereUsername($query, string $username): Builder
    {
        return $query->where('username_hash', Encryption::makeHash($username));
    }
}
