<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Application extends Model
{
    protected $fillable = ['folio', 'type', 'status', 'full_name', 'rut', 'rut_hash', 'email', 'phone', 'application_date', 'data', 'attachments', 'admin_notes'];

    protected function casts(): array
    {
        return [
            'rut' => 'encrypted',
            'email' => 'encrypted',
            'phone' => 'encrypted',
            'data' => 'encrypted:array',
            'attachments' => 'encrypted:array',
            'admin_notes' => 'encrypted',
            'application_date' => 'date',
        ];
    }

    protected static function booted(): void
    {
        static::saving(function (Application $application) {
            if ($application->isDirty('rut')) {
                $cleanRut = strtoupper(preg_replace('/[^0-9K]/i', '', (string) $application->rut));
                $application->rut_hash = hash_hmac('sha256', $cleanRut, config('app.key'));
            }
        });
    }
}
