<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'payroll_run_id', 'employee_id', 'days_worked', 'days_absent',
        'unpaid_leave_days', 'overtime_minutes_day', 'overtime_minutes_night',
        'gross_earnings', 'total_deductions', 'net_pay',
        'employer_sio', 'employer_eosb', 'employer_total_cost', 'status',
    ];

    public function getForRun(int $runId, ?string $search = null): array
    {
        $builder = $this->db->table('payroll_items pi')
            ->select('pi.*, e.full_name, e.employee_number, e.cpr_number, e.bank_account, e.bank_name, e.nationality')
            ->join('employees e', 'e.id = pi.employee_id', 'inner')
            ->where('pi.payroll_run_id', $runId)
            ->where('e.deleted_at', null);

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

        return $builder->orderBy('e.full_name', 'ASC')->get()->getResultArray();
    }

    public function getWithRunAndEmployee(int $itemId): ?array
    {
        $row = $this->db->table('payroll_items pi')
            ->select('pi.*, e.full_name, e.employee_number, e.cpr_number, e.bank_account, e.bank_name,
                      e.nationality, e.department_id, e.job_title, e.hire_date,
                      pr.period_year, pr.period_month, pr.status as run_status, pr.title as run_title')
            ->join('employees e', 'e.id = pi.employee_id', 'inner')
            ->join('payroll_runs pr', 'pr.id = pi.payroll_run_id', 'inner')
            ->where('pi.id', $itemId)
            ->where('e.deleted_at', null)
            ->get()
            ->getRowArray();

        return $row ?: null;
    }

    public function deleteForRun(int $runId): void
    {
        $items = $this->where('payroll_run_id', $runId)->findAll();
        $lineModel = new PayrollItemLineModel();
        foreach ($items as $item) {
            $lineModel->where('payroll_item_id', (int) $item['id'])->delete();
        }
        $this->where('payroll_run_id', $runId)->delete();
    }

    public function getRunTotals(int $runId): array
    {
        $row = $this->db->table('payroll_items')
            ->select('COUNT(*) as employee_count,
                      COALESCE(SUM(gross_earnings), 0) as total_gross,
                      COALESCE(SUM(total_deductions), 0) as total_deductions,
                      COALESCE(SUM(net_pay), 0) as total_net,
                      COALESCE(SUM(employer_sio), 0) as total_sio,
                      COALESCE(SUM(employer_eosb), 0) as total_eosb,
                      COALESCE(SUM(employer_total_cost), 0) as total_cost')
            ->where('payroll_run_id', $runId)
            ->get()
            ->getRowArray();

        return $row ?: [
            'employee_count'   => 0,
            'total_gross'      => 0,
            'total_deductions' => 0,
            'total_net'        => 0,
            'total_sio'        => 0,
            'total_eosb'       => 0,
            'total_cost'       => 0,
        ];
    }
}
