<?php

namespace App\Http\Controllers\Web\Payroll\V2;

use App\Http\Controllers\Controller;
use App\Models\PayrollCycle;
use App\Services\Payroll\V2\PayrollCycleService;
use Illuminate\Http\Request;

class PayrollCycleController extends Controller
{
    public function __construct(
        protected PayrollCycleService $cycleService
    ) {}

    public function index(Request $request)
    {
        $companyId = auth()->user()->company_id;
        if (! $companyId) {
            return redirect()->route('dashboard')->with('error', 'Company not found.');
        }
        $year = $request->filled('year') ? (int) $request->year : (int) date('Y');
        $year = max(2020, min(2030, $year));
        $monthStatuses = $this->cycleService->getMonthStatuses($companyId, $year);
        return view('payroll.v2.index', [
            'year' => $year,
            'monthStatuses' => $monthStatuses,
        ]);
    }

    public function run(Request $request, int $year, int $month)
    {
        $companyId = auth()->user()->company_id;
        if (! $companyId) {
            return redirect()->route('payroll.v2.index')->with('error', 'Company not found.');
        }
        $cycle = $this->cycleService->createOrOpen($companyId, $year, $month);
        return redirect()->route('payroll.v2.cycles.run', $cycle);
    }

    public function showRun(PayrollCycle $cycle)
    {
        $companyId = auth()->user()->company_id;
        if ($companyId && (int) $cycle->company_id !== $companyId) {
            abort(403);
        }
        $cycle->load(['employeePayrolls.user.department']);
        $cycle->employeePayrolls->load('components');
        return view('payroll.v2.run', [
            'cycle' => $cycle,
        ]);
    }
}
