<?php

namespace App\Models;

use CodeIgniter\Model;

class PayrollItemLineModel extends Model
{
    protected $table         = 'payroll_item_lines';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = false;

    protected $allowedFields = ['payroll_item_id', 'component_id', 'amount', 'notes', 'created_at'];

    public function getForItem(int $itemId): array
    {
        return $this->db->table('payroll_item_lines pil')
            ->select('pil.*, pc.code, pc.name, pc.type, pc.sort_order')
            ->join('payroll_components pc', 'pc.id = pil.component_id', 'inner')
            ->where('pil.payroll_item_id', $itemId)
            ->orderBy('pc.sort_order', 'ASC')
            ->get()
            ->getResultArray();
    }

    public function replaceForItem(int $itemId, array $lines): void
    {
        $this->where('payroll_item_id', $itemId)->delete();
        $now = date('Y-m-d H:i:s');
        foreach ($lines as $line) {
            $this->insert([
                'payroll_item_id' => $itemId,
                'component_id'    => $line['component_id'],
                'amount'          => $line['amount'],
                'notes'           => $line['notes'] ?? null,
                'created_at'      => $now,
            ]);
        }
    }
}
