<?php

namespace App\Models;

use CodeIgniter\Model;

class PayrollTransactionModel extends Model
{
    protected $table            = 'pay_trans';
    protected $primaryKey       = 'paytrans_id';
    protected $useAutoIncrement = true;
    protected $returnType       = \App\Entities\PayrollTransaction::class;
    protected $useSoftDeletes   = true;
    protected $protectFields    = true;
    protected $allowedFields    = ['paytype_id', 
                                   'payschedule_id', 
                                   'payroll_from', 
                                   'payroll_to', 
                                   'no_of_days', 
                                   'total_emp', 
                                   'total_gross', 
                                   'remarks', 
                                   'is_open'];

    protected bool $allowEmptyInserts = false;

    // Dates
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    // Validation
    protected $validationRules      = [];
    protected $validationMessages   = [];
    protected $skipValidation       = false;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks = true;
    protected $beforeInsert   = ['assignCreatedBy'];
    protected $afterInsert    = [];
    protected $beforeUpdate   = ['assignUpdatedBy'];
    protected $afterUpdate    = [];
    protected $beforeFind     = [];
    protected $afterFind      = [];
    protected $beforeDelete   = [];
    protected $afterDelete    = [];

    public function assignCreatedBy(array $data)
    {
        $data['data']['created_by'] = auth()->user()->employee_id;
        return $data;
    }

    public function assignUpdatedBy(array $data)
    {
        $data['data']['updated_by'] = auth()->user()->employee_id;
        return $data;
    }

    public function getPayTransXPayTypeXPaySchedByPayTransId($paytransid)
    {
        $builder = $this->db->table('pay_trans');
        $builder->select('*');
        $builder->join('pay_type', 'pay_type.paytype_id = pay_trans.paytype_id');
        $builder->join('pay_schedule', 'pay_schedule.payschedule_id = pay_trans.payschedule_id');
        $builder->where(['pay_trans.paytrans_id' => $paytransid, 
                         'pay_trans.deleted_at' => null]);
        $query = $builder->get();

        return $query->getRow();
    }
}
