<?php
declare(strict_types=1);

namespace App\Modules\HR\Services;

use App\Core\App;

/**
 * Overtime Calculation Service
 *
 * Egyptian Labour Law Art. 85:
 *   Day overtime: 135% of hourly rate
 *   Night overtime (7PM-7AM): 170% of hourly rate
 *
 * Hourly rate = (basic_salary + overtime-affecting allowances) / (working_days * hours_per_day)
 */
final class OvertimeService
{
    /**
     * Calculate overtime amount for given hours.
     *
     * @param string $basicSalary       Employee basic salary
     * @param string $overtimeBase      Total of salary components that affect overtime
     * @param int    $workingDaysMonth  Working days in the month
     * @param string $hoursPerDay       Expected hours per day
     * @param string $dayOvertimeHours  Day overtime hours
     * @param string $nightOvertimeHours Night overtime hours
     */
    public static function calculate(
        string $basicSalary,
        string $overtimeBase,
        int $workingDaysMonth,
        string $hoursPerDay,
        string $dayOvertimeHours,
        string $nightOvertimeHours
    ): array {
        $config = self::loadConfig();

        // Hourly rate = overtimeBase / (workingDays * hoursPerDay)
        $totalMonthlyHours = bcmul((string) $workingDaysMonth, $hoursPerDay, 2);
        if (bccomp($totalMonthlyHours, '0', 2) <= 0) {
            return [
                'hourly_rate'           => '0.00',
                'day_overtime_amount'   => '0.00',
                'night_overtime_amount' => '0.00',
                'total_overtime_amount' => '0.00',
                'day_hours'             => $dayOvertimeHours,
                'night_hours'           => $nightOvertimeHours,
            ];
        }

        $hourlyRate = bcdiv($overtimeBase, $totalMonthlyHours, 4);

        // Day overtime = hours * hourlyRate * dayMultiplier
        $dayRate = bcmul($hourlyRate, $config['day_multiplier'], 4);
        $dayAmount = bcmul($dayOvertimeHours, $dayRate, 2);

        // Night overtime = hours * hourlyRate * nightMultiplier
        $nightRate = bcmul($hourlyRate, $config['night_multiplier'], 4);
        $nightAmount = bcmul($nightOvertimeHours, $nightRate, 2);

        $totalAmount = bcadd($dayAmount, $nightAmount, 2);

        return [
            'hourly_rate'           => $hourlyRate,
            'day_rate'              => $dayRate,
            'night_rate'            => $nightRate,
            'day_overtime_amount'   => $dayAmount,
            'night_overtime_amount' => $nightAmount,
            'total_overtime_amount' => $totalAmount,
            'day_hours'             => $dayOvertimeHours,
            'night_hours'           => $nightOvertimeHours,
            'day_multiplier'        => $config['day_multiplier'],
            'night_multiplier'      => $config['night_multiplier'],
        ];
    }

    private static function loadConfig(): array
    {
        $db = App::getInstance()->db();
        $rows = $db->select(
            "SELECT config_key, config_value FROM system_config WHERE config_key LIKE 'hr.overtime.%'"
        );

        $cfg = [];
        foreach ($rows as $row) {
            $key = str_replace('hr.overtime.', '', $row['config_key']);
            $cfg[$key] = $row['config_value'];
        }

        return [
            'day_multiplier'   => $cfg['day_rate_multiplier'] ?? '1.35',
            'night_multiplier' => $cfg['night_rate_multiplier'] ?? '1.70',
            'night_start_hour' => (int) ($cfg['night_start_hour'] ?? 19),
            'night_end_hour'   => (int) ($cfg['night_end_hour'] ?? 7),
        ];
    }
}
