<?php

namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Support\Facades\Crypt;

class OptionalEncrypted implements CastsAttributes
{
    /**
     * @return mixed
     */
    public function get($model, string $key, $value, array $attributes)
    {
        if (!config('encryption.enabled') || is_null($value)) {
            return $value;
        }

        try {
            return Crypt::decryptString($value);
        } catch (\Exception $e) {
            // Decryption failed — value is likely legacy plaintext (not yet migrated).
            // Return the raw value rather than null to avoid breaking NOT NULL constraints.
            return $value;
        }
    }

    /**
     * @return mixed
     */
    public function set($model, string $key, $value, array $attributes)
    {
        if (!config('encryption.enabled') || is_null($value)) {
            return $value;
        }

        return Crypt::encryptString($value);
    }
}
