<?php

namespace App\Http\Controllers\Admin\Finance;

use App\Http\Controllers\Admin\PageController;
use App\Http\Requests\Finance\StorePayrollRunRequest;
use App\Models\PayrollRun;
use App\Models\Staff;
use App\Services\Finance\PayrollService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;

class PayrollController extends PageController
{
    public function __construct(
        private readonly PayrollService $payrollService,
    ) {}

    public function index(): View
    {
        $runs = PayrollRun::query()
            ->with('processedBy')
            ->latest('period_end')
            ->paginate(20);

        return $this->page('admin.payroll.index', [
            'crumbTitle' => 'Payroll',
            'crumbSub' => 'Salaries & deductions',
            'runs' => $runs,
        ]);
    }

    public function create(): View
    {
        return $this->page('admin.payroll.create', [
            'crumbTitle' => 'Payroll',
            'crumbSub' => 'Run payroll',
            'staffMembers' => Staff::query()
                ->where('status', 'active')
                ->whereNotNull('salary')
                ->orderBy('first_name')
                ->get(),
        ]);
    }

    public function store(StorePayrollRunRequest $request): RedirectResponse
    {
        $validated = $request->validated();

        $items = collect($validated['staff_ids'])->map(fn (int $staffId) => [
            'staff_id' => $staffId,
        ])->all();

        try {
            $run = $this->payrollService->run([
                'period_start' => $validated['period_start'],
                'period_end' => $validated['period_end'],
                'pay_date' => $validated['pay_date'],
                'processed_by' => Auth::id(),
            ], $items);
        } catch (\Throwable $e) {
            return back()->withInput()->with('error', $e->getMessage());
        }

        return $this->redirectWithSuccess(
            'finance.payroll.index',
            "Payroll run {$run->reference} posted successfully."
        );
    }
}
