<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'employee_id', 'termination_date', 'last_working_day', 'years_of_service',
        'unused_leave_days', 'leave_encashment', 'legacy_eosb', 'notice_pay',
        'last_salary', 'other_entitlements', 'total_deductions', 'total_settlement',
        'status', 'notes', 'approved_by', 'approved_at', 'paid_at', 'created_by',
    ];

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

        return $this;
    }

    public function getWithEmployees(?string $search = null, ?string $status = null): array
    {
        $builder = $this->db->table('payroll_settlements ps')
            ->select('ps.*, e.full_name, e.employee_number, e.nationality')
            ->join('employees e', 'e.id = ps.employee_id', 'inner')
            ->where('e.deleted_at', null);

        if ($status) {
            $builder->where('ps.status', $status);
        }

        if ($search) {
            $builder->groupStart()
                ->like('e.full_name', $search)
                ->orLike('e.employee_number', $search)
                ->groupEnd();
        }

        return $builder->orderBy('ps.created_at', 'DESC')->get()->getResultArray();
    }

    public function getWithEmployee(int $id): ?array
    {
        $row = $this->db->table('payroll_settlements ps')
            ->select('ps.*, e.full_name, e.employee_number, e.cpr_number, e.nationality,
                      e.hire_date, e.bank_account, e.bank_name, e.job_title')
            ->join('employees e', 'e.id = ps.employee_id', 'inner')
            ->where('ps.id', $id)
            ->where('e.deleted_at', null)
            ->get()
            ->getRowArray();

        return $row ?: null;
    }
}
