<?php
declare(strict_types=1);

namespace App\Modules\HR\Models;

use App\Core\Model;
use App\Core\App;

class HrLeaveBalance extends Model
{
    protected static string $table = 'hr_leave_balances';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = false;
    protected static bool $autoTrackAuthor = true;

    protected static array $fillable = [
        'employee_profile_id', 'leave_type_id', 'year',
        'entitled_days', 'carried_over_days', 'adjustment_days',
        'used_days', 'pending_days', 'adjustment_reason',
    ];

    public static function getForEmployee(int $profileId, int $year): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT lb.*, lt.code as leave_code, lt.name_ar as leave_name, lt.category,
                    (lb.entitled_days + lb.carried_over_days + lb.adjustment_days - lb.used_days - lb.pending_days) as remaining_days
             FROM hr_leave_balances lb
             JOIN hr_leave_types lt ON lt.id = lb.leave_type_id
             WHERE lb.employee_profile_id = ? AND lb.year = ?
             ORDER BY lt.sort_order ASC",
            [$profileId, $year]
        );
    }

    public static function getBalance(int $profileId, int $leaveTypeId, int $year): ?array
    {
        $db = App::getInstance()->db();
        return $db->selectOne(
            "SELECT *, (entitled_days + carried_over_days + adjustment_days - used_days - pending_days) as remaining_days
             FROM hr_leave_balances
             WHERE employee_profile_id = ? AND leave_type_id = ? AND year = ?",
            [$profileId, $leaveTypeId, $year]
        );
    }

    public static function deductDays(int $balanceId, string $days): void
    {
        $db = App::getInstance()->db();
        $db->update(
            'hr_leave_balances',
            ['used_days' => new \App\Core\RawExpression("used_days + {$days}"),
             'pending_days' => new \App\Core\RawExpression("GREATEST(pending_days - {$days}, 0)"),
             'updated_at' => date('Y-m-d H:i:s')],
            '`id` = ?',
            [$balanceId]
        );
    }

    public static function addPendingDays(int $balanceId, string $days): void
    {
        $db = App::getInstance()->db();
        $db->update(
            'hr_leave_balances',
            ['pending_days' => new \App\Core\RawExpression("pending_days + {$days}"),
             'updated_at' => date('Y-m-d H:i:s')],
            '`id` = ?',
            [$balanceId]
        );
    }

    public static function releasePendingDays(int $balanceId, string $days): void
    {
        $db = App::getInstance()->db();
        $db->update(
            'hr_leave_balances',
            ['pending_days' => new \App\Core\RawExpression("GREATEST(pending_days - {$days}, 0)"),
             'updated_at' => date('Y-m-d H:i:s')],
            '`id` = ?',
            [$balanceId]
        );
    }
}
