<?php

namespace App\Models;

use CodeIgniter\Model;

class PayrollRunModel extends Model
{
    protected $table         = 'payroll_runs';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';

    protected $allowedFields = [
        'period_year', 'period_month', 'title', 'status', 'run_date',
        'notes', 'approved_by', 'approved_at', 'paid_at',
        'created_by', 'updated_by',
    ];

    public function scopeForList(?int $year = null, ?string $status = null): self
    {
        if ($year) {
            $this->where('period_year', $year);
        }

        if ($status) {
            $this->where('status', $status);
        }

        return $this;
    }

    public function findByPeriod(int $year, int $month): ?array
    {
        return $this->where('period_year', $year)
            ->where('period_month', $month)
            ->first() ?: null;
    }

    public function periodLabel(array $run): string
    {
        return date('F Y', mktime(0, 0, 0, (int) $run['period_month'], 1, (int) $run['period_year']));
    }
}
