<?php

namespace App\Models;

use App\Casts\Hash;
use App\Models\BaseModel;
use Illuminate\Support\Facades\Crypt;

class FaceRegistration extends BaseModel
{
    protected $table = 'face_registrations';

    protected $default = ['xid', 'x_user_id', 'x_company_id'];

    protected $guarded = ['id', 'created_at', 'updated_at'];

    protected $hidden = ['id', 'user_id', 'company_id', 'face_data'];

    protected $appends = ['xid', 'x_user_id', 'x_company_id'];

    protected $hashableGetterFunctions = [
        'getXUserIdAttribute' => 'user_id',
        'getXCompanyIdAttribute' => 'company_id',
    ];

    protected $casts = [
        'user_id' => Hash::class . ':hash',
        'company_id' => Hash::class . ':hash',
    ];

    /**
     * Encrypt face_data when setting
     */
    public function setFaceDataAttribute($value)
    {
        if ($value) {
            $this->attributes['face_data'] = Crypt::encryptString($value);
        }
    }

    /**
     * Get decrypted face data (for API responses)
     * Note: We don't auto-decrypt on access for security
     */
    public function getDecryptedFaceData()
    {
        if (isset($this->attributes['face_data']) && $this->attributes['face_data']) {
            try {
                return Crypt::decryptString($this->attributes['face_data']);
            } catch (\Exception $e) {
                return null;
            }
        }
        return null;
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function company()
    {
        return $this->belongsTo(Company::class, 'company_id', 'id');
    }
}

