BalanceCheckHandler.php

4.75 KB
08/07/2025 09:10
PHP
BalanceCheckHandler.php
<?php

namespace App\Handlers;

use App\Core\Database;
use App\Models\Employee;
use App\Models\LeaveBalance; // We'll use the existing model method
use App\Services\TelegramService;

class BalanceCheckHandler
{
    private TelegramService $telegramService;
    private int $chatId;
    private int $userId; // Telegram User ID
    private ?int $employeeId = null; // System's employee ID

    /**
     * @param TelegramService $telegramService
     * @param int $chatId
     * @param int $userId
     */
    public function __construct(TelegramService $telegramService, int $chatId, int $userId)
    {
        $this->telegramService = $telegramService;
        $this->chatId = $chatId;
        $this->userId = $userId;
        $this->loadEmployeeId();
    }

    private function loadEmployeeId(): void
    {
        $employeeModel = new Employee(Database::getInstance());
        $employee = $employeeModel->findByChatUserId((string) $this->userId);
        if ($employee && $employee->id) {
            $this->employeeId = $employee->id;
            // log_message("BalanceCheckHandler: Employee ID {$this->employeeId} loaded for Telegram user ID {$this->userId}");
        } else {
            log_message("BalanceCheckHandler: No employee record found for Telegram user ID {$this->userId}.");
        }
    }

    /**
     * @return null
     */
    public function showBalances(): void
    {
        if ($this->employeeId === null) {
            $this->telegramService->sendMessage($this->chatId, "ขออภัยค่ะ ไม่พบข้อมูลพนักงานของคุณ (Telegram User ID: {$this->userId}) ในระบบ โปรดติดต่อ HR เพื่อลงทะเบียน Telegram User ID ของคุณก่อนค่ะ");
            return;
        }

        $currentYear = (int) date('Y');
        $leaveBalanceModel = new LeaveBalance(Database::getInstance());

        $balancesData = $leaveBalanceModel->getBalancesForEmployeeByYear($this->employeeId, $currentYear);

        $employeeModel = new Employee(Database::getInstance());
        $employeeObject = $employeeModel->read($this->employeeId); // Assuming read(id) returns the employee object or false
        $employeeName = ($employeeObject && $employeeObject->first_name) ? htmlspecialchars($employeeObject->first_name) : "ผู้ใช้";

        if (empty($balancesData)) {
            $this->telegramService->sendMessage(
                $this->chatId,
                "คุณ {$employeeName} (ID: {$this->employeeId}) ยังไม่มียอดวันลาสำหรับปี {$currentYear} ค่ะ หรืออาจยังไม่มีการตั้งค่าประเภทวันลาที่สามารถตรวจสอบยอดได้"
            );
            return;
        }

        $responseText = "ยอดวันลาคงเหลือของคุณ {$employeeName} สำหรับปี {$currentYear} (ID: {$this->employeeId}):\n";
        $foundBalances = false;
        foreach ($balancesData as $balance) {
            // Based on LeaveBalance->getBalancesForEmployeeByYear current implementation, $balance is an array
            if (is_array($balance) && isset($balance['leave_type_name']) && isset($balance['balance_days'])) {
                $balanceDisplay = rtrim(rtrim(number_format((float) $balance['balance_days'], 2, '.', ''), '0'), '.');
                if ($balanceDisplay === '') {
                    $balanceDisplay = '0';
                }

                $typeName = htmlspecialchars($balance['leave_type_name']);
                $responseText .= "• {$typeName}: {$balanceDisplay} วัน\n";
                $foundBalances = true;
            }
            // This elseif is a fallback if the model changes to return objects with populated LeaveType
            elseif (is_object($balance) && isset($balance->leaveType) && isset($balance->leaveType->name) && isset($balance->balance_days)) {
                $balanceDisplay = rtrim(rtrim(number_format((float) $balance->balance_days, 2, '.', ''), '0'), '.');
                if ($balanceDisplay === '') {
                    $balanceDisplay = '0';
                }

                $typeName = htmlspecialchars($balance->leaveType->name);
                $responseText .= "• {$typeName}: {$balanceDisplay} วัน\n";
                $foundBalances = true;
            }
        }

        if (!$foundBalances) {
            $responseText = "ไม่พบข้อมูลยอดวันลาที่สามารถแสดงผลได้สำหรับปี {$currentYear} ค่ะ (คุณ {$employeeName}, ID: {$this->employeeId})";
        }

        $this->telegramService->sendMessage($this->chatId, $responseText);
    }
}