<?php

namespace App\Modules\Payroll\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\Payroll\Models\PayrollEmployeeSnapshot;
use App\Modules\Payroll\Repositories\PayrollEmployeeSnapshotRepository;
use App\Modules\Payroll\Repositories\PayrollPeriodRepository;
use App\Modules\Payroll\Services\PayslipViewService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Illuminate\View\View;

class PayrollPayslipsPageController extends Controller
{
    use AuthorizesRequests;

    public function __construct(
        private readonly PayslipViewService $payslips,
        private readonly PayrollEmployeeSnapshotRepository $snapshots,
        private readonly PayrollPeriodRepository $periods,
    ) {}

    public function index(Request $request): View
    {
        $this->authorize('viewAny', PayrollEmployeeSnapshot::class);
        $tenant = $this->tenant();

        return view('pages.payroll.payslips.index', [
            'snapshots' => $this->snapshots->paginateFinalizedForIndex((int) $tenant->id, $request),
            'periods' => $this->periods->finalizedForTenant((int) $tenant->id),
        ]);
    }

    public function show(int $snapshot): View
    {
        $tenant = $this->tenant();
        $row = $this->payslips->buildAdminPayslip((int) $tenant->id, $snapshot);
        $this->authorize('view', $row);
        $breakdown = $this->payslips->breakdown($row);

        return view('pages.payroll.payslips.show', [
            'snapshot' => $row,
            'breakdown' => $breakdown,
        ]);
    }

    private function tenant(): Tenant
    {
        $t = auth()->user()?->tenant;
        abort_if($t === null, 403);

        return $t;
    }
}

