<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Crypt;

class DomainLogin extends Model
{
    use HasFactory;

    protected $fillable = [
        'domain_id',
        'login_type',
        'username',
        'password',
        'login_url',
    ];

    public function setPasswordAttribute($value)
    {
        if (!empty($value)) {
            $this->attributes['password'] = Crypt::encryptString($value);
        } else {
            $this->attributes['password'] = $value;
        }
    }

    public function getPasswordAttribute($value)
    {
        if (empty($value)) return $value;
        try {
            return Crypt::decryptString($value);
        } catch (\Illuminate\Contracts\Encryption\DecryptException $e) {
            return $value;
        }
    }

    public function domain()
    {
        return $this->belongsTo(Domain::class);
    }
}
