<?php

namespace App\Casts;

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

class OptionalEncryptedArray implements CastsAttributes
{
    /**
     * @return mixed
     */
    public function get($model, string $key, $value, array $attributes)
    {
        if (is_null($value)) {
            return $value;
        }

        if (config('encryption.enabled')) {
            try {
                $value = Crypt::decryptString($value);
            } catch (\Exception $e) {
                // legacy plaintext — fall through to json_decode below
            }
        }

        $decoded = json_decode($value, true);
        return is_array($decoded) ? $decoded : null;
    }

    /**
     * @return mixed
     */
    public function set($model, string $key, $value, array $attributes)
    {
        if (is_null($value)) {
            return $value;
        }

        $json = json_encode($value);

        if (config('encryption.enabled')) {
            return Crypt::encryptString($json);
        }

        return $json;
    }
}
