<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\GeneratePayrollRequest;
use App\Models\Payroll;
use App\Services\PayrollGenerationService;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class PayrollController extends Controller
{
    public function __construct(protected PayrollGenerationService $payrollService) {}

    public function index(): Response
    {
        return Inertia::render('Admin/Payroll/Index', [
            'payrolls' => Payroll::with(['generatedBy', 'approvedBy'])
                ->orderByDesc('created_at')
                ->get(),
        ]);
    }

    /**
     * Preview payroll for a given month — does not persist.
     */
    public function preview(Request $request): Response
    {
        $request->validate(['month' => ['required', 'date_format:Y-m']]);

        $month = $request->month.'-01';
        $preview = $this->payrollService->generatePreview($month);
        $existing = Payroll::whereDate('month', $preview['month'])->first();

        return Inertia::render('Admin/Payroll/Generate', [
            'preview' => $preview,
            'existingPayroll' => $existing,
            'month' => $request->month,
        ]);
    }

    /**
     * Persist snapshot payroll from confirmed preview.
     */
    public function generate(GeneratePayrollRequest $request)
    {
        $data = $request->validated();
        $month = $data['month'].'-01';

        try {
            $payroll = $this->payrollService->generate(
                $month,
                $data['employee_ids'],
                $request->user(),
                $data['adjustments'] ?? []
            );

            return redirect()->route('admin.payroll.show', $payroll)
                ->with('success', 'Payroll generated successfully.');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function show(Payroll $payroll): Response
    {
        return Inertia::render('Admin/Payroll/Show', [
            'payroll' => $payroll->load(['items.employee.employeeProfile', 'generatedBy', 'approvedBy']),
        ]);
    }

    public function approve(Request $request, Payroll $payroll)
    {
        try {
            $this->payrollService->approve($payroll, $request->user());

            return back()->with('success', 'Payroll approved and locked.');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function reject(Payroll $payroll)
    {
        try {
            $this->payrollService->reject($payroll, request()->user());

            return back()->with('success', 'Payroll rejected.');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function sendForApproval(Payroll $payroll)
    {
        if ($payroll->status !== 'draft') {
            return back()->with('error', 'Only draft payrolls can be sent for approval.');
        }

        $payroll->update(['status' => 'pending']);

        return back()->with('success', 'Payroll sent for approval.');
    }
}
