<?php

namespace App\Models;

use CodeIgniter\Model;
use Ramsey\Uuid\Uuid;

class CertificateModel extends Model
{
    protected $table            = 'certificates';
    protected $primaryKey       = 'cert_id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = true;
    protected $allowedFields    = [
        'cert_number', 'cert_name', 'cert_type', 'actid', 'issued_date', 
        'expired_date', 'user_id', 'user_validation_at', 'spv_id', 
        'spv_validation_at', 'manager_id', 'manager_validation_at', 
        'status', 'file_location', 'file_url', 'metadata_title', 'metadata_keywords', 'deleted_at'
    ];

    // Timestamps
    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    // Callbacks
    protected $beforeInsert = ['generateUuidBinary'];
    protected $afterFind    = ['convertBinaryToUuidString'];

    /**
     * Otomatis Generate UUIDv4 dan ubah ke Binary sebelum Insert
     */
    protected function generateUuidBinary(array $data)
    {
        if (!isset($data['data']['cert_number'])) {
            $uuid = Uuid::uuid4();
            // Simpan dalam format byte (binary 16)
            $data['data']['cert_number'] = $uuid->getBytes();
        }
        return $data;
    }

    /**
     * Otomatis ubah Binary ke String UUID setelah data diambil (Get)
     */
    protected function convertBinaryToUuidString(array $data)
    {
        if (empty($data['data'])) return $data;

        // Cek apakah data berupa single row atau multiple rows
        if (isset($data['data']['cert_number'])) {
            // Single row (find/first)
            $data['data']['cert_number'] = Uuid::fromBytes($data['data']['cert_number'])->toString();
        } else {
            // Multiple rows (findAll)
            foreach ($data['data'] as &$row) {
                if (isset($row['cert_number'])) {
                    $row['cert_number'] = Uuid::fromBytes($row['cert_number'])->toString();
                }
            }
        }

        return $data;
    }

    /**
     * Helper untuk mencari data berdasarkan String UUID
     */
    public function getByUuid(string $uuidString)
    {
        $binary = Uuid::fromString($uuidString)->getBytes();
        return $this->where('cert_number', $binary)->first();
    }
}