<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
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 admin.
     */
    public function index(Request $request): Response
    {
        $pendingApprovals = LeaveRequest::with(['user', 'leaveType', 'manager'])
            ->where('status', 'pending_admin')
            ->orderBy('manager_approved_at', 'asc')
            ->get();

        return Inertia::render('Admin/Leave/Approvals', [
            'approvals' => $pendingApprovals,
        ]);
    }

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

        try {
            $this->leaveService->approveByAdmin($leaveRequest, $user, $request->input('comment'));

            return back()->with('success', 'Leave request fully approved.');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

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

        $user = $request->user();

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

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