<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'employee_id', 'effective_from', 'effective_to',
        'basic_salary', 'social_allowance', 'housing_allowance',
        'transport_allowance', 'other_allowances', 'payment_method',
        'notes', 'created_by', 'updated_by',
    ];

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

        return $this;
    }

    public function getEffectiveForEmployee(int $employeeId, string $asOfDate): ?array
    {
        return $this->where('employee_id', $employeeId)
            ->where('effective_from <=', $asOfDate)
            ->groupStart()
                ->where('effective_to >=', $asOfDate)
                ->orWhere('effective_to', null)
            ->groupEnd()
            ->orderBy('effective_from', 'DESC')
            ->first() ?: null;
    }

    public function getCurrentForEmployee(int $employeeId): ?array
    {
        return $this->getEffectiveForEmployee($employeeId, date('Y-m-d'));
    }

    public function closeOpenStructure(int $employeeId, string $effectiveTo): void
    {
        $this->where('employee_id', $employeeId)
            ->where('effective_to', null)
            ->set(['effective_to' => $effectiveTo, 'updated_at' => date('Y-m-d H:i:s')])
            ->update();
    }

    public function getWithEmployees(?string $search = null): array
    {
        $builder = $this->db->table('employee_salary_structures ess')
            ->select('ess.*, e.full_name, e.employee_number, e.department_id, e.status as employee_status')
            ->join('employees e', 'e.id = ess.employee_id', 'inner')
            ->where('e.deleted_at', null)
            ->where('ess.effective_to', 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 grossSalary(array $structure): float
    {
        return (float) $structure['basic_salary']
            + (float) $structure['social_allowance']
            + (float) $structure['housing_allowance']
            + (float) $structure['transport_allowance']
            + (float) $structure['other_allowances'];
    }

    public function sioBase(array $structure): float
    {
        return (float) $structure['basic_salary'] + (float) $structure['social_allowance'];
    }
}
