<?php

namespace App\Http\Controllers\HR;

use App\Http\Controllers\Controller;
use App\Services\HR\BusinessIncomePaymentService;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class BusinessIncomePaymentController extends Controller
{
    private const ALLOWED_PAYROLL_USERS = ['이경호', '전진선', '김보곤'];

    public function __construct(
        private BusinessIncomePaymentService $service
    ) {}

    /**
     * 사업소득자 임금대장 페이지
     */
    public function index(Request $request): View|Response
    {
        if ($request->header('HX-Request')) {
            return response('', 200)->header('HX-Redirect', route('hr.business-income-payments.index'));
        }

        if (! in_array(auth()->user()->name, self::ALLOWED_PAYROLL_USERS)) {
            return view('hr.payrolls.restricted');
        }

        $year = $request->integer('year') ?: now()->year;
        $month = $request->integer('month') ?: now()->month;

        $earners = $this->service->getActiveEarners();
        $payments = $this->service->getPayments($year, $month);
        $stats = $this->service->getMonthlyStats($year, $month);

        $earnersForJs = $earners->map(fn ($e) => [
            'user_id' => $e->user_id,
            'business_name' => $e->business_name ?? ($e->user?->name ?? ''),
            'user_name' => $e->user?->name ?? '',
            'business_reg_number' => $e->business_registration_number ?? '',
        ])->values();

        return view('hr.business-income-payments.index', [
            'payments' => $payments,
            'earnersForJs' => $earnersForJs,
            'stats' => $stats,
            'year' => $year,
            'month' => $month,
        ]);
    }
}
