<?php

namespace Modules\Payroll\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\EmployeePayroll;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class PayrollController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $user = $request->user();
        $query = EmployeePayroll::withoutGlobalScopes()
            ->where('company_id', $user->company_id)
            ->where('user_id', $user->id)
            ->with(['payrollCycle', 'components']);

        if ($request->filled('year')) {
            $query->whereHas('payrollCycle', fn ($q) => $q->where('year', (int) $request->year));
        }
        if ($request->filled('month')) {
            $query->whereHas('payrollCycle', fn ($q) => $q->where('month', (int) $request->month));
        }

        $payrolls = $query->orderByDesc('id')->paginate($request->input('per_page', 12));

        return response()->json($payrolls);
    }

    public function myPayslip(Request $request): JsonResponse
    {
        $year = (int) $request->input('year', now()->year);
        $month = (int) $request->input('month', now()->month);
        $user = $request->user();

        $payroll = EmployeePayroll::withoutGlobalScopes()
            ->where('company_id', $user->company_id)
            ->where('user_id', $user->id)
            ->whereHas('payrollCycle', fn ($q) => $q->where('year', $year)->where('month', $month))
            ->with(['user', 'payrollCycle', 'components'])
            ->first();

        return response()->json($payroll ?? ['message' => 'Payslip not found for this period.']);
    }

    public function show(EmployeePayroll $payroll): JsonResponse
    {
        $user = auth()->user();
        if ((int) $payroll->company_id !== (int) $user->company_id) {
            abort(403);
        }
        if ((int) $payroll->user_id !== (int) $user->id && ! $user->isTenantManager()) {
            abort(403);
        }

        return response()->json($payroll->load(['user', 'payrollCycle', 'components']));
    }
}
