<?php

namespace App\Http\Controllers\HR;

use App\Http\Controllers\Controller;
use App\Models\Boards\File;
use App\Services\HR\BusinessIncomeEarnerService;
use Illuminate\Contracts\View\View;

class BusinessIncomeEarnerController extends Controller
{
    public function __construct(
        private BusinessIncomeEarnerService $service
    ) {}

    public function index(): View
    {
        $stats = $this->service->getStats();
        $departments = $this->service->getDepartments();

        return view('hr.business-income-earners.index', [
            'stats' => $stats,
            'departments' => $departments,
        ]);
    }

    public function create(): View
    {
        $departments = $this->service->getDepartments();
        $ranks = $this->service->getPositions('rank');
        $titles = $this->service->getPositions('title');

        return view('hr.business-income-earners.create', [
            'departments' => $departments,
            'ranks' => $ranks,
            'titles' => $titles,
            'banks' => config('banks', []),
        ]);
    }

    public function show(int $id): View
    {
        $earner = $this->service->getById($id);

        if (! $earner) {
            abort(404, '사업소득자 정보를 찾을 수 없습니다.');
        }

        $files = File::where('document_type', 'business_income_earner_profile')
            ->where('document_id', $earner->id)
            ->where('tenant_id', session('selected_tenant_id'))
            ->orderBy('created_at', 'desc')
            ->get();

        return view('hr.business-income-earners.show', [
            'earner' => $earner,
            'files' => $files,
        ]);
    }

    public function edit(int $id): View
    {
        $earner = $this->service->getById($id);

        if (! $earner) {
            abort(404, '사업소득자 정보를 찾을 수 없습니다.');
        }

        $departments = $this->service->getDepartments();
        $ranks = $this->service->getPositions('rank');
        $titles = $this->service->getPositions('title');

        $files = File::where('document_type', 'business_income_earner_profile')
            ->where('document_id', $earner->id)
            ->where('tenant_id', session('selected_tenant_id'))
            ->orderBy('created_at', 'desc')
            ->get();

        return view('hr.business-income-earners.edit', [
            'earner' => $earner,
            'departments' => $departments,
            'ranks' => $ranks,
            'titles' => $titles,
            'banks' => config('banks', []),
            'files' => $files,
        ]);
    }
}
