<?php

namespace App\Models;

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

class SmsGateway extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $hidden = ['api_key', 'settings'];

    protected $fillable = [
        'name',
        'provider',
        'api_url',
        'api_key',
        'sender_id',
        'settings',
        'status',
    ];

    protected $casts = [
        'settings' => 'array',
        'status' => 'boolean',
    ];

    public function messages()
    {
        return $this->hasMany(SmsMessage::class, 'gateway_id');
    }

    public function setApiKeyAttribute($value): void
    {
        $this->attributes['api_key'] = filled($value) ? Crypt::encryptString((string) $value) : null;
    }

    public function getApiKeyAttribute($value): ?string
    {
        if (! filled($value)) return null;
        try { return Crypt::decryptString($value); } catch (\Throwable) { return $value; }
    }
}
