<?php

namespace App\Services;

use App\Models\Employee;
use App\Models\Attendance;
use App\Services\AttendanceService;

class PayrollService
{
    protected $attendanceService;

    public function __construct(AttendanceService $attendanceService)
    {
        $this->attendanceService = $attendanceService;
    }

    /**
     * Hitung total tunjangan yang diterima karyawan di bulan tertentu
     */
    public function calculateAllowances($employeeId, $year, $month, $branchId)
    {
        $employee = Employee::with('allowances.allowanceType')->findOrFail($employeeId);
        $daysEffectif = $this->attendanceService->getWorkingDays($year, $month, $branchId);
        
        // Hitung kehadiran riil
        $actualAttendance = Attendance::where('employee_id', $employeeId)
            ->whereYear('date', $year)
            ->whereMonth('date', $month)
            ->where('status', 'hadir')
            ->count();

        $totalAllowances = 0;

        foreach ($employee->allowances as $item) {
            $type = $item->allowanceType;
            $nominal = $item->amount;

            // Logika Perhitungan per Kategori
            if ($type->calculation_method === 'flat') {
                $totalAllowances += $nominal;
            } 
            elseif ($type->calculation_method === 'prorata_working_days') {
                // (Nominal / Hari Kerja Efektif) * Kehadiran Riil
                $totalAllowances += ($nominal / ($daysEffectif ?: 1)) * $actualAttendance;
            }
            elseif ($type->calculation_method === 'attendance_based') {
                // Contoh: Tunjangan makan per kehadiran
                $totalAllowances += ($nominal * $actualAttendance);
            }
        }

        return $totalAllowances;
    }
}