<?php

namespace App\Modules\Pilkades\Models;

use App\Core\Concerns\HasUuid;
use App\Modules\Pilkades\Models\Concerns\BelongsToDesa;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class Voter extends Model
{
    use BelongsToDesa, HasFactory, HasUuid, SoftDeletes;

    protected $table = 'voters';

    protected $fillable = [
        'desa_id',
        'nama',
        'nik',
        'tps_id',
        'rt',
        'rw',
        'status_terdaftar',
    ];

    protected $hidden = [
        'nik_encrypted',
        'nik_hash',
    ];

    protected function casts(): array
    {
        return [
            'nik_encrypted' => 'encrypted',
        ];
    }

    public function tps(): BelongsTo
    {
        return $this->belongsTo(Tps::class);
    }

    /**
     * Virtual "nik" attribute: writing sets both the encrypted value (via the
     * "encrypted" cast on nik_encrypted) and its deterministic hash (used for
     * exact-match search without decrypting rows).
     */
    public function setNikAttribute(string $value): void
    {
        $this->setAttribute('nik_encrypted', $value);
        $this->attributes['nik_hash'] = hash('sha256', $value);
    }

    public function getNikAttribute(): ?string
    {
        return $this->getAttribute('nik_encrypted');
    }

    public static function hashNik(string $nik): string
    {
        return hash('sha256', $nik);
    }

    public static function maskNik(string $nik): string
    {
        return substr($nik, 0, 4).str_repeat('*', 8).substr($nik, -4);
    }
}
