<?php

namespace App\Models;

use CodeIgniter\Model;

class EmployeeDocumentVersionModel extends Model
{
    protected $table         = 'employee_document_versions';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = false;
    protected $dateFormat    = 'datetime';

    protected $allowedFields = [
        'employee_document_id', 'version_number', 'file_path', 'original_filename',
        'file_size', 'mime_type', 'change_notes', 'uploaded_by', 'created_at',
    ];

    public function getForDocument(int $documentId): array
    {
        return $this
            ->where('employee_document_id', $documentId)
            ->orderBy('version_number', 'DESC')
            ->findAll();
    }

    public function getLatest(int $documentId): ?array
    {
        return $this
            ->where('employee_document_id', $documentId)
            ->orderBy('version_number', 'DESC')
            ->first();
    }

    public function getByVersion(int $documentId, int $versionId): ?array
    {
        return $this
            ->where('employee_document_id', $documentId)
            ->where('id', $versionId)
            ->first();
    }

    public function nextVersionNumber(int $documentId): int
    {
        $row = $this
            ->selectMax('version_number', 'max_version')
            ->where('employee_document_id', $documentId)
            ->first();

        return ((int) ($row['max_version'] ?? 0)) + 1;
    }
}
