<?php

namespace App\Traits;

use Illuminate\Support\Facades\Crypt;

trait Encryptable
{
    /**
     * Encrypt a value
     */
    public function encrypt($value)
    {
        if (is_null($value) || $value === '') {
            return null;
        }
        
        return Crypt::encryptString($value);
    }

    /**
     * Decrypt a value
     */
    public function decrypt($value)
    {
        if (is_null($value) || $value === '') {
            return null;
        }
        
        try {
            return Crypt::decryptString($value);
        } catch (\Exception $e) {
            // Jika gagal decrypt, return value asli (untuk data lama yang belum dienkripsi)
            return $value;
        }
    }

    /**
     * Get encrypted attribute
     */
    public function getEncryptedAttribute($key)
    {
        $encryptedKey = $key . '_encrypted';
        
        if (isset($this->attributes[$encryptedKey])) {
            return $this->decrypt($this->attributes[$encryptedKey]);
        }
        
        return $this->attributes[$key] ?? null;
    }

    /**
     * Set encrypted attribute
     */
    public function setEncryptedAttribute($key, $value)
    {
        $encryptedKey = $key . '_encrypted';
        
        // Simpan data asli di kolom biasa (untuk backup)
        $this->attributes[$key] = $value;
        
        // Simpan data terenkripsi di kolom encrypted
        $this->attributes[$encryptedKey] = $this->encrypt($value);
    }
}
