<?php

namespace App\Modules\Clients;

use Illuminate\Support\Facades\Crypt;
use Exception;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use App\Models\ValidationModel;
use App\Modules\Clients\Client;
use App\Modules\Clients\Customer;

class License extends ValidationModel
{
    use SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['client_id', 'client_type', 'product', 'key', 'expiry_date', 'created_by', 'updated_by'];

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'licenses';

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['deleted_at'];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [];

    /**
     * Array of validation rules.
     *
     * @var  array
     */
    protected static $rules = [
        'client_id'   => 'required',
        'client_type' => 'required',
        'product'     => 'required',
        'key'         => 'required',
    ];

    /**
     * The "booting" method of the model.
     */
    public static function boot(): void
    {
        parent::boot();

        // When a transaction is created we want to
        // update the created_by field
        static::creating(function ($model) {
            $model->created_by = getAuthUserId();
            $model->updated_by = getAuthUserId();
        });

        static::updating(function ($model) {
            $model->updated_by = getAuthUserId();
        });
    }

    /**
     * Decrypt the key.
     */
    public function getKeyAttribute($value): string|false
    {
        try {
            return Crypt::decrypt($value);
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * Encrypts the key.
     */
    public function setKeyAttribute($value): void
    {
        $this->attributes['key'] = Crypt::encrypt($value);
    }

    /**
     * Returns the client model.
     */
    public function client(): BelongsTo
    {
        if ($this->attributes['client_type'] == 'client') {
            return $this->belongsTo(Client::class, 'client_id');
        } else {
            return $this->belongsTo(Customer::class, 'client_id');
        }
    }
}
