<?php

namespace App\Http\Controllers\Manager;

use App\Http\Controllers\Controller;
use App\Models\EmployeeProfile;
use App\Models\LeaveRequest;
use App\Services\LeaveService;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class LeaveApprovalController extends Controller
{
    public function __construct(protected LeaveService $leaveService) {}

    /**
     * Display pending leave approvals for manager.
     */
    public function index(Request $request): Response
    {
        $user = $request->user();

        if (! $user->isManager()) {
            abort(403, 'You are not authorized to access this page.');
        }

        $employeeIds = EmployeeProfile::where('manager_id', $user->id)->pluck('user_id');

        $pendingApprovals = LeaveRequest::with(['user', 'leaveType'])
            ->whereIn('user_id', $employeeIds)
            ->where('status', 'pending_manager')
            ->orderBy('created_at', 'desc')
            ->get();

        return Inertia::render('Employee/Manager/LeaveApprovals/Index', [
            'approvals' => $pendingApprovals,
        ]);
    }

    /**
     * Approve leave request by manager.
     */
    public function approve(Request $request, LeaveRequest $leaveRequest)
    {
        $user = $request->user();

        $success = $this->leaveService->approveByManager($leaveRequest, $user, $request->input('comment'));

        if (! $success) {
            return back()->with('error', 'Unable to approve leave request.');
        }

        return back()->with('success', 'Leave request approved and forwarded to Admin.');
    }

    /**
     * Reject leave request by manager.
     */
    public function reject(Request $request, LeaveRequest $leaveRequest)
    {
        $request->validate([
            'reason' => 'required|string|min:10',
        ]);

        $user = $request->user();

        $success = $this->leaveService->reject($leaveRequest, $user, $request->input('reason'), false);

        if (! $success) {
            return back()->with('error', 'Unable to reject leave request.');
        }

        return back()->with('success', 'Leave request rejected.');
    }
}
