<?php

namespace App\Models;

use Config\Lookups;

/**
 * The manager's typed-in allowance/deduction rows for a payslip — see
 * CreatePayslipLineItemsTable's migration comment for why this is
 * free-form entry, not a computed tax formula.
 */
class PayslipLineItemModel extends TenantModel
{
    protected $table            = 'payslip_line_items';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'object';
    protected $useTimestamps    = true;
    protected $createdField     = 'created_at';
    protected $updatedField     = '';

    protected $allowedFields = [
        'payslip_id',
        'type',
        'label',
        'amount',
    ];

    public function __construct()
    {
        parent::__construct();

        $types = array_keys((new Lookups())->payslipLineItemTypes);

        $this->validationRules = [
            'payslip_id' => 'required|integer',
            'type'       => 'required|in_list[' . implode(',', $types) . ']',
            'label'      => 'required|max_length[150]',
            'amount'     => 'required|decimal',
        ];
    }

    public function forPayslip(int $payslipId): array
    {
        return $this->where('payslip_id', $payslipId)->orderBy('created_at', 'asc')->findAll();
    }
}
