<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'employee_id', 'leave_type_id', 'year', 'entitled', 'used',
    ];

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

        if ($employeeId) {
            $this->where('employee_id', $employeeId);
        }

        if ($leaveTypeId) {
            $this->where('leave_type_id', $leaveTypeId);
        }

        return $this;
    }

    public function findOrCreate(int $employeeId, int $leaveTypeId, int $year, float $defaultEntitled = 0): array
    {
        $balance = $this->where('employee_id', $employeeId)
            ->where('leave_type_id', $leaveTypeId)
            ->where('year', $year)
            ->first();

        if ($balance) {
            return $balance;
        }

        $this->insert([
            'employee_id'   => $employeeId,
            'leave_type_id' => $leaveTypeId,
            'year'          => $year,
            'entitled'      => $defaultEntitled,
            'used'          => 0,
        ]);

        return $this->find($this->getInsertID());
    }

    public function getRemaining(array $balance): float
    {
        return max(0, (float) $balance['entitled'] - (float) $balance['used']);
    }

    public function addUsed(int $id, float $days): bool
    {
        $balance = $this->find($id);
        if (! $balance) {
            return false;
        }

        return $this->update($id, ['used' => (float) $balance['used'] + $days]);
    }

    public function subtractUsed(int $id, float $days): bool
    {
        $balance = $this->find($id);
        if (! $balance) {
            return false;
        }

        $newUsed = max(0, (float) $balance['used'] - $days);

        return $this->update($id, ['used' => $newUsed]);
    }
}
